blob: b62cc2546fb3f0f697587e54f06d0379555e29bd [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) {
David Blaikie65813a32014-04-02 18:21:09 +0000231 // quick optimization to avoid having to intern strings that are already
232 // stored reliably elsewhere
233 if (!isa<ClassTemplateSpecializationDecl>(RD))
Guy Benyei11169dd2012-12-18 14:30:41 +0000234 return RD->getName();
235
David Blaikie65813a32014-04-02 18:21:09 +0000236 SmallString<128> Name;
Benjamin Kramer9170e912013-02-22 15:46:01 +0000237 {
David Blaikie65813a32014-04-02 18:21:09 +0000238 llvm::raw_svector_ostream OS(Name);
239 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
240 /*Qualified*/ false);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000241 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000242
243 // Copy this name on the side and use its reference.
David Blaikie65813a32014-04-02 18:21:09 +0000244 return internString(Name);
Guy Benyei11169dd2012-12-18 14:30:41 +0000245}
246
247/// getOrCreateFile - Get the file debug info descriptor for the input location.
248llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
249 if (!Loc.isValid())
250 // If Location is not valid then use main input file.
251 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
252
253 SourceManager &SM = CGM.getContext().getSourceManager();
254 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
255
256 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
257 // If the location is not valid then use main input file.
258 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
259
260 // Cache the results.
261 const char *fname = PLoc.getFilename();
262 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
263 DIFileCache.find(fname);
264
265 if (it != DIFileCache.end()) {
266 // Verify that the information still exists.
267 if (llvm::Value *V = it->second)
268 return llvm::DIFile(cast<llvm::MDNode>(V));
269 }
270
271 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
272
273 DIFileCache[fname] = F;
274 return F;
275}
276
277/// getOrCreateMainFile - Get the file info for main compile unit.
278llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
279 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
280}
281
282/// getLineNumber - Get line number for the location. If location is invalid
283/// then use current location.
284unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
285 if (Loc.isInvalid() && CurLoc.isInvalid())
286 return 0;
287 SourceManager &SM = CGM.getContext().getSourceManager();
288 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
289 return PLoc.isValid()? PLoc.getLine() : 0;
290}
291
292/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000293unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000294 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000295 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 return 0;
297
298 // If the location is invalid then use the current column.
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.getColumn() : 0;
304}
305
306StringRef CGDebugInfo::getCurrentDirname() {
307 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
308 return CGM.getCodeGenOpts().DebugCompilationDir;
309
310 if (!CWDName.empty())
311 return CWDName;
312 SmallString<256> CWD;
313 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000314 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000315}
316
317/// CreateCompileUnit - Create new compile unit.
318void CGDebugInfo::CreateCompileUnit() {
319
320 // Get absolute path name.
321 SourceManager &SM = CGM.getContext().getSourceManager();
322 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
323 if (MainFileName.empty())
324 MainFileName = "<unknown>";
325
326 // The main file name provided via the "-main-file-name" option contains just
327 // the file name itself with no path information. This file name may have had
328 // a relative path, so we look into the actual file entry for the main
329 // file to determine the real absolute path for the file.
330 std::string MainFileDir;
331 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
332 MainFileDir = MainFile->getDir()->getName();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000333 if (MainFileDir != ".") {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000334 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
335 llvm::sys::path::append(MainFileDirSS, MainFileName);
336 MainFileName = MainFileDirSS.str();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000337 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000338 }
339
340 // Save filename string.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000341 StringRef Filename = internString(MainFileName);
Eric Christopherf1545832013-02-22 23:50:16 +0000342
343 // Save split dwarf file string.
344 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000345 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000346
Guy Benyei11169dd2012-12-18 14:30:41 +0000347 unsigned LangTag;
348 const LangOptions &LO = CGM.getLangOpts();
349 if (LO.CPlusPlus) {
350 if (LO.ObjC1)
351 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
352 else
353 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
354 } else if (LO.ObjC1) {
355 LangTag = llvm::dwarf::DW_LANG_ObjC;
356 } else if (LO.C99) {
357 LangTag = llvm::dwarf::DW_LANG_C99;
358 } else {
359 LangTag = llvm::dwarf::DW_LANG_C89;
360 }
361
362 std::string Producer = getClangFullVersion();
363
364 // Figure out which version of the ObjC runtime we have.
365 unsigned RuntimeVers = 0;
366 if (LO.ObjC1)
367 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
368
369 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 // FIXME - Eliminate TheCU.
Eric Christophere4200a22014-02-27 01:25:08 +0000371 TheCU = DBuilder.createCompileUnit(
372 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
373 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
374 DebugKind == CodeGenOptions::DebugLineTablesOnly
375 ? llvm::DIBuilder::LineTablesOnly
376 : llvm::DIBuilder::FullDebug);
Guy Benyei11169dd2012-12-18 14:30:41 +0000377}
378
379/// CreateType - Get the Basic type from the cache or create a new
380/// one if necessary.
381llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
382 unsigned Encoding = 0;
383 StringRef BTName;
384 switch (BT->getKind()) {
385#define BUILTIN_TYPE(Id, SingletonId)
386#define PLACEHOLDER_TYPE(Id, SingletonId) \
387 case BuiltinType::Id:
388#include "clang/AST/BuiltinTypes.def"
389 case BuiltinType::Dependent:
390 llvm_unreachable("Unexpected builtin type");
391 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000392 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 case BuiltinType::Void:
394 return llvm::DIType();
395 case BuiltinType::ObjCClass:
David Blaikief427b002014-05-06 03:42:01 +0000396 if (!ClassTy)
397 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
398 "objc_class", TheCU,
399 getOrCreateMainFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000400 return ClassTy;
401 case BuiltinType::ObjCId: {
402 // typedef struct objc_class *Class;
403 // typedef struct objc_object {
404 // Class isa;
405 // } *id;
406
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000407 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000408 return ObjTy;
409
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000410 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000411 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
412 "objc_class", TheCU,
413 getOrCreateMainFile(), 0);
414
415 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000416
Guy Benyei11169dd2012-12-18 14:30:41 +0000417 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
418
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000419 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000420 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
421 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000422
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000423 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
424 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000425 return ObjTy;
426 }
427 case BuiltinType::ObjCSel: {
David Blaikief427b002014-05-06 03:42:01 +0000428 if (!SelTy)
429 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
430 "objc_selector", TheCU,
431 getOrCreateMainFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 return SelTy;
433 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000434
435 case BuiltinType::OCLImage1d:
436 return getOrCreateStructPtrType("opencl_image1d_t",
437 OCLImage1dDITy);
438 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000439 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000440 OCLImage1dArrayDITy);
441 case BuiltinType::OCLImage1dBuffer:
442 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
443 OCLImage1dBufferDITy);
444 case BuiltinType::OCLImage2d:
445 return getOrCreateStructPtrType("opencl_image2d_t",
446 OCLImage2dDITy);
447 case BuiltinType::OCLImage2dArray:
448 return getOrCreateStructPtrType("opencl_image2d_array_t",
449 OCLImage2dArrayDITy);
450 case BuiltinType::OCLImage3d:
451 return getOrCreateStructPtrType("opencl_image3d_t",
452 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000453 case BuiltinType::OCLSampler:
454 return DBuilder.createBasicType("opencl_sampler_t",
455 CGM.getContext().getTypeSize(BT),
456 CGM.getContext().getTypeAlign(BT),
457 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000458 case BuiltinType::OCLEvent:
459 return getOrCreateStructPtrType("opencl_event_t",
460 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000461
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 case BuiltinType::UChar:
463 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
464 case BuiltinType::Char_S:
465 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
466 case BuiltinType::Char16:
467 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
468 case BuiltinType::UShort:
469 case BuiltinType::UInt:
470 case BuiltinType::UInt128:
471 case BuiltinType::ULong:
472 case BuiltinType::WChar_U:
473 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
474 case BuiltinType::Short:
475 case BuiltinType::Int:
476 case BuiltinType::Int128:
477 case BuiltinType::Long:
478 case BuiltinType::WChar_S:
479 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
480 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
481 case BuiltinType::Half:
482 case BuiltinType::Float:
483 case BuiltinType::LongDouble:
484 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
485 }
486
487 switch (BT->getKind()) {
488 case BuiltinType::Long: BTName = "long int"; break;
489 case BuiltinType::LongLong: BTName = "long long int"; break;
490 case BuiltinType::ULong: BTName = "long unsigned int"; break;
491 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
492 default:
493 BTName = BT->getName(CGM.getLangOpts());
494 break;
495 }
496 // Bit size, align and offset of the type.
497 uint64_t Size = CGM.getContext().getTypeSize(BT);
498 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000499 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 DBuilder.createBasicType(BTName, Size, Align, Encoding);
501 return DbgTy;
502}
503
504llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
505 // Bit size, align and offset of the type.
506 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
507 if (Ty->isComplexIntegerType())
508 Encoding = llvm::dwarf::DW_ATE_lo_user;
509
510 uint64_t Size = CGM.getContext().getTypeSize(Ty);
511 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000512 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000513 DBuilder.createBasicType("complex", Size, Align, Encoding);
514
515 return DbgTy;
516}
517
518/// CreateCVRType - Get the qualified type from the cache or create
519/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000520llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000521 QualifierCollector Qc;
522 const Type *T = Qc.strip(Ty);
523
524 // Ignore these qualifiers for now.
525 Qc.removeObjCGCAttr();
526 Qc.removeAddressSpace();
527 Qc.removeObjCLifetime();
528
529 // We will create one Derived type for one qualifier and recurse to handle any
530 // additional ones.
531 unsigned Tag;
532 if (Qc.hasConst()) {
533 Tag = llvm::dwarf::DW_TAG_const_type;
534 Qc.removeConst();
535 } else if (Qc.hasVolatile()) {
536 Tag = llvm::dwarf::DW_TAG_volatile_type;
537 Qc.removeVolatile();
538 } else if (Qc.hasRestrict()) {
539 Tag = llvm::dwarf::DW_TAG_restrict_type;
540 Qc.removeRestrict();
541 } else {
542 assert(Qc.empty() && "Unknown type qualifier for debug info");
543 return getOrCreateType(QualType(T, 0), Unit);
544 }
545
David Blaikie99dab3b2013-09-04 22:03:57 +0000546 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000547
548 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
549 // CVR derived types.
550 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000551
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 return DbgTy;
553}
554
555llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
556 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000557
558 // The frontend treats 'id' as a typedef to an ObjCObjectType,
559 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
560 // debug info, we want to emit 'id' in both cases.
561 if (Ty->isObjCQualifiedIdType())
562 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
563
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000565 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 Ty->getPointeeType(), Unit);
567 return DbgTy;
568}
569
570llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
571 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000572 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000573 Ty->getPointeeType(), Unit);
574}
575
Manman Rene0064d82013-08-29 23:19:58 +0000576/// In C++ mode, types have linkage, so we can rely on the ODR and
577/// on their mangled names, if they're external.
578static SmallString<256>
579getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
580 llvm::DICompileUnit TheCU) {
581 SmallString<256> FullName;
582 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
583 // For now, only apply ODR with C++.
584 const TagDecl *TD = Ty->getDecl();
585 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
586 !TD->isExternallyVisible())
587 return FullName;
588 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
589 if (CGM.getTarget().getCXXABI().isMicrosoft())
590 return FullName;
591
592 // TODO: This is using the RTTI name. Is there a better way to get
593 // a unique string for a type?
594 llvm::raw_svector_ostream Out(FullName);
595 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
596 Out.flush();
597 return FullName;
598}
599
Guy Benyei11169dd2012-12-18 14:30:41 +0000600// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000601llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000602CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000603 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000604 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000605 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000606 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000607 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
608 unsigned Line = getLineNumber(RD->getLocation());
609 StringRef RDName = getClassName(RD);
610
611 unsigned Tag = 0;
612 if (RD->isStruct() || RD->isInterface())
613 Tag = llvm::dwarf::DW_TAG_structure_type;
614 else if (RD->isUnion())
615 Tag = llvm::dwarf::DW_TAG_union_type;
616 else {
617 assert(RD->isClass());
618 Tag = llvm::dwarf::DW_TAG_class_type;
619 }
620
621 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000622 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
David Blaikief427b002014-05-06 03:42:01 +0000623 llvm::DICompositeType RetTy = DBuilder.createReplaceableForwardDecl(
624 Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0, FullName);
625 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
626 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +0000627}
628
Guy Benyei11169dd2012-12-18 14:30:41 +0000629llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000630 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 QualType PointeeTy,
632 llvm::DIFile Unit) {
633 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
634 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000635 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000636
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 // Bit size, align and offset of the type.
638 // Size is always the size of a pointer. We can't use getTypeSize here
639 // because that does not return the correct value for references.
640 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000641 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000642 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
643
David Blaikie99dab3b2013-09-04 22:03:57 +0000644 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
645 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
Eric Christopher0fdcb312013-05-16 00:52:20 +0000648llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
649 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000650 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000651 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000652 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
653 TheCU, getOrCreateMainFile(), 0);
654 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
655 Cache = DBuilder.createPointerType(Cache, Size);
656 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000657}
658
Guy Benyei11169dd2012-12-18 14:30:41 +0000659llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
660 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000661 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000662 return BlockLiteralGeneric;
663
664 SmallVector<llvm::Value *, 8> EltTys;
665 llvm::DIType FieldTy;
666 QualType FType;
667 uint64_t FieldSize, FieldOffset;
668 unsigned FieldAlign;
669 llvm::DIArray Elements;
670 llvm::DIType EltTy, DescTy;
671
672 FieldOffset = 0;
673 FType = CGM.getContext().UnsignedLongTy;
674 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
675 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
676
677 Elements = DBuilder.getOrCreateArray(EltTys);
678 EltTys.clear();
679
680 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
681 unsigned LineNo = getLineNumber(CurLoc);
682
683 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
684 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000685 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000686
687 // Bit size, align and offset of the type.
688 uint64_t Size = CGM.getContext().getTypeSize(Ty);
689
690 DescTy = DBuilder.createPointerType(EltTy, Size);
691
692 FieldOffset = 0;
693 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
694 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
695 FType = CGM.getContext().IntTy;
696 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
697 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
698 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
699 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
700
701 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
702 FieldTy = DescTy;
703 FieldSize = CGM.getContext().getTypeSize(Ty);
704 FieldAlign = CGM.getContext().getTypeAlign(Ty);
705 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
706 LineNo, FieldSize, FieldAlign,
707 FieldOffset, 0, FieldTy);
708 EltTys.push_back(FieldTy);
709
710 FieldOffset += FieldSize;
711 Elements = DBuilder.getOrCreateArray(EltTys);
712
713 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
714 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000715 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000716
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
718 return BlockLiteralGeneric;
719}
720
David Blaikief1b382e2014-04-06 17:14:06 +0000721llvm::DIType CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, llvm::DIFile Unit) {
722 assert(Ty->isTypeAlias());
723 llvm::DIType Src = getOrCreateType(Ty->getAliasedType(), Unit);
David Blaikief1b382e2014-04-06 17:14:06 +0000724
725 SmallString<128> NS;
726 llvm::raw_svector_ostream OS(NS);
727 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), /*qualified*/ false);
728
729 TemplateSpecializationType::PrintTemplateArgumentList(
730 OS, Ty->getArgs(), Ty->getNumArgs(),
731 CGM.getContext().getPrintingPolicy());
732
733 TypeAliasDecl *AliasDecl =
734 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
735 ->getTemplatedDecl();
736
737 SourceLocation Loc = AliasDecl->getLocation();
738 llvm::DIFile File = getOrCreateFile(Loc);
739 unsigned Line = getLineNumber(Loc);
740
741 llvm::DIDescriptor Ctxt = getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext()));
742
743 return DBuilder.createTypedef(Src, internString(OS.str()), File, Line, Ctxt);
744}
745
David Blaikie99dab3b2013-09-04 22:03:57 +0000746llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 // Typedefs are derived from some other type. If we have a typedef of a
748 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000749 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000750 // We don't set size information, but do specify where the typedef was
751 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000752 SourceLocation Loc = Ty->getDecl()->getLocation();
753 llvm::DIFile File = getOrCreateFile(Loc);
754 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000755 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000756
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 llvm::DIDescriptor TypedefContext =
758 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000759
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000761 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000762}
763
764llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
765 llvm::DIFile Unit) {
766 SmallVector<llvm::Value *, 16> EltTys;
767
768 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000769 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000770
771 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000772 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 if (isa<FunctionNoProtoType>(Ty))
774 EltTys.push_back(DBuilder.createUnspecifiedParameter());
775 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000776 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
777 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000778 if (FPT->isVariadic())
779 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000780 }
781
782 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
783 return DBuilder.createSubroutineType(Unit, EltTypeArray);
784}
785
786
Guy Benyei11169dd2012-12-18 14:30:41 +0000787llvm::DIType CGDebugInfo::createFieldType(StringRef name,
788 QualType type,
789 uint64_t sizeInBitsOverride,
790 SourceLocation loc,
791 AccessSpecifier AS,
792 uint64_t offsetInBits,
793 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000794 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 llvm::DIType debugType = getOrCreateType(type, tunit);
796
797 // Get the location for the field.
798 llvm::DIFile file = getOrCreateFile(loc);
799 unsigned line = getLineNumber(loc);
800
801 uint64_t sizeInBits = 0;
802 unsigned alignInBits = 0;
803 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000804 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000805
806 if (sizeInBitsOverride)
807 sizeInBits = sizeInBitsOverride;
808 }
809
810 unsigned flags = 0;
811 if (AS == clang::AS_private)
812 flags |= llvm::DIDescriptor::FlagPrivate;
813 else if (AS == clang::AS_protected)
814 flags |= llvm::DIDescriptor::FlagProtected;
815
816 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
817 alignInBits, offsetInBits, flags, debugType);
818}
819
Eric Christopher91a31902013-01-16 01:22:32 +0000820/// CollectRecordLambdaFields - Helper for CollectRecordFields.
821void CGDebugInfo::
822CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
823 SmallVectorImpl<llvm::Value *> &elements,
824 llvm::DIType RecordTy) {
825 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
826 // has the name and the location of the variable so we should iterate over
827 // both concurrently.
828 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
829 RecordDecl::field_iterator Field = CXXDecl->field_begin();
830 unsigned fieldno = 0;
831 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
832 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
833 const LambdaExpr::Capture C = *I;
834 if (C.capturesVariable()) {
835 VarDecl *V = C.getCapturedVar();
836 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
837 StringRef VName = V->getName();
838 uint64_t SizeInBitsOverride = 0;
839 if (Field->isBitField()) {
840 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
841 assert(SizeInBitsOverride && "found named 0-width bitfield");
842 }
843 llvm::DIType fieldType
844 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
845 C.getLocation(), Field->getAccess(),
846 layout.getFieldOffset(fieldno), VUnit, RecordTy);
847 elements.push_back(fieldType);
848 } else {
849 // TODO: Need to handle 'this' in some way by probably renaming the
850 // this of the lambda class and having a field member of 'this' or
851 // by using AT_object_pointer for the function and having that be
852 // used as 'this' for semantic references.
853 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
854 FieldDecl *f = *Field;
855 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
856 QualType type = f->getType();
857 llvm::DIType fieldType
858 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
859 layout.getFieldOffset(fieldno), VUnit, RecordTy);
860
861 elements.push_back(fieldType);
862 }
863 }
864}
865
David Blaikie6943dea2013-08-20 01:28:15 +0000866/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000867llvm::DIDerivedType
868CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
869 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000870 // Create the descriptor for the static variable, with or without
871 // constant initializers.
872 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
873 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
874
Eric Christopher91a31902013-01-16 01:22:32 +0000875 unsigned LineNumber = getLineNumber(Var->getLocation());
876 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000877 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000878 if (Var->getInit()) {
879 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000880 if (Value) {
881 if (Value->isInt())
882 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
883 if (Value->isFloat())
884 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
885 }
Eric Christopher91a31902013-01-16 01:22:32 +0000886 }
887
888 unsigned Flags = 0;
889 AccessSpecifier Access = Var->getAccess();
890 if (Access == clang::AS_private)
891 Flags |= llvm::DIDescriptor::FlagPrivate;
892 else if (Access == clang::AS_protected)
893 Flags |= llvm::DIDescriptor::FlagProtected;
894
David Blaikieae019462013-08-15 22:50:29 +0000895 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
896 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000897 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000898 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000899}
900
901/// CollectRecordNormalField - Helper for CollectRecordFields.
902void CGDebugInfo::
903CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
904 llvm::DIFile tunit,
905 SmallVectorImpl<llvm::Value *> &elements,
906 llvm::DIType RecordTy) {
907 StringRef name = field->getName();
908 QualType type = field->getType();
909
910 // Ignore unnamed fields unless they're anonymous structs/unions.
911 if (name.empty() && !type->isRecordType())
912 return;
913
914 uint64_t SizeInBitsOverride = 0;
915 if (field->isBitField()) {
916 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
917 assert(SizeInBitsOverride && "found named 0-width bitfield");
918 }
919
920 llvm::DIType fieldType
921 = createFieldType(name, type, SizeInBitsOverride,
922 field->getLocation(), field->getAccess(),
923 OffsetInBits, tunit, RecordTy);
924
925 elements.push_back(fieldType);
926}
927
Guy Benyei11169dd2012-12-18 14:30:41 +0000928/// CollectRecordFields - A helper function to collect debug info for
929/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000930void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
931 llvm::DIFile tunit,
932 SmallVectorImpl<llvm::Value *> &elements,
933 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
935
Eric Christopher91a31902013-01-16 01:22:32 +0000936 if (CXXDecl && CXXDecl->isLambda())
937 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
938 else {
939 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000940
Eric Christopher91a31902013-01-16 01:22:32 +0000941 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000942 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000943
Eric Christopher91a31902013-01-16 01:22:32 +0000944 // Static and non-static members should appear in the same order as
945 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +0000946 for (const auto *I : record->decls())
947 if (const auto *V = dyn_cast<VarDecl>(I)) {
David Blaikiece763042013-08-20 21:49:21 +0000948 // Reuse the existing static member declaration if one exists
949 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
950 StaticDataMemberCache.find(V->getCanonicalDecl());
951 if (MI != StaticDataMemberCache.end()) {
952 assert(MI->second &&
953 "Static data member declaration should still exist");
954 elements.push_back(
955 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
956 } else
957 elements.push_back(CreateRecordStaticField(V, RecordTy));
Aaron Ballman629afae2014-03-07 19:56:05 +0000958 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000959 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
960 tunit, elements, RecordTy);
961
962 // Bump field number for next field.
963 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 }
966}
967
968/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
969/// function type is not updated to include implicit "this" pointer. Use this
970/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000971llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000972CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
973 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000974 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000975 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000976 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000977 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
978 Func, Unit);
979}
David Blaikie2aaf0652013-01-07 22:24:59 +0000980
David Blaikie469f0792013-05-22 23:22:42 +0000981llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000982 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000984 llvm::DIArray Args = llvm::DICompositeType(
985 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 assert (Args.getNumElements() && "Invalid number of arguments!");
987
988 SmallVector<llvm::Value *, 16> Elts;
989
990 // First element is always return type. For 'void' functions it is NULL.
991 Elts.push_back(Args.getElement(0));
992
David Blaikie2aaf0652013-01-07 22:24:59 +0000993 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000994 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000995 if (isa<ClassTemplateSpecializationDecl>(RD)) {
996 // Create pointer type directly in this case.
997 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
998 QualType PointeeTy = ThisPtrTy->getPointeeType();
999 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001000 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +00001001 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1002 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +00001003 llvm::DIType ThisPtrType =
1004 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +00001005 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1006 // TODO: This and the artificial type below are misleading, the
1007 // types aren't artificial the argument is, but the current
1008 // metadata doesn't represent that.
1009 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1010 Elts.push_back(ThisPtrType);
1011 } else {
1012 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1013 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1014 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1015 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 }
1017
1018 // Copy rest of the arguments.
1019 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1020 Elts.push_back(Args.getElement(i));
1021
1022 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1023
Adrian Prantl0630eb72013-12-18 21:48:18 +00001024 unsigned Flags = 0;
1025 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1026 Flags |= llvm::DIDescriptor::FlagLValueReference;
1027 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1028 Flags |= llvm::DIDescriptor::FlagRValueReference;
1029
1030 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031}
1032
Eric Christopherb2a008c2013-05-16 00:45:12 +00001033/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001034/// inside a function.
1035static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1036 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1037 return isFunctionLocalClass(NRD);
1038 if (isa<FunctionDecl>(RD->getDeclContext()))
1039 return true;
1040 return false;
1041}
1042
1043/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1044/// a single member function GlobalDecl.
1045llvm::DISubprogram
1046CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1047 llvm::DIFile Unit,
1048 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001049 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001051
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001053 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001054
1055 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1056 // make sense to give a single ctor/dtor a linkage name.
1057 StringRef MethodLinkageName;
1058 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1059 MethodLinkageName = CGM.getMangledName(Method);
1060
1061 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001062 llvm::DIFile MethodDefUnit;
1063 unsigned MethodLine = 0;
1064 if (!Method->isImplicit()) {
1065 MethodDefUnit = getOrCreateFile(Method->getLocation());
1066 MethodLine = getLineNumber(Method->getLocation());
1067 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001068
1069 // Collect virtual method info.
1070 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001071 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001072 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001073
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 if (Method->isVirtual()) {
1075 if (Method->isPure())
1076 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1077 else
1078 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001079
Guy Benyei11169dd2012-12-18 14:30:41 +00001080 // It doesn't make sense to give a virtual destructor a vtable index,
1081 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001082 // FIXME: Add proper support for debug info for virtual calls in
1083 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1084 // lookup if we have multiple or virtual inheritance.
1085 if (!isa<CXXDestructorDecl>(Method) &&
1086 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001087 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001088 ContainingType = RecordTy;
1089 }
1090
1091 unsigned Flags = 0;
1092 if (Method->isImplicit())
1093 Flags |= llvm::DIDescriptor::FlagArtificial;
1094 AccessSpecifier Access = Method->getAccess();
1095 if (Access == clang::AS_private)
1096 Flags |= llvm::DIDescriptor::FlagPrivate;
1097 else if (Access == clang::AS_protected)
1098 Flags |= llvm::DIDescriptor::FlagProtected;
1099 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1100 if (CXXC->isExplicit())
1101 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001102 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 dyn_cast<CXXConversionDecl>(Method)) {
1104 if (CXXC->isExplicit())
1105 Flags |= llvm::DIDescriptor::FlagExplicit;
1106 }
1107 if (Method->hasPrototype())
1108 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001109 if (Method->getRefQualifier() == RQ_LValue)
1110 Flags |= llvm::DIDescriptor::FlagLValueReference;
1111 if (Method->getRefQualifier() == RQ_RValue)
1112 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001113
1114 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1115 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001116 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001118 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001119 /* isDefinition=*/ false,
1120 Virtuality, VIndex, ContainingType,
1121 Flags, CGM.getLangOpts().Optimize, NULL,
1122 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001123
Guy Benyei11169dd2012-12-18 14:30:41 +00001124 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1125
1126 return SP;
1127}
1128
1129/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001130/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001131/// a Record.
1132void CGDebugInfo::
1133CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1134 SmallVectorImpl<llvm::Value *> &EltTys,
1135 llvm::DIType RecordTy) {
1136
1137 // Since we want more than just the individual member decls if we
1138 // have templated functions iterate over every declaration to gather
1139 // the functions.
Aaron Ballman629afae2014-03-07 19:56:05 +00001140 for(const auto *I : RD->decls()) {
1141 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001142 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001143 // It may be associated with the declaration of the type & should be
1144 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001145 //
1146 // This situation can arise in the vtable-based debug info reduction where
1147 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001148 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1149 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001150 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001151 // If the member is implicit, lazily create it when we see the
1152 // definition, not before. (an ODR-used implicit default ctor that's
1153 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001154 if (!Method->isImplicit())
1155 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1156 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001157 EltTys.push_back(MI->second);
Aaron Ballman629afae2014-03-07 19:56:05 +00001158 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001159 // Add any template specializations that have already been seen. Like
1160 // implicit member functions, these may have been added to a declaration
1161 // in the case of vtable-based debug info reduction.
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001162 for (const auto *SI : FTD->specializations()) {
David Blaikief2053af2013-08-28 23:06:52 +00001163 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001164 SPCache.find(cast<CXXMethodDecl>(SI)->getCanonicalDecl());
David Blaikief2053af2013-08-28 23:06:52 +00001165 if (MI != SPCache.end())
1166 EltTys.push_back(MI->second);
1167 }
David Blaikie6943dea2013-08-20 01:28:15 +00001168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001170}
Guy Benyei11169dd2012-12-18 14:30:41 +00001171
Guy Benyei11169dd2012-12-18 14:30:41 +00001172/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001173/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001174/// a Record.
1175void CGDebugInfo::
1176CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1177 SmallVectorImpl<llvm::Value *> &EltTys,
1178 llvm::DIType RecordTy) {
1179
1180 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Aaron Ballman574705e2014-03-13 15:41:46 +00001181 for (const auto &BI : RD->bases()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 unsigned BFlags = 0;
1183 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001184
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001186 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001187
Aaron Ballman574705e2014-03-13 15:41:46 +00001188 if (BI.isVirtual()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 // virtual base offset offset is -ve. The code generator emits dwarf
1190 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001191 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001192 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1194 BFlags = llvm::DIDescriptor::FlagVirtual;
1195 } else
1196 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1197 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1198 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001199
Aaron Ballman574705e2014-03-13 15:41:46 +00001200 AccessSpecifier Access = BI.getAccessSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00001201 if (Access == clang::AS_private)
1202 BFlags |= llvm::DIDescriptor::FlagPrivate;
1203 else if (Access == clang::AS_protected)
1204 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001205
1206 llvm::DIType DTy =
1207 DBuilder.createInheritance(RecordTy,
Aaron Ballman574705e2014-03-13 15:41:46 +00001208 getOrCreateType(BI.getType(), Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 BaseOffset, BFlags);
1210 EltTys.push_back(DTy);
1211 }
1212}
1213
1214/// CollectTemplateParams - A helper function to collect template parameters.
1215llvm::DIArray CGDebugInfo::
1216CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001217 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001219 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001220 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1221 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001222 StringRef Name;
1223 if (TPList)
1224 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001225 switch (TA.getKind()) {
1226 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001227 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1228 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001229 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001231 } break;
1232 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1234 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001235 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001236 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001237 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1238 TemplateParams.push_back(TVP);
1239 } break;
1240 case TemplateArgument::Declaration: {
1241 const ValueDecl *D = TA.getAsDecl();
1242 bool InstanceMember = D->isCXXInstanceMember();
1243 QualType T = InstanceMember
1244 ? CGM.getContext().getMemberPointerType(
1245 D->getType(), cast<RecordDecl>(D->getDeclContext())
1246 ->getTypeForDecl())
1247 : CGM.getContext().getPointerType(D->getType());
1248 llvm::DIType TTy = getOrCreateType(T, Unit);
1249 llvm::Value *V = 0;
1250 // Variable pointer template parameters have a value that is the address
1251 // of the variable.
1252 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1253 V = CGM.GetAddrOfGlobalVar(VD);
1254 // Member function pointers have special support for building them, though
1255 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001256 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001257 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1258 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001259 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1260 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001261 // Member data pointers have special handling too to compute the fixed
1262 // offset within the object.
Adrian Prantlefb88052014-04-01 17:52:06 +00001263 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
David Blaikie38079fd2013-05-10 21:53:14 +00001264 // These five lines (& possibly the above member function pointer
1265 // handling) might be able to be refactored to use similar code in
1266 // CodeGenModule::getMemberPointerConstant
1267 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1268 CharUnits chars =
1269 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1270 V = CGM.getCXXABI().EmitMemberDataPointer(
1271 cast<MemberPointerType>(T.getTypePtr()), chars);
1272 }
1273 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001274 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1275 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001276 TemplateParams.push_back(TVP);
1277 } break;
1278 case TemplateArgument::NullPtr: {
1279 QualType T = TA.getNullPtrType();
1280 llvm::DIType TTy = getOrCreateType(T, Unit);
1281 llvm::Value *V = 0;
1282 // Special case member data pointer null values since they're actually -1
1283 // instead of zero.
1284 if (const MemberPointerType *MPT =
1285 dyn_cast<MemberPointerType>(T.getTypePtr()))
1286 // But treat member function pointers as simple zero integers because
1287 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1288 // CodeGen grows handling for values of non-null member function
1289 // pointers then perhaps we could remove this special case and rely on
1290 // EmitNullMemberPointer for member function pointers.
1291 if (MPT->isMemberDataPointer())
1292 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1293 if (!V)
1294 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1295 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001296 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001297 TemplateParams.push_back(TVP);
1298 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001299 case TemplateArgument::Template: {
1300 llvm::DITemplateValueParameter TVP =
1301 DBuilder.createTemplateTemplateParameter(
1302 TheCU, Name, llvm::DIType(),
1303 TA.getAsTemplate().getAsTemplateDecl()
1304 ->getQualifiedNameAsString());
1305 TemplateParams.push_back(TVP);
1306 } break;
1307 case TemplateArgument::Pack: {
1308 llvm::DITemplateValueParameter TVP =
1309 DBuilder.createTemplateParameterPack(
1310 TheCU, Name, llvm::DIType(),
1311 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1312 TemplateParams.push_back(TVP);
1313 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001314 case TemplateArgument::Expression: {
1315 const Expr *E = TA.getAsExpr();
1316 QualType T = E->getType();
1317 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1318 assert(V && "Expression in template argument isn't constant");
1319 llvm::DIType TTy = getOrCreateType(T, Unit);
1320 llvm::DITemplateValueParameter TVP =
1321 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1322 V->stripPointerCasts());
1323 TemplateParams.push_back(TVP);
1324 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001325 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001326 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001327 case TemplateArgument::Null:
1328 llvm_unreachable(
1329 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 }
1331 }
1332 return DBuilder.getOrCreateArray(TemplateParams);
1333}
1334
1335/// CollectFunctionTemplateParams - A helper function to collect debug
1336/// info for function template parameters.
1337llvm::DIArray CGDebugInfo::
1338CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1339 if (FD->getTemplatedKind() ==
1340 FunctionDecl::TK_FunctionTemplateSpecialization) {
1341 const TemplateParameterList *TList =
1342 FD->getTemplateSpecializationInfo()->getTemplate()
1343 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001344 return CollectTemplateParams(
1345 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 }
1347 return llvm::DIArray();
1348}
1349
1350/// CollectCXXTemplateParams - A helper function to collect debug info for
1351/// template parameters.
1352llvm::DIArray CGDebugInfo::
1353CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1354 llvm::DIFile Unit) {
Adrian Prantl649f0302014-04-17 01:04:01 +00001355 // Always get the full list of parameters, not just the ones from
1356 // the specialization.
1357 TemplateParameterList *TPList =
1358 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001359 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001360 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001361}
1362
1363/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1364llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1365 if (VTablePtrType.isValid())
1366 return VTablePtrType;
1367
1368 ASTContext &Context = CGM.getContext();
1369
1370 /* Function type */
1371 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1372 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1373 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1374 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1375 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1376 "__vtbl_ptr_type");
1377 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1378 return VTablePtrType;
1379}
1380
1381/// getVTableName - Get vtable name for the given Class.
1382StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001383 // Copy the gdb compatible name on the side and use its reference.
1384 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001385}
1386
1387
1388/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1389/// debug info entry in EltTys vector.
1390void CGDebugInfo::
1391CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1392 SmallVectorImpl<llvm::Value *> &EltTys) {
1393 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1394
1395 // If there is a primary base then it will hold vtable info.
1396 if (RL.getPrimaryBase())
1397 return;
1398
1399 // If this class is not dynamic then there is not any vtable info to collect.
1400 if (!RD->isDynamicClass())
1401 return;
1402
1403 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1404 llvm::DIType VPTR
1405 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001406 0, Size, 0, 0,
1407 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 getOrCreateVTablePtrType(Unit));
1409 EltTys.push_back(VPTR);
1410}
1411
Eric Christopherb2a008c2013-05-16 00:45:12 +00001412/// getOrCreateRecordType - Emit record type's standalone debug info.
1413llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001415 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001416 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1417 return T;
1418}
1419
1420/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1421/// debug info.
1422llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001423 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001424 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001426 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 return T;
1428}
1429
David Blaikie483a9da2014-05-06 18:35:21 +00001430void CGDebugInfo::completeType(const EnumDecl *ED) {
1431 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1432 return;
1433 QualType Ty = CGM.getContext().getEnumType(ED);
1434 void* TyPtr = Ty.getAsOpaquePtr();
1435 auto I = TypeCache.find(TyPtr);
1436 if (I == TypeCache.end() ||
1437 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
1438 .isForwardDecl())
1439 return;
1440 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1441 assert(!Res.isForwardDecl());
1442 TypeCache[TyPtr] = Res;
1443}
1444
David Blaikieb2e86eb2013-08-15 20:49:17 +00001445void CGDebugInfo::completeType(const RecordDecl *RD) {
1446 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1447 !CGM.getLangOpts().CPlusPlus)
1448 completeRequiredType(RD);
1449}
1450
1451void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie0856f662014-03-04 22:01:08 +00001452 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1453 return;
1454
David Blaikie6943dea2013-08-20 01:28:15 +00001455 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1456 if (CXXDecl->isDynamicClass())
1457 return;
1458
David Blaikieb2e86eb2013-08-15 20:49:17 +00001459 QualType Ty = CGM.getContext().getRecordType(RD);
1460 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001461 if (T && T.isForwardDecl())
1462 completeClassData(RD);
1463}
1464
1465void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1466 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001467 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001468 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001469 void* TyPtr = Ty.getAsOpaquePtr();
David Blaikieef8a9512014-05-05 23:23:53 +00001470 auto I = TypeCache.find(TyPtr);
1471 if (I != TypeCache.end() &&
1472 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
1473 .isForwardDecl())
David Blaikieb2e86eb2013-08-15 20:49:17 +00001474 return;
1475 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1476 assert(!Res.isForwardDecl());
David Blaikieb2e86eb2013-08-15 20:49:17 +00001477 TypeCache[TyPtr] = Res;
1478}
1479
David Blaikie0e716b42014-03-03 23:48:23 +00001480static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1481 CXXRecordDecl::method_iterator End) {
1482 for (; I != End; ++I)
1483 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00001484 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1485 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00001486 return true;
1487 return false;
1488}
1489
1490static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1491 const RecordDecl *RD,
1492 const LangOptions &LangOpts) {
1493 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1494 return false;
1495
1496 if (!LangOpts.CPlusPlus)
1497 return false;
1498
1499 if (!RD->isCompleteDefinitionRequired())
1500 return true;
1501
1502 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1503
1504 if (!CXXDecl)
1505 return false;
1506
1507 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1508 return true;
1509
1510 TemplateSpecializationKind Spec = TSK_Undeclared;
1511 if (const ClassTemplateSpecializationDecl *SD =
1512 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1513 Spec = SD->getSpecializationKind();
1514
1515 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1516 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1517 CXXDecl->method_end()))
1518 return true;
1519
1520 return false;
1521}
1522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001524llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001525 RecordDecl *RD = Ty->getDecl();
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001526 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
David Blaikie0e716b42014-03-03 23:48:23 +00001527 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001528 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001529 T = getOrCreateRecordFwdDecl(
1530 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001531 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001532 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001533
David Blaikieb2e86eb2013-08-15 20:49:17 +00001534 return CreateTypeDefinition(Ty);
1535}
1536
1537llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1538 RecordDecl *RD = Ty->getDecl();
1539
Guy Benyei11169dd2012-12-18 14:30:41 +00001540 // Get overall information about the record type for the debug info.
1541 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1542
1543 // Records and classes and unions can all be recursive. To handle them, we
1544 // first generate a debug descriptor for the struct as a forward declaration.
1545 // Then (if it is a definition) we go through and get debug info for all of
1546 // its members. Finally, we create a descriptor for the complete type (which
1547 // may refer to the forward decl if the struct is recursive) and replace all
1548 // uses of the forward declaration with the final definition.
1549
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001550 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001551 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001552 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001553
1554 if (FwdDecl.isForwardDecl())
1555 return FwdDecl;
1556
David Blaikieadfbf992013-08-18 16:55:33 +00001557 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1558 CollectContainingType(CXXDecl, FwdDecl);
1559
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001561 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1563
Guy Benyei11169dd2012-12-18 14:30:41 +00001564 // Convert all the elements.
1565 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001566 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001567
1568 // Note: The split of CXXDecl information here is intentional, the
1569 // gdb tests will depend on a certain ordering at printout. The debug
1570 // information offsets are still correct if we merge them all together
1571 // though.
1572 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1573 if (CXXDecl) {
1574 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1575 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1576 }
1577
Eric Christopher91a31902013-01-16 01:22:32 +00001578 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001580 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001581 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001582
1583 LexicalBlockStack.pop_back();
1584 RegionMap.erase(Ty->getDecl());
1585
1586 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001587 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001588
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001589 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1590 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001591}
1592
1593/// CreateType - get objective-c object type.
1594llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1595 llvm::DIFile Unit) {
1596 // Ignore protocols.
1597 return getOrCreateType(Ty->getBaseType(), Unit);
1598}
1599
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001600
1601/// \return true if Getter has the default name for the property PD.
1602static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1603 const ObjCMethodDecl *Getter) {
1604 assert(PD);
1605 if (!Getter)
1606 return true;
1607
1608 assert(Getter->getDeclName().isObjCZeroArgSelector());
1609 return PD->getName() ==
1610 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1611}
1612
1613/// \return true if Setter has the default name for the property PD.
1614static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1615 const ObjCMethodDecl *Setter) {
1616 assert(PD);
1617 if (!Setter)
1618 return true;
1619
1620 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001621 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001622 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1623}
1624
Guy Benyei11169dd2012-12-18 14:30:41 +00001625/// CreateType - get objective-c interface type.
1626llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1627 llvm::DIFile Unit) {
1628 ObjCInterfaceDecl *ID = Ty->getDecl();
1629 if (!ID)
1630 return llvm::DIType();
1631
1632 // Get overall information about the record type for the debug info.
1633 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1634 unsigned Line = getLineNumber(ID->getLocation());
1635 unsigned RuntimeLang = TheCU.getLanguage();
1636
1637 // If this is just a forward declaration return a special forward-declaration
1638 // debug type since we won't be able to lay out the entire type.
1639 ObjCInterfaceDecl *Def = ID->getDefinition();
David Blaikieef8a9512014-05-05 23:23:53 +00001640 if (!Def || !Def->getImplementation()) {
David Blaikief427b002014-05-06 03:42:01 +00001641 llvm::DIType FwdDecl = DBuilder.createReplaceableForwardDecl(
1642 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1643 RuntimeLang);
David Blaikieef8a9512014-05-05 23:23:53 +00001644 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 return FwdDecl;
1646 }
1647
David Blaikieef8a9512014-05-05 23:23:53 +00001648
1649 return CreateTypeDefinition(Ty, Unit);
1650}
1651
1652llvm::DIType CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, llvm::DIFile Unit) {
1653 ObjCInterfaceDecl *ID = Ty->getDecl();
1654 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1655 unsigned Line = getLineNumber(ID->getLocation());
1656 unsigned RuntimeLang = TheCU.getLanguage();
Guy Benyei11169dd2012-12-18 14:30:41 +00001657
1658 // Bit size, align and offset of the type.
1659 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1660 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1661
1662 unsigned Flags = 0;
1663 if (ID->getImplementation())
1664 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1665
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001666 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1668 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001669 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001670
David Blaikieef8a9512014-05-05 23:23:53 +00001671 QualType QTy(Ty, 0);
1672 TypeCache[QTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001673
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001674 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001675 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1677
1678 // Convert all the elements.
1679 SmallVector<llvm::Value *, 16> EltTys;
1680
1681 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1682 if (SClass) {
1683 llvm::DIType SClassTy =
1684 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1685 if (!SClassTy.isValid())
1686 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001687
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 llvm::DIType InhTag =
1689 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1690 EltTys.push_back(InhTag);
1691 }
1692
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001693 // Create entries for all of the properties.
Aaron Ballmand174edf2014-03-13 19:11:50 +00001694 for (const auto *PD : ID->properties()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001695 SourceLocation Loc = PD->getLocation();
1696 llvm::DIFile PUnit = getOrCreateFile(Loc);
1697 unsigned PLine = getLineNumber(Loc);
1698 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1699 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1700 llvm::MDNode *PropertyNode =
1701 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001702 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001703 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001705 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 getSelectorName(PD->getSetterName()),
1707 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001708 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 EltTys.push_back(PropertyNode);
1710 }
1711
1712 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1713 unsigned FieldNo = 0;
1714 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1715 Field = Field->getNextIvar(), ++FieldNo) {
1716 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1717 if (!FieldTy.isValid())
1718 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001719
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 StringRef FieldName = Field->getName();
1721
1722 // Ignore unnamed fields.
1723 if (FieldName.empty())
1724 continue;
1725
1726 // Get the location for the field.
1727 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1728 unsigned FieldLine = getLineNumber(Field->getLocation());
1729 QualType FType = Field->getType();
1730 uint64_t FieldSize = 0;
1731 unsigned FieldAlign = 0;
1732
1733 if (!FType->isIncompleteArrayType()) {
1734
1735 // Bit size, align and offset of the type.
1736 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001737 ? Field->getBitWidthValue(CGM.getContext())
1738 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 FieldAlign = CGM.getContext().getTypeAlign(FType);
1740 }
1741
1742 uint64_t FieldOffset;
1743 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1744 // We don't know the runtime offset of an ivar if we're using the
1745 // non-fragile ABI. For bitfields, use the bit offset into the first
1746 // byte of storage of the bitfield. For other fields, use zero.
1747 if (Field->isBitField()) {
1748 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1749 CGM, ID, Field);
1750 FieldOffset %= CGM.getContext().getCharWidth();
1751 } else {
1752 FieldOffset = 0;
1753 }
1754 } else {
1755 FieldOffset = RL.getFieldOffset(FieldNo);
1756 }
1757
1758 unsigned Flags = 0;
1759 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1760 Flags = llvm::DIDescriptor::FlagProtected;
1761 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1762 Flags = llvm::DIDescriptor::FlagPrivate;
1763
1764 llvm::MDNode *PropertyNode = NULL;
1765 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001766 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001767 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1768 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001769 SourceLocation Loc = PD->getLocation();
1770 llvm::DIFile PUnit = getOrCreateFile(Loc);
1771 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1773 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1774 PropertyNode =
1775 DBuilder.createObjCProperty(PD->getName(),
1776 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001777 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001778 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001779 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 getSelectorName(PD->getSetterName()),
1781 PD->getPropertyAttributes(),
1782 getOrCreateType(PD->getType(), PUnit));
1783 }
1784 }
1785 }
1786 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1787 FieldLine, FieldSize, FieldAlign,
1788 FieldOffset, Flags, FieldTy,
1789 PropertyNode);
1790 EltTys.push_back(FieldTy);
1791 }
1792
1793 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001794 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001795
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001797 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001798}
1799
1800llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1801 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1802 int64_t Count = Ty->getNumElements();
1803 if (Count == 0)
1804 // If number of elements are not known then this is an unbounded array.
1805 // Use Count == -1 to express such arrays.
1806 Count = -1;
1807
1808 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1809 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1810
1811 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1812 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1813
1814 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1815}
1816
1817llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1818 llvm::DIFile Unit) {
1819 uint64_t Size;
1820 uint64_t Align;
1821
1822 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1823 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1824 Size = 0;
1825 Align =
1826 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1827 } else if (Ty->isIncompleteArrayType()) {
1828 Size = 0;
1829 if (Ty->getElementType()->isIncompleteType())
1830 Align = 0;
1831 else
1832 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001833 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 Size = 0;
1835 Align = 0;
1836 } else {
1837 // Size and align of the whole array, not the element type.
1838 Size = CGM.getContext().getTypeSize(Ty);
1839 Align = CGM.getContext().getTypeAlign(Ty);
1840 }
1841
1842 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1843 // interior arrays, do we care? Why aren't nested arrays represented the
1844 // obvious/recursive way?
1845 SmallVector<llvm::Value *, 8> Subscripts;
1846 QualType EltTy(Ty, 0);
1847 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1848 // If the number of elements is known, then count is that number. Otherwise,
1849 // it's -1. This allows us to represent a subrange with an array of 0
1850 // elements, like this:
1851 //
1852 // struct foo {
1853 // int x[0];
1854 // };
1855 int64_t Count = -1; // Count == -1 is an unbounded array.
1856 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1857 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001858
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 // FIXME: Verify this is right for VLAs.
1860 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1861 EltTy = Ty->getElementType();
1862 }
1863
1864 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1865
Eric Christopherb2a008c2013-05-16 00:45:12 +00001866 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1868 SubscriptArray);
1869 return DbgTy;
1870}
1871
Eric Christopherb2a008c2013-05-16 00:45:12 +00001872llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001874 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 Ty, Ty->getPointeeType(), Unit);
1876}
1877
Eric Christopherb2a008c2013-05-16 00:45:12 +00001878llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001880 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 Ty, Ty->getPointeeType(), Unit);
1882}
1883
Eric Christopherb2a008c2013-05-16 00:45:12 +00001884llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001886 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1887 if (!Ty->getPointeeType()->isFunctionType())
1888 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001889 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001890
1891 const FunctionProtoType *FPT =
1892 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001893 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001894 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1895 FPT->getTypeQuals())),
1896 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001897}
1898
Eric Christopherb2a008c2013-05-16 00:45:12 +00001899llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 llvm::DIFile U) {
1901 // Ignore the atomic wrapping
1902 // FIXME: What is the correct representation?
1903 return getOrCreateType(Ty->getValueType(), U);
1904}
1905
1906/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001907llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001908 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001909 uint64_t Size = 0;
1910 uint64_t Align = 0;
1911 if (!ED->getTypeForDecl()->isIncompleteType()) {
1912 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1913 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1914 }
1915
Manman Rene0064d82013-08-29 23:19:58 +00001916 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1917
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 // If this is just a forward declaration, construct an appropriately
1919 // marked node and just return it.
1920 if (!ED->getDefinition()) {
1921 llvm::DIDescriptor EDContext;
1922 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1923 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1924 unsigned Line = getLineNumber(ED->getLocation());
1925 StringRef EDName = ED->getName();
David Blaikief427b002014-05-06 03:42:01 +00001926 llvm::DIType RetTy = DBuilder.createReplaceableForwardDecl(
1927 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1928 0, Size, Align, FullName);
1929 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
1930 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 }
1932
David Blaikie483a9da2014-05-06 18:35:21 +00001933 return CreateTypeDefinition(Ty);
1934}
1935
1936llvm::DIType CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1937 const EnumDecl *ED = Ty->getDecl();
1938 uint64_t Size = 0;
1939 uint64_t Align = 0;
1940 if (!ED->getTypeForDecl()->isIncompleteType()) {
1941 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1942 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1943 }
1944
1945 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1946
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 // Create DIEnumerator elements for each enumerator.
1948 SmallVector<llvm::Value *, 16> Enumerators;
1949 ED = ED->getDefinition();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001950 for (const auto *Enum : ED->enumerators()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 Enumerators.push_back(
1952 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001953 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 }
1955
1956 // Return a CompositeType for the enum itself.
1957 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1958
1959 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1960 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001961 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001962 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001963 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001964 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001965 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001966 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1967 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001968 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 return DbgTy;
1970}
1971
David Blaikie05491062013-01-21 04:37:12 +00001972static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1973 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001974 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001975 Qualifiers InnerQuals = T.getLocalQualifiers();
1976 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1977 // that is already there.
1978 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1979 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001980 QualType LastT = T;
1981 switch (T->getTypeClass()) {
1982 default:
David Blaikie05491062013-01-21 04:37:12 +00001983 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00001984 case Type::TemplateSpecialization: {
1985 const auto *Spec = cast<TemplateSpecializationType>(T);
1986 if (Spec->isTypeAlias())
1987 return C.getQualifiedType(T.getTypePtr(), Quals);
1988 T = Spec->desugar();
1989 break; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 case Type::TypeOfExpr:
1991 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1992 break;
1993 case Type::TypeOf:
1994 T = cast<TypeOfType>(T)->getUnderlyingType();
1995 break;
1996 case Type::Decltype:
1997 T = cast<DecltypeType>(T)->getUnderlyingType();
1998 break;
1999 case Type::UnaryTransform:
2000 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2001 break;
2002 case Type::Attributed:
2003 T = cast<AttributedType>(T)->getEquivalentType();
2004 break;
2005 case Type::Elaborated:
2006 T = cast<ElaboratedType>(T)->getNamedType();
2007 break;
2008 case Type::Paren:
2009 T = cast<ParenType>(T)->getInnerType();
2010 break;
David Blaikie05491062013-01-21 04:37:12 +00002011 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00002012 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 break;
2014 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00002015 QualType DT = cast<AutoType>(T)->getDeducedType();
2016 if (DT.isNull())
2017 return T;
2018 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 break;
2020 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002021
Guy Benyei11169dd2012-12-18 14:30:41 +00002022 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00002023 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 } while (true);
2025}
2026
Eric Christopher0fdcb312013-05-16 00:52:20 +00002027/// getType - Get the type from the cache or return null type if it doesn't
2028/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00002029llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2030
2031 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002032 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002033
David Blaikief427b002014-05-06 03:42:01 +00002034 auto it = TypeCache.find(Ty.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 if (it != TypeCache.end()) {
2036 // Verify that the debug info still exists.
2037 if (llvm::Value *V = it->second)
2038 return llvm::DIType(cast<llvm::MDNode>(V));
2039 }
2040
2041 return llvm::DIType();
2042}
2043
David Blaikie0e716b42014-03-03 23:48:23 +00002044void CGDebugInfo::completeTemplateDefinition(
2045 const ClassTemplateSpecializationDecl &SD) {
David Blaikie0856f662014-03-04 22:01:08 +00002046 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2047 return;
2048
David Blaikie0e716b42014-03-03 23:48:23 +00002049 completeClassData(&SD);
2050 // In case this type has no member function definitions being emitted, ensure
2051 // it is retained
2052 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2053}
2054
Guy Benyei11169dd2012-12-18 14:30:41 +00002055/// getOrCreateType - Get the type from the cache or create a new
2056/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002057llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002058 if (Ty.isNull())
2059 return llvm::DIType();
2060
2061 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002062 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002063
David Blaikieef8a9512014-05-05 23:23:53 +00002064 if (llvm::DIType T = getTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002065 return T;
2066
2067 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002068 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002069 void* TyPtr = Ty.getAsOpaquePtr();
2070
2071 // And update the type cache.
2072 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002073
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 return Res;
2075}
2076
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002077/// Currently the checksum of an interface includes the number of
2078/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002079unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002080 // The assumption is that the number of ivars can only increase
2081 // monotonically, so it is safe to just use their current number as
2082 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002083 unsigned Sum = 0;
2084 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2085 Ivar != 0; Ivar = Ivar->getNextIvar())
2086 ++Sum;
2087
2088 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002089}
2090
2091ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2092 switch (Ty->getTypeClass()) {
2093 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002094 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2095 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002096 case Type::ObjCInterface:
2097 return cast<ObjCInterfaceType>(Ty)->getDecl();
2098 default:
2099 return 0;
2100 }
2101}
2102
Guy Benyei11169dd2012-12-18 14:30:41 +00002103/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002104llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 // Handle qualifiers, which recursively handles what they refer to.
2106 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002107 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002108
2109 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002110
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 // Work out details of type.
2112 switch (Ty->getTypeClass()) {
2113#define TYPE(Class, Base)
2114#define ABSTRACT_TYPE(Class, Base)
2115#define NON_CANONICAL_TYPE(Class, Base)
2116#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2117#include "clang/AST/TypeNodes.def"
2118 llvm_unreachable("Dependent types cannot show up in debug information");
2119
2120 case Type::ExtVector:
2121 case Type::Vector:
2122 return CreateType(cast<VectorType>(Ty), Unit);
2123 case Type::ObjCObjectPointer:
2124 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2125 case Type::ObjCObject:
2126 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2127 case Type::ObjCInterface:
2128 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2129 case Type::Builtin:
2130 return CreateType(cast<BuiltinType>(Ty));
2131 case Type::Complex:
2132 return CreateType(cast<ComplexType>(Ty));
2133 case Type::Pointer:
2134 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002135 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002136 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002137 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002138 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002139 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002140 case Type::BlockPointer:
2141 return CreateType(cast<BlockPointerType>(Ty), Unit);
2142 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002143 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002145 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002147 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 case Type::FunctionProto:
2149 case Type::FunctionNoProto:
2150 return CreateType(cast<FunctionType>(Ty), Unit);
2151 case Type::ConstantArray:
2152 case Type::VariableArray:
2153 case Type::IncompleteArray:
2154 return CreateType(cast<ArrayType>(Ty), Unit);
2155
2156 case Type::LValueReference:
2157 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2158 case Type::RValueReference:
2159 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2160
2161 case Type::MemberPointer:
2162 return CreateType(cast<MemberPointerType>(Ty), Unit);
2163
2164 case Type::Atomic:
2165 return CreateType(cast<AtomicType>(Ty), Unit);
2166
Guy Benyei11169dd2012-12-18 14:30:41 +00002167 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00002168 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2169
2170 case Type::Attributed:
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 case Type::Elaborated:
2172 case Type::Paren:
2173 case Type::SubstTemplateTypeParm:
2174 case Type::TypeOfExpr:
2175 case Type::TypeOf:
2176 case Type::Decltype:
2177 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002178 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002179 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002180 case Type::Auto:
2181 Diag = "auto";
2182 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002184
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 assert(Diag && "Fall through without a diagnostic?");
2186 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2187 "debug information for %0 is not yet supported");
2188 CGM.getDiags().Report(DiagID)
2189 << Diag;
2190 return llvm::DIType();
2191}
2192
2193/// getOrCreateLimitedType - Get the type from the cache or create a new
2194/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002195llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002196 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002197 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002198
David Blaikie8d5e1282013-08-20 21:03:29 +00002199 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002200
2201 // We may have cached a forward decl when we could have created
2202 // a non-forward decl. Go ahead and create a non-forward decl
2203 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002204 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002205
2206 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002207 llvm::DICompositeType Res = CreateLimitedType(Ty);
2208
2209 // Propagate members from the declaration to the definition
2210 // CreateType(const RecordType*) will overwrite this with the members in the
2211 // correct order if the full type is needed.
2212 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002213
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002215 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002216 return Res;
2217}
2218
2219// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002220llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002222
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 // Get overall information about the record type for the debug info.
2224 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2225 unsigned Line = getLineNumber(RD->getLocation());
2226 StringRef RDName = getClassName(RD);
2227
Eric Christopher07429ff2013-10-15 21:22:34 +00002228 llvm::DIDescriptor RDContext =
2229 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002230
David Blaikied2785892013-08-18 17:36:19 +00002231 // If we ended up creating the type during the context chain construction,
2232 // just return that.
David Blaikie8d5e1282013-08-20 21:03:29 +00002233 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2234 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002235 return T;
2236
Adrian Prantl381e7552014-02-04 21:29:50 +00002237 // If this is just a forward or incomplete declaration, construct an
2238 // appropriately marked node and just return it.
2239 const RecordDecl *D = RD->getDefinition();
2240 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002241 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002242
2243 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2244 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002245 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002246
Manman Rene0064d82013-08-29 23:19:58 +00002247 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2248
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 if (RD->isUnion())
2250 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002251 Size, Align, 0, llvm::DIArray(), 0,
2252 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 else if (RD->isClass()) {
2254 // FIXME: This could be a struct type giving a default visibility different
2255 // than C++ class type, but needs llvm metadata changes first.
2256 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002257 Size, Align, 0, 0, llvm::DIType(),
2258 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002259 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 } else
2261 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002262 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002263 llvm::DIArray(), 0, llvm::DIType(),
2264 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002265
2266 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002267 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002268
David Blaikieadfbf992013-08-18 16:55:33 +00002269 if (const ClassTemplateSpecializationDecl *TSpecial =
2270 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2271 RealDecl.setTypeArray(llvm::DIArray(),
2272 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002273 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002274}
2275
David Blaikieadfbf992013-08-18 16:55:33 +00002276void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2277 llvm::DICompositeType RealDecl) {
2278 // A class's primary base or the class itself contains the vtable.
2279 llvm::DICompositeType ContainingType;
2280 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2281 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002282 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002283 while (1) {
2284 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2285 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2286 if (PBT && !BRL.isPrimaryBaseVirtual())
2287 PBase = PBT;
2288 else
2289 break;
2290 }
2291 ContainingType = llvm::DICompositeType(
2292 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2293 getOrCreateFile(RD->getLocation())));
2294 } else if (RD->isDynamicClass())
2295 ContainingType = RealDecl;
2296
2297 RealDecl.setContainingType(ContainingType);
2298}
2299
Guy Benyei11169dd2012-12-18 14:30:41 +00002300/// CreateMemberType - Create new member and increase Offset by FType's size.
2301llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2302 StringRef Name,
2303 uint64_t *Offset) {
2304 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2305 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2306 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2307 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2308 FieldSize, FieldAlign,
2309 *Offset, 0, FieldTy);
2310 *Offset += FieldSize;
2311 return Ty;
2312}
2313
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002314llvm::DIScope CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00002315 // We only need a declaration (not a definition) of the type - so use whatever
2316 // we would otherwise do to get a type for a pointee. (forward declarations in
2317 // limited debug info, full definitions (if the type definition is available)
2318 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002319 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2320 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002321 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002322 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2323 // This doesn't handle providing declarations (for functions or variables) for
2324 // entities without definitions in this TU, nor when the definition proceeds
2325 // the call to this function.
2326 // FIXME: This should be split out into more specific maps with support for
2327 // emitting forward declarations and merging definitions with declarations,
2328 // the same way as we do for types.
2329 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2330 DeclCache.find(D->getCanonicalDecl());
2331 if (I == DeclCache.end())
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002332 return llvm::DIScope();
David Blaikiebd483762013-05-20 04:58:53 +00002333 llvm::Value *V = I->second;
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002334 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikiebd483762013-05-20 04:58:53 +00002335}
2336
Guy Benyei11169dd2012-12-18 14:30:41 +00002337/// getFunctionDeclaration - Return debug info descriptor to describe method
2338/// declaration for the given method definition.
2339llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002340 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2341 return llvm::DISubprogram();
2342
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2344 if (!FD) return llvm::DISubprogram();
2345
2346 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002347 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002348
2349 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2350 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002351 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002352 if (const CXXMethodDecl *MD =
2353 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002354 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002355 llvm::DISubprogram SP =
2356 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002357 return SP;
2358 }
2359 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 if (MI != SPCache.end()) {
2361 llvm::Value *V = MI->second;
2362 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002363 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 return SP;
2365 }
2366
Aaron Ballman86c93902014-03-06 23:45:36 +00002367 for (auto NextFD : FD->redecls()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2369 MI = SPCache.find(NextFD->getCanonicalDecl());
2370 if (MI != SPCache.end()) {
2371 llvm::Value *V = MI->second;
2372 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002373 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 return SP;
2375 }
2376 }
2377 return llvm::DISubprogram();
2378}
2379
2380// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2381// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002382llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2383 QualType FnType,
2384 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002385 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2386 // Create fake but valid subroutine type. Otherwise
2387 // llvm::DISubprogram::Verify() would return false, and
2388 // subprogram DIE will miss DW_AT_decl_file and
2389 // DW_AT_decl_line fields.
2390 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002391
2392 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2393 return getOrCreateMethodType(Method, F);
2394 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2395 // Add "self" and "_cmd"
2396 SmallVector<llvm::Value *, 16> Elts;
2397
2398 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002399 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002400
2401 // Replace the instancetype keyword with the actual type.
2402 if (ResultTy == CGM.getContext().getObjCInstanceType())
2403 ResultTy = CGM.getContext().getPointerType(
2404 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2405
Adrian Prantl7bec9032013-05-10 21:08:31 +00002406 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002408 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2409 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2410 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 // "_cmd" pointer is always second argument.
2412 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2413 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2414 // Get rest of the arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002415 for (const auto *PI : OMethod->params())
2416 Elts.push_back(getOrCreateType(PI->getType(), F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002417
2418 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2419 return DBuilder.createSubroutineType(F, EltTypeArray);
2420 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002421
Adrian Prantl800faef2014-02-25 23:42:18 +00002422 // Handle variadic function types; they need an additional
2423 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002424 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2425 if (FD->isVariadic()) {
2426 SmallVector<llvm::Value *, 16> EltTys;
2427 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2428 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2429 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2430 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2431 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2432 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2433 return DBuilder.createSubroutineType(F, EltTypeArray);
2434 }
2435
David Blaikie469f0792013-05-22 23:22:42 +00002436 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002437}
2438
2439/// EmitFunctionStart - Constructs the debug code for entering a function.
Adrian Prantl42d71b92014-04-10 23:21:53 +00002440void CGDebugInfo::EmitFunctionStart(GlobalDecl GD,
2441 SourceLocation Loc,
2442 SourceLocation ScopeLoc,
2443 QualType FnType,
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 llvm::Function *Fn,
2445 CGBuilderTy &Builder) {
2446
2447 StringRef Name;
2448 StringRef LinkageName;
2449
2450 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2451
2452 const Decl *D = GD.getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 bool HasDecl = (D != 0);
Eric Christopher885c41b2014-04-01 22:25:28 +00002454
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 unsigned Flags = 0;
2456 llvm::DIFile Unit = getOrCreateFile(Loc);
2457 llvm::DIDescriptor FDContext(Unit);
2458 llvm::DIArray TParamsArray;
2459 if (!HasDecl) {
2460 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002461 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2463 // If there is a DISubprogram for this function available then use it.
2464 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2465 FI = SPCache.find(FD->getCanonicalDecl());
2466 if (FI != SPCache.end()) {
2467 llvm::Value *V = FI->second;
2468 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2469 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2470 llvm::MDNode *SPN = SP;
2471 LexicalBlockStack.push_back(SPN);
2472 RegionMap[D] = llvm::WeakVH(SP);
2473 return;
2474 }
2475 }
2476 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002477 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 if (FD->hasPrototype()) {
2479 LinkageName = CGM.getMangledName(GD);
2480 Flags |= llvm::DIDescriptor::FlagPrototyped;
2481 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002482 // No need to replicate the linkage name if it isn't different from the
2483 // subprogram name, no need to have it at all unless coverage is enabled or
2484 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002486 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2487 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002488 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 LinkageName = StringRef();
2490
Eric Christopher75e17682013-05-16 00:45:23 +00002491 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Eric Christopher4cbd0d9d2014-03-27 05:29:34 +00002492 if (const NamespaceDecl *NSDecl =
2493 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2494 FDContext = getOrCreateNameSpace(NSDecl);
2495 else if (const RecordDecl *RDecl =
2496 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2497 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2498
2499 // Collect template parameters.
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2501 }
2502 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2503 Name = getObjCMethodName(OMD);
2504 Flags |= llvm::DIDescriptor::FlagPrototyped;
2505 } else {
2506 // Use llvm function name.
2507 Name = Fn->getName();
2508 Flags |= llvm::DIDescriptor::FlagPrototyped;
2509 }
2510 if (!Name.empty() && Name[0] == '\01')
2511 Name = Name.substr(1);
2512
Adrian Prantl42d71b92014-04-10 23:21:53 +00002513 if (!HasDecl || D->isImplicit()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 Flags |= llvm::DIDescriptor::FlagArtificial;
Adrian Prantl42d71b92014-04-10 23:21:53 +00002515 // Artificial functions without a location should not silently reuse CurLoc.
2516 if (Loc.isInvalid())
2517 CurLoc = SourceLocation();
2518 }
2519 unsigned LineNo = getLineNumber(Loc);
2520 unsigned ScopeLine = getLineNumber(ScopeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002521
Eric Christopher8018e412014-03-27 18:50:35 +00002522 // FIXME: The function declaration we're constructing here is mostly reusing
2523 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2524 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2525 // all subprograms instead of the actual context since subprogram definitions
2526 // are emitted as CU level entities by the backend.
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002527 llvm::DISubprogram SP =
2528 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2529 getOrCreateFunctionType(D, FnType, Unit),
2530 Fn->hasInternalLinkage(), true /*definition*/,
Adrian Prantl42d71b92014-04-10 23:21:53 +00002531 ScopeLine, Flags,
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002532 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2533 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002534 if (HasDecl)
2535 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002536
Adrian Prantlbebb8932014-03-21 21:01:58 +00002537 // Push the function onto the lexical block stack.
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 llvm::MDNode *SPN = SP;
2539 LexicalBlockStack.push_back(SPN);
Adrian Prantlbebb8932014-03-21 21:01:58 +00002540
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 if (HasDecl)
2542 RegionMap[D] = llvm::WeakVH(SP);
2543}
2544
2545/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002546/// information in the source file. If the location is invalid, the
2547/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002548void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002549 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 // Update our current location
2551 setLocation(Loc);
2552
2553 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2554
2555 // Don't bother if things are the same as last time.
2556 SourceManager &SM = CGM.getContext().getSourceManager();
2557 if (CurLoc == PrevLoc ||
2558 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2559 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002560 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2561 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2562 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002564
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 // Update last state.
2566 PrevLoc = CurLoc;
2567
Adrian Prantle83b1302014-01-07 22:05:52 +00002568 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002569 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2570 (getLineNumber(CurLoc),
2571 getColumnNumber(CurLoc, ForceColumnInfo),
2572 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002573}
2574
2575/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2576/// the stack.
2577void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2578 llvm::DIDescriptor D =
2579 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2580 llvm::DIDescriptor() :
2581 llvm::DIDescriptor(LexicalBlockStack.back()),
2582 getOrCreateFile(CurLoc),
2583 getLineNumber(CurLoc),
Diego Novilloe6d398182014-03-03 18:53:32 +00002584 getColumnNumber(CurLoc),
2585 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 llvm::MDNode *DN = D;
2587 LexicalBlockStack.push_back(DN);
2588}
2589
2590/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2591/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002592void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2593 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 // Set our current location.
2595 setLocation(Loc);
2596
2597 // Create a new lexical block and push it on the stack.
2598 CreateLexicalBlock(Loc);
2599
2600 // Emit a line table change for the current location inside the new scope.
2601 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2602 getColumnNumber(Loc),
2603 LexicalBlockStack.back()));
2604}
2605
2606/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2607/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002608void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2609 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2611
2612 // Provide an entry in the line table for the end of the block.
2613 EmitLocation(Builder, Loc);
2614
2615 LexicalBlockStack.pop_back();
2616}
2617
2618/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2619void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2620 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2621 unsigned RCount = FnBeginRegionCount.back();
2622 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2623
2624 // Pop all regions for this function.
2625 while (LexicalBlockStack.size() != RCount)
2626 EmitLexicalBlockEnd(Builder, CurLoc);
2627 FnBeginRegionCount.pop_back();
2628}
2629
Eric Christopherb2a008c2013-05-16 00:45:12 +00002630// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002631// See BuildByRefType.
2632llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2633 uint64_t *XOffset) {
2634
2635 SmallVector<llvm::Value *, 5> EltTys;
2636 QualType FType;
2637 uint64_t FieldSize, FieldOffset;
2638 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002641 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002642
2643 FieldOffset = 0;
2644 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2645 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2646 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2647 FType = CGM.getContext().IntTy;
2648 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2649 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2650
2651 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2652 if (HasCopyAndDispose) {
2653 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2654 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2655 &FieldOffset));
2656 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2657 &FieldOffset));
2658 }
2659 bool HasByrefExtendedLayout;
2660 Qualifiers::ObjCLifetime Lifetime;
2661 if (CGM.getContext().getByrefLifetime(Type,
2662 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002663 && HasByrefExtendedLayout) {
2664 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 EltTys.push_back(CreateMemberType(Unit, FType,
2666 "__byref_variable_layout",
2667 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002668 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002669
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2671 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002672 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002673 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2675 CharUnits AlignedOffsetInBytes
2676 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2677 CharUnits NumPaddingBytes
2678 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 if (NumPaddingBytes.isPositive()) {
2681 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2682 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2683 pad, ArrayType::Normal, 0);
2684 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2685 }
2686 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002687
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 FType = Type;
David Blaikief427b002014-05-06 03:42:01 +00002689 llvm::DIType FieldTy = getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 FieldSize = CGM.getContext().getTypeSize(FType);
2691 FieldAlign = CGM.getContext().toBits(Align);
2692
Eric Christopherb2a008c2013-05-16 00:45:12 +00002693 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2695 0, FieldSize, FieldAlign,
2696 FieldOffset, 0, FieldTy);
2697 EltTys.push_back(FieldTy);
2698 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002699
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002701
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002703
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002705 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002706}
2707
2708/// EmitDeclare - Emit local variable declaration debug info.
2709void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002710 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002712 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2714
David Blaikie7fceebf2013-08-19 03:37:48 +00002715 bool Unwritten =
2716 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2717 cast<Decl>(VD->getDeclContext())->isImplicit());
2718 llvm::DIFile Unit;
2719 if (!Unwritten)
2720 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 llvm::DIType Ty;
2722 uint64_t XOffset = 0;
2723 if (VD->hasAttr<BlocksAttr>())
2724 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002725 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 Ty = getOrCreateType(VD->getType(), Unit);
2727
2728 // If there is no debug info for this type then do not emit debug info
2729 // for this variable.
2730 if (!Ty)
2731 return;
2732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002734 unsigned Line = 0;
2735 unsigned Column = 0;
2736 if (!Unwritten) {
2737 Line = getLineNumber(VD->getLocation());
2738 Column = getColumnNumber(VD->getLocation());
2739 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 unsigned Flags = 0;
2741 if (VD->isImplicit())
2742 Flags |= llvm::DIDescriptor::FlagArtificial;
2743 // If this is the first argument and it is implicit then
2744 // give it an object pointer flag.
2745 // FIXME: There has to be a better way to do this, but for static
2746 // functions there won't be an implicit param at arg1 and
2747 // otherwise it is 'self' or 'this'.
2748 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2749 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002750 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002751 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2752 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002753 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754
2755 llvm::MDNode *Scope = LexicalBlockStack.back();
2756
2757 StringRef Name = VD->getName();
2758 if (!Name.empty()) {
2759 if (VD->hasAttr<BlocksAttr>()) {
2760 CharUnits offset = CharUnits::fromQuantity(32);
2761 SmallVector<llvm::Value *, 9> addr;
2762 llvm::Type *Int64Ty = CGM.Int64Ty;
2763 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2764 // offset of __forwarding field
2765 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002766 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2768 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2769 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2770 // offset of x field
2771 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2772 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2773
2774 // Create the descriptor for the variable.
2775 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002776 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 llvm::DIDescriptor(Scope),
2778 VD->getName(), Unit, Line, Ty,
2779 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002780
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 // Insert an llvm.dbg.declare into the current block.
2782 llvm::Instruction *Call =
2783 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2784 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2785 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002786 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002787 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002788 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2789 // If VD is an anonymous union then Storage represents value for
2790 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002792 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002793 for (const auto *Field : RD->fields()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2795 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002796
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 // Ignore unnamed fields. Do not ignore unnamed records.
2798 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2799 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002800
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 // Use VarDecl's Tag, Scope and Line number.
2802 llvm::DIVariable D =
2803 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002804 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 CGM.getLangOpts().Optimize, Flags,
2806 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002807
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 // Insert an llvm.dbg.declare into the current block.
2809 llvm::Instruction *Call =
2810 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2811 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2812 }
David Blaikie219c7d92013-01-05 20:03:07 +00002813 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 }
2815 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002816
2817 // Create the descriptor for the variable.
2818 llvm::DIVariable D =
2819 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2820 Name, Unit, Line, Ty,
2821 CGM.getLangOpts().Optimize, Flags, ArgNo);
2822
2823 // Insert an llvm.dbg.declare into the current block.
2824 llvm::Instruction *Call =
2825 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2826 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002827}
2828
2829void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2830 llvm::Value *Storage,
2831 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002832 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2834}
2835
Adrian Prantlde17db32013-03-29 19:20:29 +00002836/// Look up the completed type for a self pointer in the TypeCache and
2837/// create a copy of it with the ObjectPointer and Artificial flags
2838/// set. If the type is not cached, a new one is created. This should
2839/// never happen though, since creating a type for the implicit self
2840/// argument implies that we already parsed the interface definition
2841/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002842llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2843 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002844 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002845 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002846 return DBuilder.createObjectPointerType(Ty);
2847}
2848
Guy Benyei11169dd2012-12-18 14:30:41 +00002849void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2850 llvm::Value *Storage,
2851 CGBuilderTy &Builder,
2852 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002853 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002855
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 if (Builder.GetInsertBlock() == 0)
2857 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002858
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002860
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 uint64_t XOffset = 0;
2862 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2863 llvm::DIType Ty;
2864 if (isByRef)
2865 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002866 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002867 Ty = getOrCreateType(VD->getType(), Unit);
2868
2869 // Self is passed along as an implicit non-arg variable in a
2870 // block. Mark it as the object pointer.
2871 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002872 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002873
2874 // Get location information.
2875 unsigned Line = getLineNumber(VD->getLocation());
2876 unsigned Column = getColumnNumber(VD->getLocation());
2877
2878 const llvm::DataLayout &target = CGM.getDataLayout();
2879
2880 CharUnits offset = CharUnits::fromQuantity(
2881 target.getStructLayout(blockInfo.StructureType)
2882 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2883
2884 SmallVector<llvm::Value *, 9> addr;
2885 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002886 if (isa<llvm::AllocaInst>(Storage))
2887 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2889 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2890 if (isByRef) {
2891 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2892 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2893 // offset of __forwarding field
2894 offset = CGM.getContext()
2895 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2896 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2897 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2898 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2899 // offset of x field
2900 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2901 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2902 }
2903
2904 // Create the descriptor for the variable.
2905 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002906 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 llvm::DIDescriptor(LexicalBlockStack.back()),
2908 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002909
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 // Insert an llvm.dbg.declare into the current block.
2911 llvm::Instruction *Call =
2912 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2913 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2914 LexicalBlockStack.back()));
2915}
2916
2917/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2918/// variable declaration.
2919void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2920 unsigned ArgNo,
2921 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002922 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2924}
2925
2926namespace {
2927 struct BlockLayoutChunk {
2928 uint64_t OffsetInBits;
2929 const BlockDecl::Capture *Capture;
2930 };
2931 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2932 return l.OffsetInBits < r.OffsetInBits;
2933 }
2934}
2935
2936void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002937 llvm::Value *Arg,
2938 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002940 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 ASTContext &C = CGM.getContext();
2942 const BlockDecl *blockDecl = block.getBlockDecl();
2943
2944 // Collect some general information about the block's location.
2945 SourceLocation loc = blockDecl->getCaretLocation();
2946 llvm::DIFile tunit = getOrCreateFile(loc);
2947 unsigned line = getLineNumber(loc);
2948 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002949
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 // Build the debug-info type for the block literal.
2951 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2952
2953 const llvm::StructLayout *blockLayout =
2954 CGM.getDataLayout().getStructLayout(block.StructureType);
2955
2956 SmallVector<llvm::Value*, 16> fields;
2957 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2958 blockLayout->getElementOffsetInBits(0),
2959 tunit, tunit));
2960 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2961 blockLayout->getElementOffsetInBits(1),
2962 tunit, tunit));
2963 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2964 blockLayout->getElementOffsetInBits(2),
2965 tunit, tunit));
2966 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2967 blockLayout->getElementOffsetInBits(3),
2968 tunit, tunit));
2969 fields.push_back(createFieldType("__descriptor",
2970 C.getPointerType(block.NeedsCopyDispose ?
2971 C.getBlockDescriptorExtendedType() :
2972 C.getBlockDescriptorType()),
2973 0, loc, AS_public,
2974 blockLayout->getElementOffsetInBits(4),
2975 tunit, tunit));
2976
2977 // We want to sort the captures by offset, not because DWARF
2978 // requires this, but because we're paranoid about debuggers.
2979 SmallVector<BlockLayoutChunk, 8> chunks;
2980
2981 // 'this' capture.
2982 if (blockDecl->capturesCXXThis()) {
2983 BlockLayoutChunk chunk;
2984 chunk.OffsetInBits =
2985 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2986 chunk.Capture = 0;
2987 chunks.push_back(chunk);
2988 }
2989
2990 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002991 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 const VarDecl *variable = capture.getVariable();
2993 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2994
2995 // Ignore constant captures.
2996 if (captureInfo.isConstant())
2997 continue;
2998
2999 BlockLayoutChunk chunk;
3000 chunk.OffsetInBits =
3001 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3002 chunk.Capture = &capture;
3003 chunks.push_back(chunk);
3004 }
3005
3006 // Sort by offset.
3007 llvm::array_pod_sort(chunks.begin(), chunks.end());
3008
3009 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3010 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3011 uint64_t offsetInBits = i->OffsetInBits;
3012 const BlockDecl::Capture *capture = i->Capture;
3013
3014 // If we have a null capture, this must be the C++ 'this' capture.
3015 if (!capture) {
3016 const CXXMethodDecl *method =
3017 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3018 QualType type = method->getThisType(C);
3019
3020 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3021 offsetInBits, tunit, tunit));
3022 continue;
3023 }
3024
3025 const VarDecl *variable = capture->getVariable();
3026 StringRef name = variable->getName();
3027
3028 llvm::DIType fieldType;
3029 if (capture->isByRef()) {
3030 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3031
3032 // FIXME: this creates a second copy of this type!
3033 uint64_t xoffset;
3034 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3035 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3036 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3037 ptrInfo.first, ptrInfo.second,
3038 offsetInBits, 0, fieldType);
3039 } else {
3040 fieldType = createFieldType(name, variable->getType(), 0,
3041 loc, AS_public, offsetInBits, tunit, tunit);
3042 }
3043 fields.push_back(fieldType);
3044 }
3045
3046 SmallString<36> typeName;
3047 llvm::raw_svector_ostream(typeName)
3048 << "__block_literal_" << CGM.getUniqueBlockCount();
3049
3050 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3051
3052 llvm::DIType type =
3053 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3054 CGM.getContext().toBits(block.BlockSize),
3055 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003056 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3058
3059 // Get overall information about the block.
3060 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3061 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062
3063 // Create the descriptor for the parameter.
3064 llvm::DIVariable debugVar =
3065 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003066 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003067 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003069 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3070
Adrian Prantl616bef42013-03-14 21:52:59 +00003071 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003072 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003073 llvm::Instruction *DbgVal =
3074 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003075 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003076 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3077 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003078
Adrian Prantl616bef42013-03-14 21:52:59 +00003079 // Insert an llvm.dbg.declare into the current block.
3080 llvm::Instruction *DbgDecl =
3081 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3082 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003083}
3084
David Blaikie6943dea2013-08-20 01:28:15 +00003085/// If D is an out-of-class definition of a static data member of a class, find
3086/// its corresponding in-class declaration.
3087llvm::DIDerivedType
3088CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3089 if (!D->isStaticDataMember())
3090 return llvm::DIDerivedType();
3091 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3092 StaticDataMemberCache.find(D->getCanonicalDecl());
3093 if (MI != StaticDataMemberCache.end()) {
3094 assert(MI->second && "Static data member declaration should still exist");
3095 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003096 }
David Blaikiece763042013-08-20 21:49:21 +00003097
3098 // If the member wasn't found in the cache, lazily construct and add it to the
3099 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003100 llvm::DICompositeType Ctxt(
3101 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3102 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003103 return T;
3104}
3105
Eric Christophercab9fae2014-04-10 05:20:00 +00003106/// Recursively collect all of the member fields of a global anonymous decl and
3107/// create static variables for them. The first time this is called it needs
3108/// to be on a union and then from there we can have additional unnamed fields.
3109llvm::DIGlobalVariable
3110CGDebugInfo::CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit,
3111 unsigned LineNo, StringRef LinkageName,
3112 llvm::GlobalVariable *Var,
3113 llvm::DIDescriptor DContext) {
3114 llvm::DIGlobalVariable GV;
3115
3116 for (const auto *Field : RD->fields()) {
3117 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
3118 StringRef FieldName = Field->getName();
3119
3120 // Ignore unnamed fields, but recurse into anonymous records.
3121 if (FieldName.empty()) {
3122 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3123 if (RT)
3124 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3125 Var, DContext);
3126 continue;
3127 }
3128 // Use VarDecl's Tag, Scope and Line number.
3129 GV = DBuilder.createStaticVariable(DContext, FieldName, LinkageName, Unit,
3130 LineNo, FieldTy,
3131 Var->hasInternalLinkage(), Var,
3132 llvm::DIDerivedType());
3133 }
3134 return GV;
3135}
3136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003138void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003140 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 // Create global variable debug descriptor.
3142 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3143 unsigned LineNo = getLineNumber(D->getLocation());
3144
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003145 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003146
3147 QualType T = D->getType();
3148 if (T->isIncompleteArrayType()) {
3149
3150 // CodeGen turns int[] into int[1] so we'll do the same here.
3151 llvm::APInt ConstVal(32, 1);
3152 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3153
3154 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3155 ArrayType::Normal, 0);
3156 }
Eric Christophercab9fae2014-04-10 05:20:00 +00003157
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003158 StringRef DeclName = D->getName();
3159 StringRef LinkageName;
Eric Christophercab9fae2014-04-10 05:20:00 +00003160 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) &&
3161 !isa<ObjCMethodDecl>(D->getDeclContext()))
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003162 LinkageName = Var->getName();
3163 if (LinkageName == DeclName)
3164 LinkageName = StringRef();
Eric Christophercab9fae2014-04-10 05:20:00 +00003165
Eric Christopherb2a008c2013-05-16 00:45:12 +00003166 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christophercab9fae2014-04-10 05:20:00 +00003168
3169 // Attempt to store one global variable for the declaration - even if we
3170 // emit a lot of fields.
3171 llvm::DIGlobalVariable GV;
3172
3173 // If this is an anonymous union then we'll want to emit a global
3174 // variable for each member of the anonymous union so that it's possible
3175 // to find the name of any field in the union.
3176 if (T->isUnionType() && DeclName.empty()) {
3177 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3178 assert(RD->isAnonymousStructOrUnion() && "unnamed non-anonymous struct or union?");
3179 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3180 } else {
3181 GV = DBuilder.createStaticVariable(
3182 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3183 Var->hasInternalLinkage(), Var,
3184 getOrCreateStaticDataMemberDeclarationOrNull(D));
3185 }
David Blaikiebd483762013-05-20 04:58:53 +00003186 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003187}
3188
3189/// EmitGlobalVariable - Emit information about an objective-c interface.
3190void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3191 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003192 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 // Create global variable debug descriptor.
3194 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3195 unsigned LineNo = getLineNumber(ID->getLocation());
3196
3197 StringRef Name = ID->getName();
3198
3199 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3200 if (T->isIncompleteArrayType()) {
3201
3202 // CodeGen turns int[] into int[1] so we'll do the same here.
3203 llvm::APInt ConstVal(32, 1);
3204 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3205
3206 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3207 ArrayType::Normal, 0);
3208 }
3209
3210 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3211 getOrCreateType(T, Unit),
3212 Var->hasInternalLinkage(), Var);
3213}
3214
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003215/// EmitGlobalVariable - Emit global variable's debug info.
3216void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3217 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003218 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003219 // Create the descriptor for the variable.
3220 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3221 StringRef Name = VD->getName();
3222 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3223 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3224 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3225 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3226 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3227 }
3228 // Do not use DIGlobalVariable for enums.
3229 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3230 return;
David Blaikiea15565562014-04-04 20:56:17 +00003231 // Do not emit separate definitions for function local const/statics.
3232 if (isa<FunctionDecl>(VD->getDeclContext()))
3233 return;
David Blaikiebb113912014-04-05 07:23:17 +00003234 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3235 auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH()));
3236 if (!pair.second)
3237 return;
David Blaikie506a7452014-04-05 07:46:57 +00003238 llvm::DIDescriptor DContext =
3239 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003240 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
David Blaikie506a7452014-04-05 07:46:57 +00003241 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3242 true, Init,
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003243 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikiebb113912014-04-05 07:23:17 +00003244 pair.first->second = llvm::WeakVH(GV);
David Blaikiebd483762013-05-20 04:58:53 +00003245}
3246
3247llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3248 if (!LexicalBlockStack.empty())
3249 return llvm::DIScope(LexicalBlockStack.back());
3250 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003251}
3252
David Blaikie9f88fe82013-04-22 06:13:21 +00003253void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003254 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3255 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003256 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003257 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3258 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003259 getLineNumber(UD.getLocation()));
3260}
3261
David Blaikiebd483762013-05-20 04:58:53 +00003262void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3263 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3264 return;
3265 assert(UD.shadow_size() &&
3266 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3267 // Emitting one decl is sufficient - debuggers can detect that this is an
3268 // overloaded name & provide lookup for all the overloads.
3269 const UsingShadowDecl &USD = **UD.shadow_begin();
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00003270 if (llvm::DIScope Target =
Eric Christopher1ecc5632013-06-07 22:54:39 +00003271 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003272 DBuilder.createImportedDeclaration(
3273 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3274 getLineNumber(USD.getLocation()));
3275}
3276
David Blaikief121b932013-05-20 22:50:41 +00003277llvm::DIImportedEntity
3278CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3279 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3280 return llvm::DIImportedEntity(0);
3281 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3282 if (VH)
3283 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3284 llvm::DIImportedEntity R(0);
3285 if (const NamespaceAliasDecl *Underlying =
3286 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3287 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00003288 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00003289 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3290 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3291 NA.getName());
3292 else
David Blaikie551fb0a2014-04-06 06:30:03 +00003293 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00003294 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3295 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3296 getLineNumber(NA.getLocation()), NA.getName());
3297 VH = R;
3298 return R;
3299}
3300
Guy Benyei11169dd2012-12-18 14:30:41 +00003301/// getOrCreateNamesSpace - Return namespace descriptor for the given
3302/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003303llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003304CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003305 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003306 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 NameSpaceCache.find(NSDecl);
3308 if (I != NameSpaceCache.end())
3309 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003310
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3312 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003313 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003314 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3315 llvm::DINameSpace NS =
3316 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3317 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3318 return NS;
3319}
3320
3321void CGDebugInfo::finalize() {
David Blaikief427b002014-05-06 03:42:01 +00003322 for (auto p : ReplaceMap) {
3323 assert(p.second);
3324 llvm::DIType Ty(cast<llvm::MDNode>(p.second));
David Blaikieb8149042014-05-05 21:21:39 +00003325 assert(Ty.isForwardDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003326
David Blaikief427b002014-05-06 03:42:01 +00003327 auto it = TypeCache.find(p.first);
David Blaikieb8149042014-05-05 21:21:39 +00003328 assert(it != TypeCache.end());
3329 assert(it->second);
Adrian Prantl73409ce2013-03-11 18:33:46 +00003330
David Blaikief427b002014-05-06 03:42:01 +00003331 llvm::DIType RepTy(cast<llvm::MDNode>(it->second));
3332 Ty.replaceAllUsesWith(CGM.getLLVMContext(), RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003334
David Blaikieef8a9512014-05-05 23:23:53 +00003335 for (auto E : ObjCInterfaceCache)
David Blaikief427b002014-05-06 03:42:01 +00003336 E.Decl.replaceAllUsesWith(CGM.getLLVMContext(),
3337 E.Type->getDecl()->getDefinition()
3338 ? CreateTypeDefinition(E.Type, E.Unit)
3339 : E.Decl);
David Blaikieef8a9512014-05-05 23:23:53 +00003340
Adrian Prantl73409ce2013-03-11 18:33:46 +00003341 // We keep our own list of retained types, because we need to look
3342 // up the final type in the type cache.
3343 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3344 RE = RetainedTypes.end(); RI != RE; ++RI)
David Blaikie0856f662014-03-04 22:01:08 +00003345 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003346
Guy Benyei11169dd2012-12-18 14:30:41 +00003347 DBuilder.finalize();
3348}