blob: 4e7e223ca0d7a8115cd9eb94fbc94afef612ad57 [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
Eric Christopher0a1301f2014-02-26 02:49:36 +000055SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
56 CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000058 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 != ".") {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000348 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
349 llvm::sys::path::append(MainFileDirSS, MainFileName);
350 MainFileName = MainFileDirSS.str();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000351 }
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 Christophere4200a22014-02-27 01:25:08 +0000385 TheCU = DBuilder.createCompileUnit(
386 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
387 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
388 DebugKind == CodeGenOptions::DebugLineTablesOnly
389 ? llvm::DIBuilder::LineTablesOnly
390 : llvm::DIBuilder::FullDebug);
Guy Benyei11169dd2012-12-18 14:30:41 +0000391}
392
393/// CreateType - Get the Basic type from the cache or create a new
394/// one if necessary.
395llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
396 unsigned Encoding = 0;
397 StringRef BTName;
398 switch (BT->getKind()) {
399#define BUILTIN_TYPE(Id, SingletonId)
400#define PLACEHOLDER_TYPE(Id, SingletonId) \
401 case BuiltinType::Id:
402#include "clang/AST/BuiltinTypes.def"
403 case BuiltinType::Dependent:
404 llvm_unreachable("Unexpected builtin type");
405 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000406 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 case BuiltinType::Void:
408 return llvm::DIType();
409 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000410 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000411 return ClassTy;
412 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413 "objc_class", TheCU,
414 getOrCreateMainFile(), 0);
415 return ClassTy;
416 case BuiltinType::ObjCId: {
417 // typedef struct objc_class *Class;
418 // typedef struct objc_object {
419 // Class isa;
420 // } *id;
421
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000422 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000423 return ObjTy;
424
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000425 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000426 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
427 "objc_class", TheCU,
428 getOrCreateMainFile(), 0);
429
430 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000431
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
433
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000434 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000435 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
436 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000437
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000438 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
439 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 return ObjTy;
441 }
442 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000443 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000444 return SelTy;
445 SelTy =
446 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
447 "objc_selector", TheCU, getOrCreateMainFile(),
448 0);
449 return SelTy;
450 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000451
452 case BuiltinType::OCLImage1d:
453 return getOrCreateStructPtrType("opencl_image1d_t",
454 OCLImage1dDITy);
455 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000456 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000457 OCLImage1dArrayDITy);
458 case BuiltinType::OCLImage1dBuffer:
459 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
460 OCLImage1dBufferDITy);
461 case BuiltinType::OCLImage2d:
462 return getOrCreateStructPtrType("opencl_image2d_t",
463 OCLImage2dDITy);
464 case BuiltinType::OCLImage2dArray:
465 return getOrCreateStructPtrType("opencl_image2d_array_t",
466 OCLImage2dArrayDITy);
467 case BuiltinType::OCLImage3d:
468 return getOrCreateStructPtrType("opencl_image3d_t",
469 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000470 case BuiltinType::OCLSampler:
471 return DBuilder.createBasicType("opencl_sampler_t",
472 CGM.getContext().getTypeSize(BT),
473 CGM.getContext().getTypeAlign(BT),
474 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000475 case BuiltinType::OCLEvent:
476 return getOrCreateStructPtrType("opencl_event_t",
477 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000478
Guy Benyei11169dd2012-12-18 14:30:41 +0000479 case BuiltinType::UChar:
480 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
481 case BuiltinType::Char_S:
482 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
483 case BuiltinType::Char16:
484 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
485 case BuiltinType::UShort:
486 case BuiltinType::UInt:
487 case BuiltinType::UInt128:
488 case BuiltinType::ULong:
489 case BuiltinType::WChar_U:
490 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
491 case BuiltinType::Short:
492 case BuiltinType::Int:
493 case BuiltinType::Int128:
494 case BuiltinType::Long:
495 case BuiltinType::WChar_S:
496 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
497 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
498 case BuiltinType::Half:
499 case BuiltinType::Float:
500 case BuiltinType::LongDouble:
501 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
502 }
503
504 switch (BT->getKind()) {
505 case BuiltinType::Long: BTName = "long int"; break;
506 case BuiltinType::LongLong: BTName = "long long int"; break;
507 case BuiltinType::ULong: BTName = "long unsigned int"; break;
508 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
509 default:
510 BTName = BT->getName(CGM.getLangOpts());
511 break;
512 }
513 // Bit size, align and offset of the type.
514 uint64_t Size = CGM.getContext().getTypeSize(BT);
515 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000516 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 DBuilder.createBasicType(BTName, Size, Align, Encoding);
518 return DbgTy;
519}
520
521llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
522 // Bit size, align and offset of the type.
523 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
524 if (Ty->isComplexIntegerType())
525 Encoding = llvm::dwarf::DW_ATE_lo_user;
526
527 uint64_t Size = CGM.getContext().getTypeSize(Ty);
528 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000529 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 DBuilder.createBasicType("complex", Size, Align, Encoding);
531
532 return DbgTy;
533}
534
535/// CreateCVRType - Get the qualified type from the cache or create
536/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000537llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000538 QualifierCollector Qc;
539 const Type *T = Qc.strip(Ty);
540
541 // Ignore these qualifiers for now.
542 Qc.removeObjCGCAttr();
543 Qc.removeAddressSpace();
544 Qc.removeObjCLifetime();
545
546 // We will create one Derived type for one qualifier and recurse to handle any
547 // additional ones.
548 unsigned Tag;
549 if (Qc.hasConst()) {
550 Tag = llvm::dwarf::DW_TAG_const_type;
551 Qc.removeConst();
552 } else if (Qc.hasVolatile()) {
553 Tag = llvm::dwarf::DW_TAG_volatile_type;
554 Qc.removeVolatile();
555 } else if (Qc.hasRestrict()) {
556 Tag = llvm::dwarf::DW_TAG_restrict_type;
557 Qc.removeRestrict();
558 } else {
559 assert(Qc.empty() && "Unknown type qualifier for debug info");
560 return getOrCreateType(QualType(T, 0), Unit);
561 }
562
David Blaikie99dab3b2013-09-04 22:03:57 +0000563 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000564
565 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
566 // CVR derived types.
567 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000568
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 return DbgTy;
570}
571
572llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
573 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000574
575 // The frontend treats 'id' as a typedef to an ObjCObjectType,
576 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
577 // debug info, we want to emit 'id' in both cases.
578 if (Ty->isObjCQualifiedIdType())
579 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000582 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 Ty->getPointeeType(), Unit);
584 return DbgTy;
585}
586
587llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
588 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000589 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 Ty->getPointeeType(), Unit);
591}
592
Manman Rene0064d82013-08-29 23:19:58 +0000593/// In C++ mode, types have linkage, so we can rely on the ODR and
594/// on their mangled names, if they're external.
595static SmallString<256>
596getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
597 llvm::DICompileUnit TheCU) {
598 SmallString<256> FullName;
599 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
600 // For now, only apply ODR with C++.
601 const TagDecl *TD = Ty->getDecl();
602 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
603 !TD->isExternallyVisible())
604 return FullName;
605 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
606 if (CGM.getTarget().getCXXABI().isMicrosoft())
607 return FullName;
608
609 // TODO: This is using the RTTI name. Is there a better way to get
610 // a unique string for a type?
611 llvm::raw_svector_ostream Out(FullName);
612 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
613 Out.flush();
614 return FullName;
615}
616
Guy Benyei11169dd2012-12-18 14:30:41 +0000617// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000618llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000619CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000620 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000621 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000622 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000623 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
625 unsigned Line = getLineNumber(RD->getLocation());
626 StringRef RDName = getClassName(RD);
627
628 unsigned Tag = 0;
629 if (RD->isStruct() || RD->isInterface())
630 Tag = llvm::dwarf::DW_TAG_structure_type;
631 else if (RD->isUnion())
632 Tag = llvm::dwarf::DW_TAG_union_type;
633 else {
634 assert(RD->isClass());
635 Tag = llvm::dwarf::DW_TAG_class_type;
636 }
637
638 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000639 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
640 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
641 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000642}
643
Guy Benyei11169dd2012-12-18 14:30:41 +0000644llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000645 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 QualType PointeeTy,
647 llvm::DIFile Unit) {
648 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
649 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000650 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000651
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 // Bit size, align and offset of the type.
653 // Size is always the size of a pointer. We can't use getTypeSize here
654 // because that does not return the correct value for references.
655 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000656 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
658
David Blaikie99dab3b2013-09-04 22:03:57 +0000659 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
660 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000661}
662
Eric Christopher0fdcb312013-05-16 00:52:20 +0000663llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
664 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000665 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000666 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000667 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
668 TheCU, getOrCreateMainFile(), 0);
669 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
670 Cache = DBuilder.createPointerType(Cache, Size);
671 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000672}
673
Guy Benyei11169dd2012-12-18 14:30:41 +0000674llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
675 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000676 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 return BlockLiteralGeneric;
678
679 SmallVector<llvm::Value *, 8> EltTys;
680 llvm::DIType FieldTy;
681 QualType FType;
682 uint64_t FieldSize, FieldOffset;
683 unsigned FieldAlign;
684 llvm::DIArray Elements;
685 llvm::DIType EltTy, DescTy;
686
687 FieldOffset = 0;
688 FType = CGM.getContext().UnsignedLongTy;
689 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
690 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
691
692 Elements = DBuilder.getOrCreateArray(EltTys);
693 EltTys.clear();
694
695 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
696 unsigned LineNo = getLineNumber(CurLoc);
697
698 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
699 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000700 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Bit size, align and offset of the type.
703 uint64_t Size = CGM.getContext().getTypeSize(Ty);
704
705 DescTy = DBuilder.createPointerType(EltTy, Size);
706
707 FieldOffset = 0;
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
710 FType = CGM.getContext().IntTy;
711 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
712 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
713 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
714 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
715
716 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
717 FieldTy = DescTy;
718 FieldSize = CGM.getContext().getTypeSize(Ty);
719 FieldAlign = CGM.getContext().getTypeAlign(Ty);
720 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
721 LineNo, FieldSize, FieldAlign,
722 FieldOffset, 0, FieldTy);
723 EltTys.push_back(FieldTy);
724
725 FieldOffset += FieldSize;
726 Elements = DBuilder.getOrCreateArray(EltTys);
727
728 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
729 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000730 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
733 return BlockLiteralGeneric;
734}
735
David Blaikie99dab3b2013-09-04 22:03:57 +0000736llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 // Typedefs are derived from some other type. If we have a typedef of a
738 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000739 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000740 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 return llvm::DIType();
742 // We don't set size information, but do specify where the typedef was
743 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000744 SourceLocation Loc = Ty->getDecl()->getLocation();
745 llvm::DIFile File = getOrCreateFile(Loc);
746 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000748
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 llvm::DIDescriptor TypedefContext =
750 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000751
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000753 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000754}
755
756llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
757 llvm::DIFile Unit) {
758 SmallVector<llvm::Value *, 16> EltTys;
759
760 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000761 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000762
763 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000764 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000765 if (isa<FunctionNoProtoType>(Ty))
766 EltTys.push_back(DBuilder.createUnspecifiedParameter());
767 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
769 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000770 if (FPT->isVariadic())
771 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 }
773
774 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
775 return DBuilder.createSubroutineType(Unit, EltTypeArray);
776}
777
778
Guy Benyei11169dd2012-12-18 14:30:41 +0000779llvm::DIType CGDebugInfo::createFieldType(StringRef name,
780 QualType type,
781 uint64_t sizeInBitsOverride,
782 SourceLocation loc,
783 AccessSpecifier AS,
784 uint64_t offsetInBits,
785 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000786 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 llvm::DIType debugType = getOrCreateType(type, tunit);
788
789 // Get the location for the field.
790 llvm::DIFile file = getOrCreateFile(loc);
791 unsigned line = getLineNumber(loc);
792
793 uint64_t sizeInBits = 0;
794 unsigned alignInBits = 0;
795 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000796 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797
798 if (sizeInBitsOverride)
799 sizeInBits = sizeInBitsOverride;
800 }
801
802 unsigned flags = 0;
803 if (AS == clang::AS_private)
804 flags |= llvm::DIDescriptor::FlagPrivate;
805 else if (AS == clang::AS_protected)
806 flags |= llvm::DIDescriptor::FlagProtected;
807
808 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
809 alignInBits, offsetInBits, flags, debugType);
810}
811
Eric Christopher91a31902013-01-16 01:22:32 +0000812/// CollectRecordLambdaFields - Helper for CollectRecordFields.
813void CGDebugInfo::
814CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
815 SmallVectorImpl<llvm::Value *> &elements,
816 llvm::DIType RecordTy) {
817 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
818 // has the name and the location of the variable so we should iterate over
819 // both concurrently.
820 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
821 RecordDecl::field_iterator Field = CXXDecl->field_begin();
822 unsigned fieldno = 0;
823 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
824 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
825 const LambdaExpr::Capture C = *I;
826 if (C.capturesVariable()) {
827 VarDecl *V = C.getCapturedVar();
828 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
829 StringRef VName = V->getName();
830 uint64_t SizeInBitsOverride = 0;
831 if (Field->isBitField()) {
832 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
833 assert(SizeInBitsOverride && "found named 0-width bitfield");
834 }
835 llvm::DIType fieldType
836 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
837 C.getLocation(), Field->getAccess(),
838 layout.getFieldOffset(fieldno), VUnit, RecordTy);
839 elements.push_back(fieldType);
840 } else {
841 // TODO: Need to handle 'this' in some way by probably renaming the
842 // this of the lambda class and having a field member of 'this' or
843 // by using AT_object_pointer for the function and having that be
844 // used as 'this' for semantic references.
845 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
846 FieldDecl *f = *Field;
847 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
848 QualType type = f->getType();
849 llvm::DIType fieldType
850 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
851 layout.getFieldOffset(fieldno), VUnit, RecordTy);
852
853 elements.push_back(fieldType);
854 }
855 }
856}
857
David Blaikie6943dea2013-08-20 01:28:15 +0000858/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000859llvm::DIDerivedType
860CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
861 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000862 // Create the descriptor for the static variable, with or without
863 // constant initializers.
864 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
865 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
866
Eric Christopher91a31902013-01-16 01:22:32 +0000867 unsigned LineNumber = getLineNumber(Var->getLocation());
868 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000869 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000870 if (Var->getInit()) {
871 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000872 if (Value) {
873 if (Value->isInt())
874 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
875 if (Value->isFloat())
876 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
877 }
Eric Christopher91a31902013-01-16 01:22:32 +0000878 }
879
880 unsigned Flags = 0;
881 AccessSpecifier Access = Var->getAccess();
882 if (Access == clang::AS_private)
883 Flags |= llvm::DIDescriptor::FlagPrivate;
884 else if (Access == clang::AS_protected)
885 Flags |= llvm::DIDescriptor::FlagProtected;
886
David Blaikieae019462013-08-15 22:50:29 +0000887 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
888 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000889 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000890 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000891}
892
893/// CollectRecordNormalField - Helper for CollectRecordFields.
894void CGDebugInfo::
895CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
896 llvm::DIFile tunit,
897 SmallVectorImpl<llvm::Value *> &elements,
898 llvm::DIType RecordTy) {
899 StringRef name = field->getName();
900 QualType type = field->getType();
901
902 // Ignore unnamed fields unless they're anonymous structs/unions.
903 if (name.empty() && !type->isRecordType())
904 return;
905
906 uint64_t SizeInBitsOverride = 0;
907 if (field->isBitField()) {
908 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
909 assert(SizeInBitsOverride && "found named 0-width bitfield");
910 }
911
912 llvm::DIType fieldType
913 = createFieldType(name, type, SizeInBitsOverride,
914 field->getLocation(), field->getAccess(),
915 OffsetInBits, tunit, RecordTy);
916
917 elements.push_back(fieldType);
918}
919
Guy Benyei11169dd2012-12-18 14:30:41 +0000920/// CollectRecordFields - A helper function to collect debug info for
921/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000922void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
923 llvm::DIFile tunit,
924 SmallVectorImpl<llvm::Value *> &elements,
925 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
927
Eric Christopher91a31902013-01-16 01:22:32 +0000928 if (CXXDecl && CXXDecl->isLambda())
929 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
930 else {
931 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000932
Eric Christopher91a31902013-01-16 01:22:32 +0000933 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000934 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000935
Eric Christopher91a31902013-01-16 01:22:32 +0000936 // Static and non-static members should appear in the same order as
937 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +0000938 for (const auto *I : record->decls())
939 if (const auto *V = dyn_cast<VarDecl>(I)) {
David Blaikiece763042013-08-20 21:49:21 +0000940 // Reuse the existing static member declaration if one exists
941 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
942 StaticDataMemberCache.find(V->getCanonicalDecl());
943 if (MI != StaticDataMemberCache.end()) {
944 assert(MI->second &&
945 "Static data member declaration should still exist");
946 elements.push_back(
947 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
948 } else
949 elements.push_back(CreateRecordStaticField(V, RecordTy));
Aaron Ballman629afae2014-03-07 19:56:05 +0000950 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000951 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
952 tunit, elements, RecordTy);
953
954 // Bump field number for next field.
955 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 }
958}
959
960/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
961/// function type is not updated to include implicit "this" pointer. Use this
962/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000963llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000964CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
965 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000966 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000967 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000968 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000969 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
970 Func, Unit);
971}
David Blaikie2aaf0652013-01-07 22:24:59 +0000972
David Blaikie469f0792013-05-22 23:22:42 +0000973llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000974 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000976 llvm::DIArray Args = llvm::DICompositeType(
977 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 assert (Args.getNumElements() && "Invalid number of arguments!");
979
980 SmallVector<llvm::Value *, 16> Elts;
981
982 // First element is always return type. For 'void' functions it is NULL.
983 Elts.push_back(Args.getElement(0));
984
David Blaikie2aaf0652013-01-07 22:24:59 +0000985 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000986 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000987 if (isa<ClassTemplateSpecializationDecl>(RD)) {
988 // Create pointer type directly in this case.
989 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
990 QualType PointeeTy = ThisPtrTy->getPointeeType();
991 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000992 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000993 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
994 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000995 llvm::DIType ThisPtrType =
996 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000997 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998 // TODO: This and the artificial type below are misleading, the
999 // types aren't artificial the argument is, but the current
1000 // metadata doesn't represent that.
1001 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1002 Elts.push_back(ThisPtrType);
1003 } else {
1004 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1005 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1006 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1007 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001008 }
1009
1010 // Copy rest of the arguments.
1011 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1012 Elts.push_back(Args.getElement(i));
1013
1014 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1015
Adrian Prantl0630eb72013-12-18 21:48:18 +00001016 unsigned Flags = 0;
1017 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1018 Flags |= llvm::DIDescriptor::FlagLValueReference;
1019 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1020 Flags |= llvm::DIDescriptor::FlagRValueReference;
1021
1022 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001023}
1024
Eric Christopherb2a008c2013-05-16 00:45:12 +00001025/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001026/// inside a function.
1027static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1028 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1029 return isFunctionLocalClass(NRD);
1030 if (isa<FunctionDecl>(RD->getDeclContext()))
1031 return true;
1032 return false;
1033}
1034
1035/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1036/// a single member function GlobalDecl.
1037llvm::DISubprogram
1038CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1039 llvm::DIFile Unit,
1040 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001041 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001042 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001043
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001045 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001046
1047 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1048 // make sense to give a single ctor/dtor a linkage name.
1049 StringRef MethodLinkageName;
1050 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1051 MethodLinkageName = CGM.getMangledName(Method);
1052
1053 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001054 llvm::DIFile MethodDefUnit;
1055 unsigned MethodLine = 0;
1056 if (!Method->isImplicit()) {
1057 MethodDefUnit = getOrCreateFile(Method->getLocation());
1058 MethodLine = getLineNumber(Method->getLocation());
1059 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001060
1061 // Collect virtual method info.
1062 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001063 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001064 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001065
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 if (Method->isVirtual()) {
1067 if (Method->isPure())
1068 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1069 else
1070 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001071
Guy Benyei11169dd2012-12-18 14:30:41 +00001072 // It doesn't make sense to give a virtual destructor a vtable index,
1073 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001074 // FIXME: Add proper support for debug info for virtual calls in
1075 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1076 // lookup if we have multiple or virtual inheritance.
1077 if (!isa<CXXDestructorDecl>(Method) &&
1078 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001079 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001080 ContainingType = RecordTy;
1081 }
1082
1083 unsigned Flags = 0;
1084 if (Method->isImplicit())
1085 Flags |= llvm::DIDescriptor::FlagArtificial;
1086 AccessSpecifier Access = Method->getAccess();
1087 if (Access == clang::AS_private)
1088 Flags |= llvm::DIDescriptor::FlagPrivate;
1089 else if (Access == clang::AS_protected)
1090 Flags |= llvm::DIDescriptor::FlagProtected;
1091 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1092 if (CXXC->isExplicit())
1093 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001094 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 dyn_cast<CXXConversionDecl>(Method)) {
1096 if (CXXC->isExplicit())
1097 Flags |= llvm::DIDescriptor::FlagExplicit;
1098 }
1099 if (Method->hasPrototype())
1100 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001101 if (Method->getRefQualifier() == RQ_LValue)
1102 Flags |= llvm::DIDescriptor::FlagLValueReference;
1103 if (Method->getRefQualifier() == RQ_RValue)
1104 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001105
1106 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1107 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001108 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001110 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 /* isDefinition=*/ false,
1112 Virtuality, VIndex, ContainingType,
1113 Flags, CGM.getLangOpts().Optimize, NULL,
1114 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001115
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1117
1118 return SP;
1119}
1120
1121/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001122/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001123/// a Record.
1124void CGDebugInfo::
1125CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1126 SmallVectorImpl<llvm::Value *> &EltTys,
1127 llvm::DIType RecordTy) {
1128
1129 // Since we want more than just the individual member decls if we
1130 // have templated functions iterate over every declaration to gather
1131 // the functions.
Aaron Ballman629afae2014-03-07 19:56:05 +00001132 for(const auto *I : RD->decls()) {
1133 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001134 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001135 // It may be associated with the declaration of the type & should be
1136 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001137 //
1138 // This situation can arise in the vtable-based debug info reduction where
1139 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001140 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1141 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001142 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001143 // If the member is implicit, lazily create it when we see the
1144 // definition, not before. (an ODR-used implicit default ctor that's
1145 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001146 if (!Method->isImplicit())
1147 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1148 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001149 EltTys.push_back(MI->second);
Aaron Ballman629afae2014-03-07 19:56:05 +00001150 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001151 // Add any template specializations that have already been seen. Like
1152 // implicit member functions, these may have been added to a declaration
1153 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001154 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1155 SE = FTD->spec_end();
1156 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001157 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1158 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1159 if (MI != SPCache.end())
1160 EltTys.push_back(MI->second);
1161 }
David Blaikie6943dea2013-08-20 01:28:15 +00001162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001164}
Guy Benyei11169dd2012-12-18 14:30:41 +00001165
Guy Benyei11169dd2012-12-18 14:30:41 +00001166/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001167/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001168/// a Record.
1169void CGDebugInfo::
1170CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1171 SmallVectorImpl<llvm::Value *> &EltTys,
1172 llvm::DIType RecordTy) {
1173
1174 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1175 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1176 BE = RD->bases_end(); BI != BE; ++BI) {
1177 unsigned BFlags = 0;
1178 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001179
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 const CXXRecordDecl *Base =
1181 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 if (BI->isVirtual()) {
1184 // virtual base offset offset is -ve. The code generator emits dwarf
1185 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001186 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001187 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1189 BFlags = llvm::DIDescriptor::FlagVirtual;
1190 } else
1191 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1192 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1193 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001194
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 AccessSpecifier Access = BI->getAccessSpecifier();
1196 if (Access == clang::AS_private)
1197 BFlags |= llvm::DIDescriptor::FlagPrivate;
1198 else if (Access == clang::AS_protected)
1199 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001200
1201 llvm::DIType DTy =
1202 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001203 getOrCreateType(BI->getType(), Unit),
1204 BaseOffset, BFlags);
1205 EltTys.push_back(DTy);
1206 }
1207}
1208
1209/// CollectTemplateParams - A helper function to collect template parameters.
1210llvm::DIArray CGDebugInfo::
1211CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001212 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001214 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1216 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001217 StringRef Name;
1218 if (TPList)
1219 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001220 switch (TA.getKind()) {
1221 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001222 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1223 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001224 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001225 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001226 } break;
1227 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1229 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001230 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001231 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001232 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1233 TemplateParams.push_back(TVP);
1234 } break;
1235 case TemplateArgument::Declaration: {
1236 const ValueDecl *D = TA.getAsDecl();
1237 bool InstanceMember = D->isCXXInstanceMember();
1238 QualType T = InstanceMember
1239 ? CGM.getContext().getMemberPointerType(
1240 D->getType(), cast<RecordDecl>(D->getDeclContext())
1241 ->getTypeForDecl())
1242 : CGM.getContext().getPointerType(D->getType());
1243 llvm::DIType TTy = getOrCreateType(T, Unit);
1244 llvm::Value *V = 0;
1245 // Variable pointer template parameters have a value that is the address
1246 // of the variable.
1247 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1248 V = CGM.GetAddrOfGlobalVar(VD);
1249 // Member function pointers have special support for building them, though
1250 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001251 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001252 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1253 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001254 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1255 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001256 // Member data pointers have special handling too to compute the fixed
1257 // offset within the object.
1258 if (isa<FieldDecl>(D)) {
1259 // These five lines (& possibly the above member function pointer
1260 // handling) might be able to be refactored to use similar code in
1261 // CodeGenModule::getMemberPointerConstant
1262 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1263 CharUnits chars =
1264 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1265 V = CGM.getCXXABI().EmitMemberDataPointer(
1266 cast<MemberPointerType>(T.getTypePtr()), chars);
1267 }
1268 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001269 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1270 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001271 TemplateParams.push_back(TVP);
1272 } break;
1273 case TemplateArgument::NullPtr: {
1274 QualType T = TA.getNullPtrType();
1275 llvm::DIType TTy = getOrCreateType(T, Unit);
1276 llvm::Value *V = 0;
1277 // Special case member data pointer null values since they're actually -1
1278 // instead of zero.
1279 if (const MemberPointerType *MPT =
1280 dyn_cast<MemberPointerType>(T.getTypePtr()))
1281 // But treat member function pointers as simple zero integers because
1282 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1283 // CodeGen grows handling for values of non-null member function
1284 // pointers then perhaps we could remove this special case and rely on
1285 // EmitNullMemberPointer for member function pointers.
1286 if (MPT->isMemberDataPointer())
1287 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1288 if (!V)
1289 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1290 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001291 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001292 TemplateParams.push_back(TVP);
1293 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001294 case TemplateArgument::Template: {
1295 llvm::DITemplateValueParameter TVP =
1296 DBuilder.createTemplateTemplateParameter(
1297 TheCU, Name, llvm::DIType(),
1298 TA.getAsTemplate().getAsTemplateDecl()
1299 ->getQualifiedNameAsString());
1300 TemplateParams.push_back(TVP);
1301 } break;
1302 case TemplateArgument::Pack: {
1303 llvm::DITemplateValueParameter TVP =
1304 DBuilder.createTemplateParameterPack(
1305 TheCU, Name, llvm::DIType(),
1306 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1307 TemplateParams.push_back(TVP);
1308 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001309 case TemplateArgument::Expression: {
1310 const Expr *E = TA.getAsExpr();
1311 QualType T = E->getType();
1312 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1313 assert(V && "Expression in template argument isn't constant");
1314 llvm::DIType TTy = getOrCreateType(T, Unit);
1315 llvm::DITemplateValueParameter TVP =
1316 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1317 V->stripPointerCasts());
1318 TemplateParams.push_back(TVP);
1319 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001320 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001321 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001322 case TemplateArgument::Null:
1323 llvm_unreachable(
1324 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 }
1326 }
1327 return DBuilder.getOrCreateArray(TemplateParams);
1328}
1329
1330/// CollectFunctionTemplateParams - A helper function to collect debug
1331/// info for function template parameters.
1332llvm::DIArray CGDebugInfo::
1333CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1334 if (FD->getTemplatedKind() ==
1335 FunctionDecl::TK_FunctionTemplateSpecialization) {
1336 const TemplateParameterList *TList =
1337 FD->getTemplateSpecializationInfo()->getTemplate()
1338 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001339 return CollectTemplateParams(
1340 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 }
1342 return llvm::DIArray();
1343}
1344
1345/// CollectCXXTemplateParams - A helper function to collect debug info for
1346/// template parameters.
1347llvm::DIArray CGDebugInfo::
1348CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1349 llvm::DIFile Unit) {
1350 llvm::PointerUnion<ClassTemplateDecl *,
1351 ClassTemplatePartialSpecializationDecl *>
1352 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001353
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1355 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1356 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1357 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001358 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001359}
1360
1361/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1362llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1363 if (VTablePtrType.isValid())
1364 return VTablePtrType;
1365
1366 ASTContext &Context = CGM.getContext();
1367
1368 /* Function type */
1369 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1370 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1371 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1372 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1373 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1374 "__vtbl_ptr_type");
1375 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1376 return VTablePtrType;
1377}
1378
1379/// getVTableName - Get vtable name for the given Class.
1380StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001381 // Copy the gdb compatible name on the side and use its reference.
1382 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001383}
1384
1385
1386/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1387/// debug info entry in EltTys vector.
1388void CGDebugInfo::
1389CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1390 SmallVectorImpl<llvm::Value *> &EltTys) {
1391 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1392
1393 // If there is a primary base then it will hold vtable info.
1394 if (RL.getPrimaryBase())
1395 return;
1396
1397 // If this class is not dynamic then there is not any vtable info to collect.
1398 if (!RD->isDynamicClass())
1399 return;
1400
1401 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1402 llvm::DIType VPTR
1403 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001404 0, Size, 0, 0,
1405 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 getOrCreateVTablePtrType(Unit));
1407 EltTys.push_back(VPTR);
1408}
1409
Eric Christopherb2a008c2013-05-16 00:45:12 +00001410/// getOrCreateRecordType - Emit record type's standalone debug info.
1411llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001413 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1415 return T;
1416}
1417
1418/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1419/// debug info.
1420llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001421 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001422 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001424 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 return T;
1426}
1427
David Blaikieb2e86eb2013-08-15 20:49:17 +00001428void CGDebugInfo::completeType(const RecordDecl *RD) {
1429 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1430 !CGM.getLangOpts().CPlusPlus)
1431 completeRequiredType(RD);
1432}
1433
1434void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie0856f662014-03-04 22:01:08 +00001435 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1436 return;
1437
David Blaikie6943dea2013-08-20 01:28:15 +00001438 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1439 if (CXXDecl->isDynamicClass())
1440 return;
1441
David Blaikieb2e86eb2013-08-15 20:49:17 +00001442 QualType Ty = CGM.getContext().getRecordType(RD);
1443 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001444 if (T && T.isForwardDecl())
1445 completeClassData(RD);
1446}
1447
1448void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1449 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001450 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001451 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001452 void* TyPtr = Ty.getAsOpaquePtr();
1453 if (CompletedTypeCache.count(TyPtr))
1454 return;
1455 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1456 assert(!Res.isForwardDecl());
1457 CompletedTypeCache[TyPtr] = Res;
1458 TypeCache[TyPtr] = Res;
1459}
1460
David Blaikie0e716b42014-03-03 23:48:23 +00001461static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1462 CXXRecordDecl::method_iterator End) {
1463 for (; I != End; ++I)
1464 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00001465 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1466 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00001467 return true;
1468 return false;
1469}
1470
1471static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1472 const RecordDecl *RD,
1473 const LangOptions &LangOpts) {
1474 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1475 return false;
1476
1477 if (!LangOpts.CPlusPlus)
1478 return false;
1479
1480 if (!RD->isCompleteDefinitionRequired())
1481 return true;
1482
1483 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1484
1485 if (!CXXDecl)
1486 return false;
1487
1488 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1489 return true;
1490
1491 TemplateSpecializationKind Spec = TSK_Undeclared;
1492 if (const ClassTemplateSpecializationDecl *SD =
1493 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1494 Spec = SD->getSpecializationKind();
1495
1496 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1497 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1498 CXXDecl->method_end()))
1499 return true;
1500
1501 return false;
1502}
1503
Guy Benyei11169dd2012-12-18 14:30:41 +00001504/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001505llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 RecordDecl *RD = Ty->getDecl();
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001507 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
David Blaikie0e716b42014-03-03 23:48:23 +00001508 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001509 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001510 T = getOrCreateRecordFwdDecl(
1511 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001512 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001513 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
David Blaikieb2e86eb2013-08-15 20:49:17 +00001515 return CreateTypeDefinition(Ty);
1516}
1517
1518llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1519 RecordDecl *RD = Ty->getDecl();
1520
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 // Get overall information about the record type for the debug info.
1522 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1523
1524 // Records and classes and unions can all be recursive. To handle them, we
1525 // first generate a debug descriptor for the struct as a forward declaration.
1526 // Then (if it is a definition) we go through and get debug info for all of
1527 // its members. Finally, we create a descriptor for the complete type (which
1528 // may refer to the forward decl if the struct is recursive) and replace all
1529 // uses of the forward declaration with the final definition.
1530
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001531 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001532 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001533 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001534
1535 if (FwdDecl.isForwardDecl())
1536 return FwdDecl;
1537
David Blaikieadfbf992013-08-18 16:55:33 +00001538 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1539 CollectContainingType(CXXDecl, FwdDecl);
1540
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001542 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1544
Adrian Prantla03a85a2013-03-06 22:03:30 +00001545 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1547
1548 // Convert all the elements.
1549 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001550 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001551
1552 // Note: The split of CXXDecl information here is intentional, the
1553 // gdb tests will depend on a certain ordering at printout. The debug
1554 // information offsets are still correct if we merge them all together
1555 // though.
1556 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1557 if (CXXDecl) {
1558 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1559 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1560 }
1561
Eric Christopher91a31902013-01-16 01:22:32 +00001562 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001564 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001566
1567 LexicalBlockStack.pop_back();
1568 RegionMap.erase(Ty->getDecl());
1569
1570 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001571 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001572
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001573 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1574 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001575}
1576
1577/// CreateType - get objective-c object type.
1578llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1579 llvm::DIFile Unit) {
1580 // Ignore protocols.
1581 return getOrCreateType(Ty->getBaseType(), Unit);
1582}
1583
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001584
1585/// \return true if Getter has the default name for the property PD.
1586static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1587 const ObjCMethodDecl *Getter) {
1588 assert(PD);
1589 if (!Getter)
1590 return true;
1591
1592 assert(Getter->getDeclName().isObjCZeroArgSelector());
1593 return PD->getName() ==
1594 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1595}
1596
1597/// \return true if Setter has the default name for the property PD.
1598static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1599 const ObjCMethodDecl *Setter) {
1600 assert(PD);
1601 if (!Setter)
1602 return true;
1603
1604 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001605 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001606 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1607}
1608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609/// CreateType - get objective-c interface type.
1610llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1611 llvm::DIFile Unit) {
1612 ObjCInterfaceDecl *ID = Ty->getDecl();
1613 if (!ID)
1614 return llvm::DIType();
1615
1616 // Get overall information about the record type for the debug info.
1617 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1618 unsigned Line = getLineNumber(ID->getLocation());
1619 unsigned RuntimeLang = TheCU.getLanguage();
1620
1621 // If this is just a forward declaration return a special forward-declaration
1622 // debug type since we won't be able to lay out the entire type.
1623 ObjCInterfaceDecl *Def = ID->getDefinition();
1624 if (!Def) {
1625 llvm::DIType FwdDecl =
1626 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001627 ID->getName(), TheCU, DefUnit, Line,
1628 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 return FwdDecl;
1630 }
1631
1632 ID = Def;
1633
1634 // Bit size, align and offset of the type.
1635 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1636 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1637
1638 unsigned Flags = 0;
1639 if (ID->getImplementation())
1640 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1641
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001642 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1644 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001645 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001646
1647 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1648 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001649 QualType QualTy = QualType(Ty, 0);
1650 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001652 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001653 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1655
1656 // Convert all the elements.
1657 SmallVector<llvm::Value *, 16> EltTys;
1658
1659 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1660 if (SClass) {
1661 llvm::DIType SClassTy =
1662 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1663 if (!SClassTy.isValid())
1664 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 llvm::DIType InhTag =
1667 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1668 EltTys.push_back(InhTag);
1669 }
1670
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001671 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1673 E = ID->prop_end(); I != E; ++I) {
1674 const ObjCPropertyDecl *PD = *I;
1675 SourceLocation Loc = PD->getLocation();
1676 llvm::DIFile PUnit = getOrCreateFile(Loc);
1677 unsigned PLine = getLineNumber(Loc);
1678 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1679 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1680 llvm::MDNode *PropertyNode =
1681 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001682 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001683 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001684 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001685 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 getSelectorName(PD->getSetterName()),
1687 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001688 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 EltTys.push_back(PropertyNode);
1690 }
1691
1692 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1693 unsigned FieldNo = 0;
1694 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1695 Field = Field->getNextIvar(), ++FieldNo) {
1696 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1697 if (!FieldTy.isValid())
1698 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001699
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 StringRef FieldName = Field->getName();
1701
1702 // Ignore unnamed fields.
1703 if (FieldName.empty())
1704 continue;
1705
1706 // Get the location for the field.
1707 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1708 unsigned FieldLine = getLineNumber(Field->getLocation());
1709 QualType FType = Field->getType();
1710 uint64_t FieldSize = 0;
1711 unsigned FieldAlign = 0;
1712
1713 if (!FType->isIncompleteArrayType()) {
1714
1715 // Bit size, align and offset of the type.
1716 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001717 ? Field->getBitWidthValue(CGM.getContext())
1718 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 FieldAlign = CGM.getContext().getTypeAlign(FType);
1720 }
1721
1722 uint64_t FieldOffset;
1723 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1724 // We don't know the runtime offset of an ivar if we're using the
1725 // non-fragile ABI. For bitfields, use the bit offset into the first
1726 // byte of storage of the bitfield. For other fields, use zero.
1727 if (Field->isBitField()) {
1728 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1729 CGM, ID, Field);
1730 FieldOffset %= CGM.getContext().getCharWidth();
1731 } else {
1732 FieldOffset = 0;
1733 }
1734 } else {
1735 FieldOffset = RL.getFieldOffset(FieldNo);
1736 }
1737
1738 unsigned Flags = 0;
1739 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1740 Flags = llvm::DIDescriptor::FlagProtected;
1741 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1742 Flags = llvm::DIDescriptor::FlagPrivate;
1743
1744 llvm::MDNode *PropertyNode = NULL;
1745 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001746 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1748 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001749 SourceLocation Loc = PD->getLocation();
1750 llvm::DIFile PUnit = getOrCreateFile(Loc);
1751 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1753 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1754 PropertyNode =
1755 DBuilder.createObjCProperty(PD->getName(),
1756 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001757 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001759 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 getSelectorName(PD->getSetterName()),
1761 PD->getPropertyAttributes(),
1762 getOrCreateType(PD->getType(), PUnit));
1763 }
1764 }
1765 }
1766 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1767 FieldLine, FieldSize, FieldAlign,
1768 FieldOffset, Flags, FieldTy,
1769 PropertyNode);
1770 EltTys.push_back(FieldTy);
1771 }
1772
1773 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001774 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001775
1776 // If the implementation is not yet set, we do not want to mark it
1777 // as complete. An implementation may declare additional
1778 // private ivars that we would miss otherwise.
1779 if (ID->getImplementation() == 0)
1780 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001781
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001783 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001784}
1785
1786llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1787 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1788 int64_t Count = Ty->getNumElements();
1789 if (Count == 0)
1790 // If number of elements are not known then this is an unbounded array.
1791 // Use Count == -1 to express such arrays.
1792 Count = -1;
1793
1794 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1795 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1796
1797 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1798 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1799
1800 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1801}
1802
1803llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1804 llvm::DIFile Unit) {
1805 uint64_t Size;
1806 uint64_t Align;
1807
1808 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1809 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1810 Size = 0;
1811 Align =
1812 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1813 } else if (Ty->isIncompleteArrayType()) {
1814 Size = 0;
1815 if (Ty->getElementType()->isIncompleteType())
1816 Align = 0;
1817 else
1818 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001819 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 Size = 0;
1821 Align = 0;
1822 } else {
1823 // Size and align of the whole array, not the element type.
1824 Size = CGM.getContext().getTypeSize(Ty);
1825 Align = CGM.getContext().getTypeAlign(Ty);
1826 }
1827
1828 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1829 // interior arrays, do we care? Why aren't nested arrays represented the
1830 // obvious/recursive way?
1831 SmallVector<llvm::Value *, 8> Subscripts;
1832 QualType EltTy(Ty, 0);
1833 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1834 // If the number of elements is known, then count is that number. Otherwise,
1835 // it's -1. This allows us to represent a subrange with an array of 0
1836 // elements, like this:
1837 //
1838 // struct foo {
1839 // int x[0];
1840 // };
1841 int64_t Count = -1; // Count == -1 is an unbounded array.
1842 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1843 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001844
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 // FIXME: Verify this is right for VLAs.
1846 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1847 EltTy = Ty->getElementType();
1848 }
1849
1850 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1851
Eric Christopherb2a008c2013-05-16 00:45:12 +00001852 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1854 SubscriptArray);
1855 return DbgTy;
1856}
1857
Eric Christopherb2a008c2013-05-16 00:45:12 +00001858llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001860 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 Ty, Ty->getPointeeType(), Unit);
1862}
1863
Eric Christopherb2a008c2013-05-16 00:45:12 +00001864llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001866 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 Ty, Ty->getPointeeType(), Unit);
1868}
1869
Eric Christopherb2a008c2013-05-16 00:45:12 +00001870llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001872 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1873 if (!Ty->getPointeeType()->isFunctionType())
1874 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001875 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001876
1877 const FunctionProtoType *FPT =
1878 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001879 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001880 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1881 FPT->getTypeQuals())),
1882 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001883}
1884
Eric Christopherb2a008c2013-05-16 00:45:12 +00001885llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 llvm::DIFile U) {
1887 // Ignore the atomic wrapping
1888 // FIXME: What is the correct representation?
1889 return getOrCreateType(Ty->getValueType(), U);
1890}
1891
1892/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001893llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001894 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 uint64_t Size = 0;
1896 uint64_t Align = 0;
1897 if (!ED->getTypeForDecl()->isIncompleteType()) {
1898 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1899 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1900 }
1901
Manman Rene0064d82013-08-29 23:19:58 +00001902 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1903
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 // If this is just a forward declaration, construct an appropriately
1905 // marked node and just return it.
1906 if (!ED->getDefinition()) {
1907 llvm::DIDescriptor EDContext;
1908 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1909 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1910 unsigned Line = getLineNumber(ED->getLocation());
1911 StringRef EDName = ED->getName();
1912 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1913 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001914 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 }
1916
1917 // Create DIEnumerator elements for each enumerator.
1918 SmallVector<llvm::Value *, 16> Enumerators;
1919 ED = ED->getDefinition();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001920 for (const auto *Enum : ED->enumerators()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 Enumerators.push_back(
1922 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001923 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001924 }
1925
1926 // Return a CompositeType for the enum itself.
1927 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1928
1929 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1930 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001931 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001933 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001935 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001936 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1937 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001938 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 return DbgTy;
1940}
1941
David Blaikie05491062013-01-21 04:37:12 +00001942static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1943 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001944 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001945 Qualifiers InnerQuals = T.getLocalQualifiers();
1946 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1947 // that is already there.
1948 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1949 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001950 QualType LastT = T;
1951 switch (T->getTypeClass()) {
1952 default:
David Blaikie05491062013-01-21 04:37:12 +00001953 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 case Type::TemplateSpecialization:
1955 T = cast<TemplateSpecializationType>(T)->desugar();
1956 break;
1957 case Type::TypeOfExpr:
1958 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1959 break;
1960 case Type::TypeOf:
1961 T = cast<TypeOfType>(T)->getUnderlyingType();
1962 break;
1963 case Type::Decltype:
1964 T = cast<DecltypeType>(T)->getUnderlyingType();
1965 break;
1966 case Type::UnaryTransform:
1967 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1968 break;
1969 case Type::Attributed:
1970 T = cast<AttributedType>(T)->getEquivalentType();
1971 break;
1972 case Type::Elaborated:
1973 T = cast<ElaboratedType>(T)->getNamedType();
1974 break;
1975 case Type::Paren:
1976 T = cast<ParenType>(T)->getInnerType();
1977 break;
David Blaikie05491062013-01-21 04:37:12 +00001978 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001979 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001980 break;
1981 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001982 QualType DT = cast<AutoType>(T)->getDeducedType();
1983 if (DT.isNull())
1984 return T;
1985 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001986 break;
1987 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001988
Guy Benyei11169dd2012-12-18 14:30:41 +00001989 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001990 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001991 } while (true);
1992}
1993
Eric Christopher0fdcb312013-05-16 00:52:20 +00001994/// getType - Get the type from the cache or return null type if it doesn't
1995/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001996llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1997
1998 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001999 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002000
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00002002 if (Ty->getTypeClass() == Type::ObjCInterface) {
2003 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2004 if (V)
2005 return llvm::DIType(cast<llvm::MDNode>(V));
2006 else return llvm::DIType();
2007 }
2008
Guy Benyei11169dd2012-12-18 14:30:41 +00002009 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2010 TypeCache.find(Ty.getAsOpaquePtr());
2011 if (it != TypeCache.end()) {
2012 // Verify that the debug info still exists.
2013 if (llvm::Value *V = it->second)
2014 return llvm::DIType(cast<llvm::MDNode>(V));
2015 }
2016
2017 return llvm::DIType();
2018}
2019
2020/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2021/// doesn't exist.
2022llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2023
2024 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002025 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002026
2027 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002028 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002029 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2030 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002031 if (it != CompletedTypeCache.end())
2032 V = it->second;
2033 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002034 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 }
2036
Adrian Prantla03a85a2013-03-06 22:03:30 +00002037 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002038 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002039}
2040
David Blaikie0e716b42014-03-03 23:48:23 +00002041void CGDebugInfo::completeTemplateDefinition(
2042 const ClassTemplateSpecializationDecl &SD) {
David Blaikie0856f662014-03-04 22:01:08 +00002043 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2044 return;
2045
David Blaikie0e716b42014-03-03 23:48:23 +00002046 completeClassData(&SD);
2047 // In case this type has no member function definitions being emitted, ensure
2048 // it is retained
2049 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2050}
2051
Adrian Prantl73409ce2013-03-11 18:33:46 +00002052/// getCachedInterfaceTypeOrNull - Get the type from the interface
2053/// cache, unless it needs to regenerated. Otherwise return null.
2054llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2055 // Is there a cached interface that hasn't changed?
2056 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2057 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2058
2059 if (it1 != ObjCInterfaceCache.end())
2060 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2061 if (Checksum(Decl) == it1->second.second)
2062 // Return cached forward declaration.
2063 return it1->second.first;
2064
2065 return 0;
2066}
Guy Benyei11169dd2012-12-18 14:30:41 +00002067
2068/// getOrCreateType - Get the type from the cache or create a new
2069/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002070llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002071 if (Ty.isNull())
2072 return llvm::DIType();
2073
2074 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002075 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002076
David Blaikie99dab3b2013-09-04 22:03:57 +00002077 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 return T;
2079
2080 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002081 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002082 void* TyPtr = Ty.getAsOpaquePtr();
2083
2084 // And update the type cache.
2085 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002086
David Blaikie6a723442013-08-15 21:21:19 +00002087 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2088 // into the cache - but getTypeOrNull has a special case for cached interface
2089 // types. We should probably just pull that out as a special case for the
2090 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002092 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002093 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2094 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2095 // Interface types may have elements added to them by a
2096 // subsequent implementation or extension, so we keep them in
2097 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002098 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002099 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002100 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2101 if (V.first)
2102 return llvm::DIType(cast<llvm::MDNode>(V.first));
2103 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2104 Decl->getName(), TheCU, Unit,
2105 getLineNumber(Decl->getLocation()),
2106 TheCU.getLanguage());
2107 // Store the forward declaration in the cache.
2108 V.first = TC;
2109 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002110
David Blaikie8e5939b2013-05-21 18:29:40 +00002111 // Register the type for replacement in finalize().
2112 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2113
Adrian Prantl73409ce2013-03-11 18:33:46 +00002114 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002115 }
2116
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002118 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002119
2120 return Res;
2121}
2122
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002123/// Currently the checksum of an interface includes the number of
2124/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002125unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002126 // The assumption is that the number of ivars can only increase
2127 // monotonically, so it is safe to just use their current number as
2128 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002129 unsigned Sum = 0;
2130 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2131 Ivar != 0; Ivar = Ivar->getNextIvar())
2132 ++Sum;
2133
2134 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002135}
2136
2137ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2138 switch (Ty->getTypeClass()) {
2139 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002140 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2141 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002142 case Type::ObjCInterface:
2143 return cast<ObjCInterfaceType>(Ty)->getDecl();
2144 default:
2145 return 0;
2146 }
2147}
2148
Guy Benyei11169dd2012-12-18 14:30:41 +00002149/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002150llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 // Handle qualifiers, which recursively handles what they refer to.
2152 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002153 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002154
2155 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002156
Guy Benyei11169dd2012-12-18 14:30:41 +00002157 // Work out details of type.
2158 switch (Ty->getTypeClass()) {
2159#define TYPE(Class, Base)
2160#define ABSTRACT_TYPE(Class, Base)
2161#define NON_CANONICAL_TYPE(Class, Base)
2162#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2163#include "clang/AST/TypeNodes.def"
2164 llvm_unreachable("Dependent types cannot show up in debug information");
2165
2166 case Type::ExtVector:
2167 case Type::Vector:
2168 return CreateType(cast<VectorType>(Ty), Unit);
2169 case Type::ObjCObjectPointer:
2170 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2171 case Type::ObjCObject:
2172 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2173 case Type::ObjCInterface:
2174 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2175 case Type::Builtin:
2176 return CreateType(cast<BuiltinType>(Ty));
2177 case Type::Complex:
2178 return CreateType(cast<ComplexType>(Ty));
2179 case Type::Pointer:
2180 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002181 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002182 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002183 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002184 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002185 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002186 case Type::BlockPointer:
2187 return CreateType(cast<BlockPointerType>(Ty), Unit);
2188 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002189 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002191 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002193 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002194 case Type::FunctionProto:
2195 case Type::FunctionNoProto:
2196 return CreateType(cast<FunctionType>(Ty), Unit);
2197 case Type::ConstantArray:
2198 case Type::VariableArray:
2199 case Type::IncompleteArray:
2200 return CreateType(cast<ArrayType>(Ty), Unit);
2201
2202 case Type::LValueReference:
2203 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2204 case Type::RValueReference:
2205 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2206
2207 case Type::MemberPointer:
2208 return CreateType(cast<MemberPointerType>(Ty), Unit);
2209
2210 case Type::Atomic:
2211 return CreateType(cast<AtomicType>(Ty), Unit);
2212
2213 case Type::Attributed:
2214 case Type::TemplateSpecialization:
2215 case Type::Elaborated:
2216 case Type::Paren:
2217 case Type::SubstTemplateTypeParm:
2218 case Type::TypeOfExpr:
2219 case Type::TypeOf:
2220 case Type::Decltype:
2221 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002222 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002224 case Type::Auto:
2225 Diag = "auto";
2226 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002228
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 assert(Diag && "Fall through without a diagnostic?");
2230 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2231 "debug information for %0 is not yet supported");
2232 CGM.getDiags().Report(DiagID)
2233 << Diag;
2234 return llvm::DIType();
2235}
2236
2237/// getOrCreateLimitedType - Get the type from the cache or create a new
2238/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002239llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002240 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002241 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002242
David Blaikie8d5e1282013-08-20 21:03:29 +00002243 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002244
2245 // We may have cached a forward decl when we could have created
2246 // a non-forward decl. Go ahead and create a non-forward decl
2247 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002248 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002249
2250 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002251 llvm::DICompositeType Res = CreateLimitedType(Ty);
2252
2253 // Propagate members from the declaration to the definition
2254 // CreateType(const RecordType*) will overwrite this with the members in the
2255 // correct order if the full type is needed.
2256 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002257
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002258 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002259 ReplaceMap.push_back(
2260 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002261
2262 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002263 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 return Res;
2265}
2266
2267// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002268llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002270
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 // Get overall information about the record type for the debug info.
2272 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2273 unsigned Line = getLineNumber(RD->getLocation());
2274 StringRef RDName = getClassName(RD);
2275
Eric Christopher07429ff2013-10-15 21:22:34 +00002276 llvm::DIDescriptor RDContext =
2277 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002278
David Blaikied2785892013-08-18 17:36:19 +00002279 // If we ended up creating the type during the context chain construction,
2280 // just return that.
2281 // FIXME: this could be dealt with better if the type was recorded as
2282 // completed before we started this (see the CompletedTypeCache usage in
2283 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2284 // be pushed to before context creation, but after it was known to be
2285 // destined for completion (might still have an issue if this caller only
2286 // required a declaration but the context construction ended up creating a
2287 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002288 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2289 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002290 return T;
2291
Adrian Prantl381e7552014-02-04 21:29:50 +00002292 // If this is just a forward or incomplete declaration, construct an
2293 // appropriately marked node and just return it.
2294 const RecordDecl *D = RD->getDefinition();
2295 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002296 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002297
2298 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2299 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002300 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002301
Manman Rene0064d82013-08-29 23:19:58 +00002302 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2303
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 if (RD->isUnion())
2305 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002306 Size, Align, 0, llvm::DIArray(), 0,
2307 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 else if (RD->isClass()) {
2309 // FIXME: This could be a struct type giving a default visibility different
2310 // than C++ class type, but needs llvm metadata changes first.
2311 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002312 Size, Align, 0, 0, llvm::DIType(),
2313 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002314 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 } else
2316 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002317 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002318 llvm::DIArray(), 0, llvm::DIType(),
2319 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002320
2321 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002322 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323
David Blaikieadfbf992013-08-18 16:55:33 +00002324 if (const ClassTemplateSpecializationDecl *TSpecial =
2325 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2326 RealDecl.setTypeArray(llvm::DIArray(),
2327 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002328 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329}
2330
David Blaikieadfbf992013-08-18 16:55:33 +00002331void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2332 llvm::DICompositeType RealDecl) {
2333 // A class's primary base or the class itself contains the vtable.
2334 llvm::DICompositeType ContainingType;
2335 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2336 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002337 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002338 while (1) {
2339 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2340 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2341 if (PBT && !BRL.isPrimaryBaseVirtual())
2342 PBase = PBT;
2343 else
2344 break;
2345 }
2346 ContainingType = llvm::DICompositeType(
2347 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2348 getOrCreateFile(RD->getLocation())));
2349 } else if (RD->isDynamicClass())
2350 ContainingType = RealDecl;
2351
2352 RealDecl.setContainingType(ContainingType);
2353}
2354
Guy Benyei11169dd2012-12-18 14:30:41 +00002355/// CreateMemberType - Create new member and increase Offset by FType's size.
2356llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2357 StringRef Name,
2358 uint64_t *Offset) {
2359 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2360 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2361 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2362 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2363 FieldSize, FieldAlign,
2364 *Offset, 0, FieldTy);
2365 *Offset += FieldSize;
2366 return Ty;
2367}
2368
David Blaikiebd483762013-05-20 04:58:53 +00002369llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2370 // We only need a declaration (not a definition) of the type - so use whatever
2371 // we would otherwise do to get a type for a pointee. (forward declarations in
2372 // limited debug info, full definitions (if the type definition is available)
2373 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002374 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2375 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002376 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002377 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2378 // This doesn't handle providing declarations (for functions or variables) for
2379 // entities without definitions in this TU, nor when the definition proceeds
2380 // the call to this function.
2381 // FIXME: This should be split out into more specific maps with support for
2382 // emitting forward declarations and merging definitions with declarations,
2383 // the same way as we do for types.
2384 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2385 DeclCache.find(D->getCanonicalDecl());
2386 if (I == DeclCache.end())
2387 return llvm::DIDescriptor();
2388 llvm::Value *V = I->second;
2389 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2390}
2391
Guy Benyei11169dd2012-12-18 14:30:41 +00002392/// getFunctionDeclaration - Return debug info descriptor to describe method
2393/// declaration for the given method definition.
2394llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002395 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2396 return llvm::DISubprogram();
2397
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2399 if (!FD) return llvm::DISubprogram();
2400
2401 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002402 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002403
2404 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2405 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002406 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002407 if (const CXXMethodDecl *MD =
2408 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002409 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002410 llvm::DISubprogram SP =
2411 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002412 return SP;
2413 }
2414 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 if (MI != SPCache.end()) {
2416 llvm::Value *V = MI->second;
2417 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002418 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 return SP;
2420 }
2421
Aaron Ballman86c93902014-03-06 23:45:36 +00002422 for (auto NextFD : FD->redecls()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2424 MI = SPCache.find(NextFD->getCanonicalDecl());
2425 if (MI != SPCache.end()) {
2426 llvm::Value *V = MI->second;
2427 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002428 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 return SP;
2430 }
2431 }
2432 return llvm::DISubprogram();
2433}
2434
2435// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2436// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002437llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2438 QualType FnType,
2439 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002440 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2441 // Create fake but valid subroutine type. Otherwise
2442 // llvm::DISubprogram::Verify() would return false, and
2443 // subprogram DIE will miss DW_AT_decl_file and
2444 // DW_AT_decl_line fields.
2445 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002446
2447 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2448 return getOrCreateMethodType(Method, F);
2449 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2450 // Add "self" and "_cmd"
2451 SmallVector<llvm::Value *, 16> Elts;
2452
2453 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002454 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002455
2456 // Replace the instancetype keyword with the actual type.
2457 if (ResultTy == CGM.getContext().getObjCInstanceType())
2458 ResultTy = CGM.getContext().getPointerType(
2459 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2460
Adrian Prantl7bec9032013-05-10 21:08:31 +00002461 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002463 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2464 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2465 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 // "_cmd" pointer is always second argument.
2467 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2468 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2469 // Get rest of the arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002470 for (const auto *PI : OMethod->params())
2471 Elts.push_back(getOrCreateType(PI->getType(), F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002472
2473 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2474 return DBuilder.createSubroutineType(F, EltTypeArray);
2475 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002476
Adrian Prantl800faef2014-02-25 23:42:18 +00002477 // Handle variadic function types; they need an additional
2478 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002479 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2480 if (FD->isVariadic()) {
2481 SmallVector<llvm::Value *, 16> EltTys;
2482 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2483 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2484 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2485 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2486 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2487 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2488 return DBuilder.createSubroutineType(F, EltTypeArray);
2489 }
2490
David Blaikie469f0792013-05-22 23:22:42 +00002491 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002492}
2493
2494/// EmitFunctionStart - Constructs the debug code for entering a function.
2495void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2496 llvm::Function *Fn,
2497 CGBuilderTy &Builder) {
2498
2499 StringRef Name;
2500 StringRef LinkageName;
2501
2502 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2503
2504 const Decl *D = GD.getDecl();
2505 // Function may lack declaration in source code if it is created by Clang
2506 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2507 bool HasDecl = (D != 0);
2508 // Use the location of the declaration.
2509 SourceLocation Loc;
2510 if (HasDecl)
2511 Loc = D->getLocation();
2512
2513 unsigned Flags = 0;
2514 llvm::DIFile Unit = getOrCreateFile(Loc);
2515 llvm::DIDescriptor FDContext(Unit);
2516 llvm::DIArray TParamsArray;
2517 if (!HasDecl) {
2518 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002519 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2521 // If there is a DISubprogram for this function available then use it.
2522 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2523 FI = SPCache.find(FD->getCanonicalDecl());
2524 if (FI != SPCache.end()) {
2525 llvm::Value *V = FI->second;
2526 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2527 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2528 llvm::MDNode *SPN = SP;
2529 LexicalBlockStack.push_back(SPN);
2530 RegionMap[D] = llvm::WeakVH(SP);
2531 return;
2532 }
2533 }
2534 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002535 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 if (FD->hasPrototype()) {
2537 LinkageName = CGM.getMangledName(GD);
2538 Flags |= llvm::DIDescriptor::FlagPrototyped;
2539 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002540 // No need to replicate the linkage name if it isn't different from the
2541 // subprogram name, no need to have it at all unless coverage is enabled or
2542 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002544 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2545 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002546 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 LinkageName = StringRef();
2548
Eric Christopher75e17682013-05-16 00:45:23 +00002549 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002551 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 FDContext = getOrCreateNameSpace(NSDecl);
2553 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002554 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2555 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002556
2557 // Collect template parameters.
2558 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2559 }
2560 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2561 Name = getObjCMethodName(OMD);
2562 Flags |= llvm::DIDescriptor::FlagPrototyped;
2563 } else {
2564 // Use llvm function name.
2565 Name = Fn->getName();
2566 Flags |= llvm::DIDescriptor::FlagPrototyped;
2567 }
2568 if (!Name.empty() && Name[0] == '\01')
2569 Name = Name.substr(1);
2570
2571 unsigned LineNo = getLineNumber(Loc);
2572 if (!HasDecl || D->isImplicit())
2573 Flags |= llvm::DIDescriptor::FlagArtificial;
2574
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002575 llvm::DISubprogram SP =
2576 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2577 getOrCreateFunctionType(D, FnType, Unit),
2578 Fn->hasInternalLinkage(), true /*definition*/,
2579 getLineNumber(CurLoc), Flags,
2580 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2581 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002582 if (HasDecl)
2583 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002584
2585 // Push function on region stack.
2586 llvm::MDNode *SPN = SP;
2587 LexicalBlockStack.push_back(SPN);
2588 if (HasDecl)
2589 RegionMap[D] = llvm::WeakVH(SP);
2590}
2591
2592/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002593/// information in the source file. If the location is invalid, the
2594/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002595void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002596 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 // Update our current location
2598 setLocation(Loc);
2599
2600 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2601
2602 // Don't bother if things are the same as last time.
2603 SourceManager &SM = CGM.getContext().getSourceManager();
2604 if (CurLoc == PrevLoc ||
2605 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2606 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002607 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2608 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2609 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002611
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 // Update last state.
2613 PrevLoc = CurLoc;
2614
Adrian Prantle83b1302014-01-07 22:05:52 +00002615 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002616 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2617 (getLineNumber(CurLoc),
2618 getColumnNumber(CurLoc, ForceColumnInfo),
2619 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002620}
2621
2622/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2623/// the stack.
2624void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2625 llvm::DIDescriptor D =
2626 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2627 llvm::DIDescriptor() :
2628 llvm::DIDescriptor(LexicalBlockStack.back()),
2629 getOrCreateFile(CurLoc),
2630 getLineNumber(CurLoc),
Diego Novilloe6d398182014-03-03 18:53:32 +00002631 getColumnNumber(CurLoc),
2632 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 llvm::MDNode *DN = D;
2634 LexicalBlockStack.push_back(DN);
2635}
2636
2637/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2638/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002639void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2640 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 // Set our current location.
2642 setLocation(Loc);
2643
2644 // Create a new lexical block and push it on the stack.
2645 CreateLexicalBlock(Loc);
2646
2647 // Emit a line table change for the current location inside the new scope.
2648 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2649 getColumnNumber(Loc),
2650 LexicalBlockStack.back()));
2651}
2652
2653/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2654/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002655void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2656 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2658
2659 // Provide an entry in the line table for the end of the block.
2660 EmitLocation(Builder, Loc);
2661
2662 LexicalBlockStack.pop_back();
2663}
2664
2665/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2666void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2667 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2668 unsigned RCount = FnBeginRegionCount.back();
2669 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2670
2671 // Pop all regions for this function.
2672 while (LexicalBlockStack.size() != RCount)
2673 EmitLexicalBlockEnd(Builder, CurLoc);
2674 FnBeginRegionCount.pop_back();
2675}
2676
Eric Christopherb2a008c2013-05-16 00:45:12 +00002677// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002678// See BuildByRefType.
2679llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2680 uint64_t *XOffset) {
2681
2682 SmallVector<llvm::Value *, 5> EltTys;
2683 QualType FType;
2684 uint64_t FieldSize, FieldOffset;
2685 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002686
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002688 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002689
2690 FieldOffset = 0;
2691 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2692 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2693 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2694 FType = CGM.getContext().IntTy;
2695 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2696 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2697
2698 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2699 if (HasCopyAndDispose) {
2700 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2701 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2702 &FieldOffset));
2703 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2704 &FieldOffset));
2705 }
2706 bool HasByrefExtendedLayout;
2707 Qualifiers::ObjCLifetime Lifetime;
2708 if (CGM.getContext().getByrefLifetime(Type,
2709 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002710 && HasByrefExtendedLayout) {
2711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 EltTys.push_back(CreateMemberType(Unit, FType,
2713 "__byref_variable_layout",
2714 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002715 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002716
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2718 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002719 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002720 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2722 CharUnits AlignedOffsetInBytes
2723 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2724 CharUnits NumPaddingBytes
2725 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002726
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 if (NumPaddingBytes.isPositive()) {
2728 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2729 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2730 pad, ArrayType::Normal, 0);
2731 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2732 }
2733 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002734
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 FType = Type;
2736 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2737 FieldSize = CGM.getContext().getTypeSize(FType);
2738 FieldAlign = CGM.getContext().toBits(Align);
2739
Eric Christopherb2a008c2013-05-16 00:45:12 +00002740 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2742 0, FieldSize, FieldAlign,
2743 FieldOffset, 0, FieldTy);
2744 EltTys.push_back(FieldTy);
2745 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002748
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002750
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002752 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002753}
2754
2755/// EmitDeclare - Emit local variable declaration debug info.
2756void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002757 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002759 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2761
David Blaikie7fceebf2013-08-19 03:37:48 +00002762 bool Unwritten =
2763 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2764 cast<Decl>(VD->getDeclContext())->isImplicit());
2765 llvm::DIFile Unit;
2766 if (!Unwritten)
2767 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 llvm::DIType Ty;
2769 uint64_t XOffset = 0;
2770 if (VD->hasAttr<BlocksAttr>())
2771 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002772 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 Ty = getOrCreateType(VD->getType(), Unit);
2774
2775 // If there is no debug info for this type then do not emit debug info
2776 // for this variable.
2777 if (!Ty)
2778 return;
2779
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002781 unsigned Line = 0;
2782 unsigned Column = 0;
2783 if (!Unwritten) {
2784 Line = getLineNumber(VD->getLocation());
2785 Column = getColumnNumber(VD->getLocation());
2786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 unsigned Flags = 0;
2788 if (VD->isImplicit())
2789 Flags |= llvm::DIDescriptor::FlagArtificial;
2790 // If this is the first argument and it is implicit then
2791 // give it an object pointer flag.
2792 // FIXME: There has to be a better way to do this, but for static
2793 // functions there won't be an implicit param at arg1 and
2794 // otherwise it is 'self' or 'this'.
2795 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2796 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002797 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002798 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2799 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002800 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002801
2802 llvm::MDNode *Scope = LexicalBlockStack.back();
2803
2804 StringRef Name = VD->getName();
2805 if (!Name.empty()) {
2806 if (VD->hasAttr<BlocksAttr>()) {
2807 CharUnits offset = CharUnits::fromQuantity(32);
2808 SmallVector<llvm::Value *, 9> addr;
2809 llvm::Type *Int64Ty = CGM.Int64Ty;
2810 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2811 // offset of __forwarding field
2812 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002813 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2815 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2816 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2817 // offset of x field
2818 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2819 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2820
2821 // Create the descriptor for the variable.
2822 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002823 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 llvm::DIDescriptor(Scope),
2825 VD->getName(), Unit, Line, Ty,
2826 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002827
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 // Insert an llvm.dbg.declare into the current block.
2829 llvm::Instruction *Call =
2830 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2831 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2832 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002833 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002834 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002835 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2836 // If VD is an anonymous union then Storage represents value for
2837 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002839 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 for (RecordDecl::field_iterator I = RD->field_begin(),
2841 E = RD->field_end();
2842 I != E; ++I) {
2843 FieldDecl *Field = *I;
2844 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2845 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002846
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 // Ignore unnamed fields. Do not ignore unnamed records.
2848 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2849 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002850
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 // Use VarDecl's Tag, Scope and Line number.
2852 llvm::DIVariable D =
2853 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002854 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 CGM.getLangOpts().Optimize, Flags,
2856 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002857
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 // Insert an llvm.dbg.declare into the current block.
2859 llvm::Instruction *Call =
2860 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2861 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2862 }
David Blaikie219c7d92013-01-05 20:03:07 +00002863 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 }
2865 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002866
2867 // Create the descriptor for the variable.
2868 llvm::DIVariable D =
2869 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2870 Name, Unit, Line, Ty,
2871 CGM.getLangOpts().Optimize, Flags, ArgNo);
2872
2873 // Insert an llvm.dbg.declare into the current block.
2874 llvm::Instruction *Call =
2875 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2876 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002877}
2878
2879void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2880 llvm::Value *Storage,
2881 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002882 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2884}
2885
Adrian Prantlde17db32013-03-29 19:20:29 +00002886/// Look up the completed type for a self pointer in the TypeCache and
2887/// create a copy of it with the ObjectPointer and Artificial flags
2888/// set. If the type is not cached, a new one is created. This should
2889/// never happen though, since creating a type for the implicit self
2890/// argument implies that we already parsed the interface definition
2891/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002892llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2893 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002894 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002895 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002896 else DEBUG(llvm::dbgs() << "No cached type for self.");
2897 return DBuilder.createObjectPointerType(Ty);
2898}
2899
Guy Benyei11169dd2012-12-18 14:30:41 +00002900void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2901 llvm::Value *Storage,
2902 CGBuilderTy &Builder,
2903 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002904 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002906
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 if (Builder.GetInsertBlock() == 0)
2908 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002909
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002911
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 uint64_t XOffset = 0;
2913 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2914 llvm::DIType Ty;
2915 if (isByRef)
2916 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002917 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 Ty = getOrCreateType(VD->getType(), Unit);
2919
2920 // Self is passed along as an implicit non-arg variable in a
2921 // block. Mark it as the object pointer.
2922 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002923 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002924
2925 // Get location information.
2926 unsigned Line = getLineNumber(VD->getLocation());
2927 unsigned Column = getColumnNumber(VD->getLocation());
2928
2929 const llvm::DataLayout &target = CGM.getDataLayout();
2930
2931 CharUnits offset = CharUnits::fromQuantity(
2932 target.getStructLayout(blockInfo.StructureType)
2933 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2934
2935 SmallVector<llvm::Value *, 9> addr;
2936 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002937 if (isa<llvm::AllocaInst>(Storage))
2938 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2940 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2941 if (isByRef) {
2942 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2943 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2944 // offset of __forwarding field
2945 offset = CGM.getContext()
2946 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2947 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2948 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2949 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2950 // offset of x field
2951 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2952 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2953 }
2954
2955 // Create the descriptor for the variable.
2956 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002957 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 llvm::DIDescriptor(LexicalBlockStack.back()),
2959 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002960
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 // Insert an llvm.dbg.declare into the current block.
2962 llvm::Instruction *Call =
2963 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2964 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2965 LexicalBlockStack.back()));
2966}
2967
2968/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2969/// variable declaration.
2970void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2971 unsigned ArgNo,
2972 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002973 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2975}
2976
2977namespace {
2978 struct BlockLayoutChunk {
2979 uint64_t OffsetInBits;
2980 const BlockDecl::Capture *Capture;
2981 };
2982 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2983 return l.OffsetInBits < r.OffsetInBits;
2984 }
2985}
2986
2987void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002988 llvm::Value *Arg,
2989 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002991 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 ASTContext &C = CGM.getContext();
2993 const BlockDecl *blockDecl = block.getBlockDecl();
2994
2995 // Collect some general information about the block's location.
2996 SourceLocation loc = blockDecl->getCaretLocation();
2997 llvm::DIFile tunit = getOrCreateFile(loc);
2998 unsigned line = getLineNumber(loc);
2999 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00003000
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 // Build the debug-info type for the block literal.
3002 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3003
3004 const llvm::StructLayout *blockLayout =
3005 CGM.getDataLayout().getStructLayout(block.StructureType);
3006
3007 SmallVector<llvm::Value*, 16> fields;
3008 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3009 blockLayout->getElementOffsetInBits(0),
3010 tunit, tunit));
3011 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3012 blockLayout->getElementOffsetInBits(1),
3013 tunit, tunit));
3014 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3015 blockLayout->getElementOffsetInBits(2),
3016 tunit, tunit));
3017 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3018 blockLayout->getElementOffsetInBits(3),
3019 tunit, tunit));
3020 fields.push_back(createFieldType("__descriptor",
3021 C.getPointerType(block.NeedsCopyDispose ?
3022 C.getBlockDescriptorExtendedType() :
3023 C.getBlockDescriptorType()),
3024 0, loc, AS_public,
3025 blockLayout->getElementOffsetInBits(4),
3026 tunit, tunit));
3027
3028 // We want to sort the captures by offset, not because DWARF
3029 // requires this, but because we're paranoid about debuggers.
3030 SmallVector<BlockLayoutChunk, 8> chunks;
3031
3032 // 'this' capture.
3033 if (blockDecl->capturesCXXThis()) {
3034 BlockLayoutChunk chunk;
3035 chunk.OffsetInBits =
3036 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3037 chunk.Capture = 0;
3038 chunks.push_back(chunk);
3039 }
3040
3041 // Variable captures.
3042 for (BlockDecl::capture_const_iterator
3043 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3044 i != e; ++i) {
3045 const BlockDecl::Capture &capture = *i;
3046 const VarDecl *variable = capture.getVariable();
3047 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3048
3049 // Ignore constant captures.
3050 if (captureInfo.isConstant())
3051 continue;
3052
3053 BlockLayoutChunk chunk;
3054 chunk.OffsetInBits =
3055 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3056 chunk.Capture = &capture;
3057 chunks.push_back(chunk);
3058 }
3059
3060 // Sort by offset.
3061 llvm::array_pod_sort(chunks.begin(), chunks.end());
3062
3063 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3064 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3065 uint64_t offsetInBits = i->OffsetInBits;
3066 const BlockDecl::Capture *capture = i->Capture;
3067
3068 // If we have a null capture, this must be the C++ 'this' capture.
3069 if (!capture) {
3070 const CXXMethodDecl *method =
3071 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3072 QualType type = method->getThisType(C);
3073
3074 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3075 offsetInBits, tunit, tunit));
3076 continue;
3077 }
3078
3079 const VarDecl *variable = capture->getVariable();
3080 StringRef name = variable->getName();
3081
3082 llvm::DIType fieldType;
3083 if (capture->isByRef()) {
3084 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3085
3086 // FIXME: this creates a second copy of this type!
3087 uint64_t xoffset;
3088 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3089 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3090 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3091 ptrInfo.first, ptrInfo.second,
3092 offsetInBits, 0, fieldType);
3093 } else {
3094 fieldType = createFieldType(name, variable->getType(), 0,
3095 loc, AS_public, offsetInBits, tunit, tunit);
3096 }
3097 fields.push_back(fieldType);
3098 }
3099
3100 SmallString<36> typeName;
3101 llvm::raw_svector_ostream(typeName)
3102 << "__block_literal_" << CGM.getUniqueBlockCount();
3103
3104 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3105
3106 llvm::DIType type =
3107 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3108 CGM.getContext().toBits(block.BlockSize),
3109 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003110 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3112
3113 // Get overall information about the block.
3114 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3115 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003116
3117 // Create the descriptor for the parameter.
3118 llvm::DIVariable debugVar =
3119 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003120 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003121 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003123 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3124
Adrian Prantl616bef42013-03-14 21:52:59 +00003125 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003126 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003127 llvm::Instruction *DbgVal =
3128 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003129 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003130 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3131 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003132
Adrian Prantl616bef42013-03-14 21:52:59 +00003133 // Insert an llvm.dbg.declare into the current block.
3134 llvm::Instruction *DbgDecl =
3135 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3136 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003137}
3138
David Blaikie6943dea2013-08-20 01:28:15 +00003139/// If D is an out-of-class definition of a static data member of a class, find
3140/// its corresponding in-class declaration.
3141llvm::DIDerivedType
3142CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3143 if (!D->isStaticDataMember())
3144 return llvm::DIDerivedType();
3145 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3146 StaticDataMemberCache.find(D->getCanonicalDecl());
3147 if (MI != StaticDataMemberCache.end()) {
3148 assert(MI->second && "Static data member declaration should still exist");
3149 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003150 }
David Blaikiece763042013-08-20 21:49:21 +00003151
3152 // If the member wasn't found in the cache, lazily construct and add it to the
3153 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003154 llvm::DICompositeType Ctxt(
3155 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3156 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003157 return T;
3158}
3159
Guy Benyei11169dd2012-12-18 14:30:41 +00003160/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003161void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003163 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 // Create global variable debug descriptor.
3165 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3166 unsigned LineNo = getLineNumber(D->getLocation());
3167
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003168 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003169
3170 QualType T = D->getType();
3171 if (T->isIncompleteArrayType()) {
3172
3173 // CodeGen turns int[] into int[1] so we'll do the same here.
3174 llvm::APInt ConstVal(32, 1);
3175 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3176
3177 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3178 ArrayType::Normal, 0);
3179 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003180 StringRef DeclName = D->getName();
3181 StringRef LinkageName;
3182 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3183 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3184 LinkageName = Var->getName();
3185 if (LinkageName == DeclName)
3186 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003187 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003189 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3190 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003191 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003192 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003193 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003194}
3195
3196/// EmitGlobalVariable - Emit information about an objective-c interface.
3197void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3198 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003199 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 // Create global variable debug descriptor.
3201 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3202 unsigned LineNo = getLineNumber(ID->getLocation());
3203
3204 StringRef Name = ID->getName();
3205
3206 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3207 if (T->isIncompleteArrayType()) {
3208
3209 // CodeGen turns int[] into int[1] so we'll do the same here.
3210 llvm::APInt ConstVal(32, 1);
3211 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3212
3213 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3214 ArrayType::Normal, 0);
3215 }
3216
3217 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3218 getOrCreateType(T, Unit),
3219 Var->hasInternalLinkage(), Var);
3220}
3221
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003222/// EmitGlobalVariable - Emit global variable's debug info.
3223void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3224 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003225 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003226 // Create the descriptor for the variable.
3227 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3228 StringRef Name = VD->getName();
3229 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3230 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3231 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3232 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3233 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3234 }
3235 // Do not use DIGlobalVariable for enums.
3236 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3237 return;
3238 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3239 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3240 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3241 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003242}
3243
3244llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3245 if (!LexicalBlockStack.empty())
3246 return llvm::DIScope(LexicalBlockStack.back());
3247 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003248}
3249
David Blaikie9f88fe82013-04-22 06:13:21 +00003250void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003251 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3252 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003253 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003254 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3255 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003256 getLineNumber(UD.getLocation()));
3257}
3258
David Blaikiebd483762013-05-20 04:58:53 +00003259void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3260 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3261 return;
3262 assert(UD.shadow_size() &&
3263 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3264 // Emitting one decl is sufficient - debuggers can detect that this is an
3265 // overloaded name & provide lookup for all the overloads.
3266 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003267 if (llvm::DIDescriptor Target =
3268 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003269 DBuilder.createImportedDeclaration(
3270 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3271 getLineNumber(USD.getLocation()));
3272}
3273
David Blaikief121b932013-05-20 22:50:41 +00003274llvm::DIImportedEntity
3275CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3276 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3277 return llvm::DIImportedEntity(0);
3278 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3279 if (VH)
3280 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3281 llvm::DIImportedEntity R(0);
3282 if (const NamespaceAliasDecl *Underlying =
3283 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3284 // This could cache & dedup here rather than relying on metadata deduping.
3285 R = DBuilder.createImportedModule(
3286 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3287 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3288 NA.getName());
3289 else
3290 R = DBuilder.createImportedModule(
3291 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3292 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3293 getLineNumber(NA.getLocation()), NA.getName());
3294 VH = R;
3295 return R;
3296}
3297
Guy Benyei11169dd2012-12-18 14:30:41 +00003298/// getOrCreateNamesSpace - Return namespace descriptor for the given
3299/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003300llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003301CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003302 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003303 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 NameSpaceCache.find(NSDecl);
3305 if (I != NameSpaceCache.end())
3306 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003307
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3309 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003310 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3312 llvm::DINameSpace NS =
3313 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3314 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3315 return NS;
3316}
3317
3318void CGDebugInfo::finalize() {
3319 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3320 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3321 llvm::DIType Ty, RepTy;
3322 // Verify that the debug info still exists.
3323 if (llvm::Value *V = VI->second)
3324 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003325
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3327 TypeCache.find(VI->first);
3328 if (it != TypeCache.end()) {
3329 // Verify that the debug info still exists.
3330 if (llvm::Value *V = it->second)
3331 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3332 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003333
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003334 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003337
3338 // We keep our own list of retained types, because we need to look
3339 // up the final type in the type cache.
3340 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3341 RE = RetainedTypes.end(); RI != RE; ++RI)
David Blaikie0856f662014-03-04 22:01:08 +00003342 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003343
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 DBuilder.finalize();
3345}