blob: 048c8f8f3674c22f3e992fdc9ef43e1183475bd6 [file] [log] [blame]
Guy Benyei7f92f2d2012-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 Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-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 Carruth3b844ba2013-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 Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070040#include "llvm/Support/Path.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Stephen Hines651f13c2014-04-23 16:59:28 -070055SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
56 CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
Adrian Prantled6bbe42013-07-18 00:28:02 +000058 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
Adrian Prantled6bbe42013-07-18 00:28:02 +000061 }
62}
63
Stephen Hines651f13c2014-04-23 16:59:28 -070064SaveAndRestoreLocation::~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 Prantled6bbe42013-07-18 00:28:02 +000075NoLocation::~NoLocation() {
Stephen Hines651f13c2014-04-23 16:59:28 -070076 if (DI)
Adrian Prantled6bbe42013-07-18 00:28:02 +000077 assert(Builder.getCurrentDebugLocation().isUnknown());
Adrian Prantled6bbe42013-07-18 00:28:02 +000078}
79
Adrian Prantlb061ce22013-07-18 01:36:04 +000080ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Stephen Hines651f13c2014-04-23 16:59:28 -070081 : SaveAndRestoreLocation(CGF, B) {
82 if (DI)
Adrian Prantlb6cdc962013-07-24 20:34:39 +000083 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Adrian Prantlb6cdc962013-07-24 20:34:39 +000084}
85
86void ArtificialLocation::Emit() {
87 if (DI) {
Adrian Prantled6bbe42013-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 Prantlb6cdc962013-07-24 20:34:39 +000092 assert(!DI->LexicalBlockStack.empty());
93 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000094 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
95 }
96}
97
Adrian Prantlb061ce22013-07-18 01:36:04 +000098ArtificialLocation::~ArtificialLocation() {
Stephen Hines651f13c2014-04-23 16:59:28 -070099 if (DI)
Adrian Prantled6bbe42013-07-18 00:28:02 +0000100 assert(Builder.getCurrentDebugLocation().getLine() == 0);
Adrian Prantled6bbe42013-07-18 00:28:02 +0000101}
102
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000103void CGDebugInfo::setLocation(SourceLocation Loc) {
104 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +0000105 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-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();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700115 llvm::DIScope Scope(LexicalBlockStack.back());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000116 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000117
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700118 if (PCLoc.isInvalid() || Scope.getFilename() == PCLoc.getFilename())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000119 return;
120
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000121 if (Scope.isLexicalBlockFile()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700122 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(Scope);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000123 llvm::DIDescriptor D
124 = DBuilder.createLexicalBlockFile(LBF.getScope(),
125 getOrCreateFile(CurLoc));
126 llvm::MDNode *N = D;
127 LexicalBlockStack.pop_back();
128 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000129 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000130 llvm::DIDescriptor D
131 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
132 llvm::MDNode *N = D;
133 LexicalBlockStack.pop_back();
134 LexicalBlockStack.push_back(N);
135 }
136}
137
138/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000139llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000140 if (!Context)
141 return TheCU;
142
143 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
144 I = RegionMap.find(Context);
145 if (I != RegionMap.end()) {
146 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000147 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000148 }
149
150 // Check namespace.
151 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000152 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000153
David Blaikiebb000792013-04-19 06:56:38 +0000154 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
155 if (!RDecl->isDependentType())
156 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000157 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000158 return TheCU;
159}
160
161/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramere5753592013-09-09 14:48:42 +0000162/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000163/// is stored on the side.
164StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
165 assert (FD && "Invalid FunctionDecl!");
166 IdentifierInfo *FII = FD->getIdentifier();
167 FunctionTemplateSpecializationInfo *Info
168 = FD->getTemplateSpecializationInfo();
169 if (!Info && FII)
170 return FII->getName();
171
172 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000173 SmallString<128> NS;
174 llvm::raw_svector_ostream OS(NS);
175 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000176
177 // Add any template specialization args.
178 if (Info) {
179 const TemplateArgumentList *TArgs = Info->TemplateArguments;
180 const TemplateArgument *Args = TArgs->data();
181 unsigned NumArgs = TArgs->size();
182 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000183 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
184 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000185 }
186
187 // Copy this name on the side and use its reference.
Benjamin Kramer84953792013-09-09 16:39:06 +0000188 return internString(OS.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000189}
190
191StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
192 SmallString<256> MethodName;
193 llvm::raw_svector_ostream OS(MethodName);
194 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
195 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000196 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000197 dyn_cast<const ObjCImplementationDecl>(DC)) {
198 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000199 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCInterfaceDecl>(DC)) {
201 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000202 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCCategoryImplDecl>(DC)){
204 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
205 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000206 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000207 // We can extract the type of the class from the self pointer.
208 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
209 QualType ClassTy =
210 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
211 ClassTy.print(OS, PrintingPolicy(LangOptions()));
212 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000213 }
214 OS << ' ' << OMD->getSelector().getAsString() << ']';
215
Benjamin Kramer84953792013-09-09 16:39:06 +0000216 return internString(OS.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000217}
218
219/// getSelectorName - Return selector name. This is used for debugging
220/// info.
221StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer84953792013-09-09 16:39:06 +0000222 return internString(S.getAsString());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000223}
224
225/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000226StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000227CGDebugInfo::getClassName(const RecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700228 // quick optimization to avoid having to intern strings that are already
229 // stored reliably elsewhere
230 if (!isa<ClassTemplateSpecializationDecl>(RD))
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000231 return RD->getName();
232
Stephen Hines651f13c2014-04-23 16:59:28 -0700233 SmallString<128> Name;
Benjamin Kramer5eada842013-02-22 15:46:01 +0000234 {
Stephen Hines651f13c2014-04-23 16:59:28 -0700235 llvm::raw_svector_ostream OS(Name);
236 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
237 /*Qualified*/ false);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000238 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000239
240 // Copy this name on the side and use its reference.
Stephen Hines651f13c2014-04-23 16:59:28 -0700241 return internString(Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000242}
243
244/// getOrCreateFile - Get the file debug info descriptor for the input location.
245llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
246 if (!Loc.isValid())
247 // If Location is not valid then use main input file.
248 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
249
250 SourceManager &SM = CGM.getContext().getSourceManager();
251 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
252
253 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
254 // If the location is not valid then use main input file.
255 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
256
257 // Cache the results.
258 const char *fname = PLoc.getFilename();
259 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
260 DIFileCache.find(fname);
261
262 if (it != DIFileCache.end()) {
263 // Verify that the information still exists.
264 if (llvm::Value *V = it->second)
265 return llvm::DIFile(cast<llvm::MDNode>(V));
266 }
267
268 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
269
270 DIFileCache[fname] = F;
271 return F;
272}
273
274/// getOrCreateMainFile - Get the file info for main compile unit.
275llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
276 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
277}
278
279/// getLineNumber - Get line number for the location. If location is invalid
280/// then use current location.
281unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
282 if (Loc.isInvalid() && CurLoc.isInvalid())
283 return 0;
284 SourceManager &SM = CGM.getContext().getSourceManager();
285 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
286 return PLoc.isValid()? PLoc.getLine() : 0;
287}
288
289/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000290unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000291 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000292 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000293 return 0;
294
295 // If the location is invalid then use the current column.
296 if (Loc.isInvalid() && CurLoc.isInvalid())
297 return 0;
298 SourceManager &SM = CGM.getContext().getSourceManager();
299 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
300 return PLoc.isValid()? PLoc.getColumn() : 0;
301}
302
303StringRef CGDebugInfo::getCurrentDirname() {
304 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
305 return CGM.getCodeGenOpts().DebugCompilationDir;
306
307 if (!CWDName.empty())
308 return CWDName;
309 SmallString<256> CWD;
310 llvm::sys::fs::current_path(CWD);
Benjamin Kramer84953792013-09-09 16:39:06 +0000311 return CWDName = internString(CWD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000312}
313
314/// CreateCompileUnit - Create new compile unit.
315void CGDebugInfo::CreateCompileUnit() {
316
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700317 // Should we be asking the SourceManager for the main file name, instead of
318 // accepting it as an argument? This just causes the main file name to
319 // mismatch with source locations and create extra lexical scopes or
320 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
321 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
322 // because that's what the SourceManager says)
323
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000324 // Get absolute path name.
325 SourceManager &SM = CGM.getContext().getSourceManager();
326 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
327 if (MainFileName.empty())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700328 MainFileName = "<stdin>";
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000329
330 // The main file name provided via the "-main-file-name" option contains just
331 // the file name itself with no path information. This file name may have had
332 // a relative path, so we look into the actual file entry for the main
333 // file to determine the real absolute path for the file.
334 std::string MainFileDir;
335 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
336 MainFileDir = MainFile->getDir()->getName();
Yaron Keren921ac4d2013-10-21 20:07:37 +0000337 if (MainFileDir != ".") {
Stephen Hines651f13c2014-04-23 16:59:28 -0700338 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
339 llvm::sys::path::append(MainFileDirSS, MainFileName);
340 MainFileName = MainFileDirSS.str();
Yaron Keren921ac4d2013-10-21 20:07:37 +0000341 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000342 }
343
344 // Save filename string.
Benjamin Kramer84953792013-09-09 16:39:06 +0000345 StringRef Filename = internString(MainFileName);
Eric Christopherff971d72013-02-22 23:50:16 +0000346
347 // Save split dwarf file string.
348 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer84953792013-09-09 16:39:06 +0000349 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopher6537f082013-05-16 00:45:12 +0000350
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700351 llvm::dwarf::SourceLanguage LangTag;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000352 const LangOptions &LO = CGM.getLangOpts();
353 if (LO.CPlusPlus) {
354 if (LO.ObjC1)
355 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
356 else
357 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
358 } else if (LO.ObjC1) {
359 LangTag = llvm::dwarf::DW_LANG_ObjC;
360 } else if (LO.C99) {
361 LangTag = llvm::dwarf::DW_LANG_C99;
362 } else {
363 LangTag = llvm::dwarf::DW_LANG_C89;
364 }
365
366 std::string Producer = getClangFullVersion();
367
368 // Figure out which version of the ObjC runtime we have.
369 unsigned RuntimeVers = 0;
370 if (LO.ObjC1)
371 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
372
373 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000374 // FIXME - Eliminate TheCU.
Stephen Hines651f13c2014-04-23 16:59:28 -0700375 TheCU = DBuilder.createCompileUnit(
376 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
377 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700378 DebugKind <= CodeGenOptions::DebugLineTablesOnly
Stephen Hines651f13c2014-04-23 16:59:28 -0700379 ? llvm::DIBuilder::LineTablesOnly
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700380 : llvm::DIBuilder::FullDebug,
381 DebugKind != CodeGenOptions::LocTrackingOnly);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000382}
383
384/// CreateType - Get the Basic type from the cache or create a new
385/// one if necessary.
386llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700387 llvm::dwarf::TypeKind Encoding;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000388 StringRef BTName;
389 switch (BT->getKind()) {
390#define BUILTIN_TYPE(Id, SingletonId)
391#define PLACEHOLDER_TYPE(Id, SingletonId) \
392 case BuiltinType::Id:
393#include "clang/AST/BuiltinTypes.def"
394 case BuiltinType::Dependent:
395 llvm_unreachable("Unexpected builtin type");
396 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000397 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000398 case BuiltinType::Void:
399 return llvm::DIType();
400 case BuiltinType::ObjCClass:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700401 if (!ClassTy)
402 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
403 "objc_class", TheCU,
404 getOrCreateMainFile(), 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000405 return ClassTy;
406 case BuiltinType::ObjCId: {
407 // typedef struct objc_class *Class;
408 // typedef struct objc_object {
409 // Class isa;
410 // } *id;
411
Eric Christopherb2d13922013-07-18 00:52:50 +0000412 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000413 return ObjTy;
414
Eric Christopherb2d13922013-07-18 00:52:50 +0000415 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000416 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
417 "objc_class", TheCU,
418 getOrCreateMainFile(), 0);
419
420 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000421
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000422 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
423
Eric Christopherf068c922013-04-02 22:59:11 +0000424 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000425 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
426 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000427
Eric Christopherf068c922013-04-02 22:59:11 +0000428 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
429 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000430 return ObjTy;
431 }
432 case BuiltinType::ObjCSel: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700433 if (!SelTy)
434 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
435 "objc_selector", TheCU,
436 getOrCreateMainFile(), 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000437 return SelTy;
438 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000439
440 case BuiltinType::OCLImage1d:
441 return getOrCreateStructPtrType("opencl_image1d_t",
442 OCLImage1dDITy);
443 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000444 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000445 OCLImage1dArrayDITy);
446 case BuiltinType::OCLImage1dBuffer:
447 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
448 OCLImage1dBufferDITy);
449 case BuiltinType::OCLImage2d:
450 return getOrCreateStructPtrType("opencl_image2d_t",
451 OCLImage2dDITy);
452 case BuiltinType::OCLImage2dArray:
453 return getOrCreateStructPtrType("opencl_image2d_array_t",
454 OCLImage2dArrayDITy);
455 case BuiltinType::OCLImage3d:
456 return getOrCreateStructPtrType("opencl_image3d_t",
457 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000458 case BuiltinType::OCLSampler:
459 return DBuilder.createBasicType("opencl_sampler_t",
460 CGM.getContext().getTypeSize(BT),
461 CGM.getContext().getTypeAlign(BT),
462 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000463 case BuiltinType::OCLEvent:
464 return getOrCreateStructPtrType("opencl_event_t",
465 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000466
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000467 case BuiltinType::UChar:
468 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
469 case BuiltinType::Char_S:
470 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
471 case BuiltinType::Char16:
472 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
473 case BuiltinType::UShort:
474 case BuiltinType::UInt:
475 case BuiltinType::UInt128:
476 case BuiltinType::ULong:
477 case BuiltinType::WChar_U:
478 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
479 case BuiltinType::Short:
480 case BuiltinType::Int:
481 case BuiltinType::Int128:
482 case BuiltinType::Long:
483 case BuiltinType::WChar_S:
484 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
485 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
486 case BuiltinType::Half:
487 case BuiltinType::Float:
488 case BuiltinType::LongDouble:
489 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
490 }
491
492 switch (BT->getKind()) {
493 case BuiltinType::Long: BTName = "long int"; break;
494 case BuiltinType::LongLong: BTName = "long long int"; break;
495 case BuiltinType::ULong: BTName = "long unsigned int"; break;
496 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
497 default:
498 BTName = BT->getName(CGM.getLangOpts());
499 break;
500 }
501 // Bit size, align and offset of the type.
502 uint64_t Size = CGM.getContext().getTypeSize(BT);
503 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000504 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000505 DBuilder.createBasicType(BTName, Size, Align, Encoding);
506 return DbgTy;
507}
508
509llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
510 // Bit size, align and offset of the type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700511 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000512 if (Ty->isComplexIntegerType())
513 Encoding = llvm::dwarf::DW_ATE_lo_user;
514
515 uint64_t Size = CGM.getContext().getTypeSize(Ty);
516 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000517 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000518 DBuilder.createBasicType("complex", Size, Align, Encoding);
519
520 return DbgTy;
521}
522
523/// CreateCVRType - Get the qualified type from the cache or create
524/// a new one if necessary.
David Blaikie29b8b682013-09-04 22:03:57 +0000525llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000526 QualifierCollector Qc;
527 const Type *T = Qc.strip(Ty);
528
529 // Ignore these qualifiers for now.
530 Qc.removeObjCGCAttr();
531 Qc.removeAddressSpace();
532 Qc.removeObjCLifetime();
533
534 // We will create one Derived type for one qualifier and recurse to handle any
535 // additional ones.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700536 llvm::dwarf::Tag Tag;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000537 if (Qc.hasConst()) {
538 Tag = llvm::dwarf::DW_TAG_const_type;
539 Qc.removeConst();
540 } else if (Qc.hasVolatile()) {
541 Tag = llvm::dwarf::DW_TAG_volatile_type;
542 Qc.removeVolatile();
543 } else if (Qc.hasRestrict()) {
544 Tag = llvm::dwarf::DW_TAG_restrict_type;
545 Qc.removeRestrict();
546 } else {
547 assert(Qc.empty() && "Unknown type qualifier for debug info");
548 return getOrCreateType(QualType(T, 0), Unit);
549 }
550
David Blaikie29b8b682013-09-04 22:03:57 +0000551 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000552
553 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
554 // CVR derived types.
555 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000556
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000557 return DbgTy;
558}
559
560llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
561 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000562
563 // The frontend treats 'id' as a typedef to an ObjCObjectType,
564 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
565 // debug info, we want to emit 'id' in both cases.
566 if (Ty->isObjCQualifiedIdType())
567 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
568
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000569 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000570 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000571 Ty->getPointeeType(), Unit);
572 return DbgTy;
573}
574
575llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
576 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000577 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000578 Ty->getPointeeType(), Unit);
579}
580
Manman Ren83369bf2013-08-29 23:19:58 +0000581/// In C++ mode, types have linkage, so we can rely on the ODR and
582/// on their mangled names, if they're external.
583static SmallString<256>
584getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
585 llvm::DICompileUnit TheCU) {
586 SmallString<256> FullName;
587 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
588 // For now, only apply ODR with C++.
589 const TagDecl *TD = Ty->getDecl();
590 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
591 !TD->isExternallyVisible())
592 return FullName;
593 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
594 if (CGM.getTarget().getCXXABI().isMicrosoft())
595 return FullName;
596
597 // TODO: This is using the RTTI name. Is there a better way to get
598 // a unique string for a type?
599 llvm::raw_svector_ostream Out(FullName);
600 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
601 Out.flush();
602 return FullName;
603}
604
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000605// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000606llvm::DICompositeType
Manman Renf3327332013-08-28 21:20:28 +0000607CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikieeaacc882013-08-20 21:03:29 +0000608 llvm::DIDescriptor Ctx) {
Manman Renf3327332013-08-28 21:20:28 +0000609 const RecordDecl *RD = Ty->getDecl();
David Blaikiec5cd1a72013-08-15 20:17:25 +0000610 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000611 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000612 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
613 unsigned Line = getLineNumber(RD->getLocation());
614 StringRef RDName = getClassName(RD);
615
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700616 llvm::dwarf::Tag Tag;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000617 if (RD->isStruct() || RD->isInterface())
618 Tag = llvm::dwarf::DW_TAG_structure_type;
619 else if (RD->isUnion())
620 Tag = llvm::dwarf::DW_TAG_union_type;
621 else {
622 assert(RD->isClass());
623 Tag = llvm::dwarf::DW_TAG_class_type;
624 }
625
626 // Create the type.
Manman Ren83369bf2013-08-29 23:19:58 +0000627 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700628 llvm::DICompositeType RetTy = DBuilder.createReplaceableForwardDecl(
629 Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0, FullName);
630 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
631 return RetTy;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000632}
633
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700634llvm::DIType CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000635 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000636 QualType PointeeTy,
637 llvm::DIFile Unit) {
638 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
639 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie29b8b682013-09-04 22:03:57 +0000640 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000641
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000642 // Bit size, align and offset of the type.
643 // Size is always the size of a pointer. We can't use getTypeSize here
644 // because that does not return the correct value for references.
645 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000646 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000647 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
648
David Blaikie29b8b682013-09-04 22:03:57 +0000649 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
650 Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000651}
652
Eric Christopherf0890c42013-05-16 00:52:20 +0000653llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
654 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000655 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000656 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000657 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
658 TheCU, getOrCreateMainFile(), 0);
659 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
660 Cache = DBuilder.createPointerType(Cache, Size);
661 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000662}
663
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000664llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
665 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000666 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000667 return BlockLiteralGeneric;
668
669 SmallVector<llvm::Value *, 8> EltTys;
670 llvm::DIType FieldTy;
671 QualType FType;
672 uint64_t FieldSize, FieldOffset;
673 unsigned FieldAlign;
674 llvm::DIArray Elements;
675 llvm::DIType EltTy, DescTy;
676
677 FieldOffset = 0;
678 FType = CGM.getContext().UnsignedLongTy;
679 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
680 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
681
682 Elements = DBuilder.getOrCreateArray(EltTys);
683 EltTys.clear();
684
685 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
686 unsigned LineNo = getLineNumber(CurLoc);
687
688 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
689 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000690 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000691
692 // Bit size, align and offset of the type.
693 uint64_t Size = CGM.getContext().getTypeSize(Ty);
694
695 DescTy = DBuilder.createPointerType(EltTy, Size);
696
697 FieldOffset = 0;
698 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
699 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
700 FType = CGM.getContext().IntTy;
701 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
702 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
705
706 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
707 FieldTy = DescTy;
708 FieldSize = CGM.getContext().getTypeSize(Ty);
709 FieldAlign = CGM.getContext().getTypeAlign(Ty);
710 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
711 LineNo, FieldSize, FieldAlign,
712 FieldOffset, 0, FieldTy);
713 EltTys.push_back(FieldTy);
714
715 FieldOffset += FieldSize;
716 Elements = DBuilder.getOrCreateArray(EltTys);
717
718 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
719 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000720 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000721
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000722 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
723 return BlockLiteralGeneric;
724}
725
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700726llvm::DIType CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, llvm::DIFile Unit) {
727 assert(Ty->isTypeAlias());
728 llvm::DIType Src = getOrCreateType(Ty->getAliasedType(), Unit);
729
730 SmallString<128> NS;
731 llvm::raw_svector_ostream OS(NS);
732 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), /*qualified*/ false);
733
734 TemplateSpecializationType::PrintTemplateArgumentList(
735 OS, Ty->getArgs(), Ty->getNumArgs(),
736 CGM.getContext().getPrintingPolicy());
737
738 TypeAliasDecl *AliasDecl =
739 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
740 ->getTemplatedDecl();
741
742 SourceLocation Loc = AliasDecl->getLocation();
743 llvm::DIFile File = getOrCreateFile(Loc);
744 unsigned Line = getLineNumber(Loc);
745
746 llvm::DIDescriptor Ctxt = getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext()));
747
748 return DBuilder.createTypedef(Src, internString(OS.str()), File, Line, Ctxt);
749}
750
David Blaikie29b8b682013-09-04 22:03:57 +0000751llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000752 // Typedefs are derived from some other type. If we have a typedef of a
753 // typedef, make sure to emit the whole chain.
David Blaikie29b8b682013-09-04 22:03:57 +0000754 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000755 // We don't set size information, but do specify where the typedef was
756 // declared.
Stephen Hines651f13c2014-04-23 16:59:28 -0700757 SourceLocation Loc = Ty->getDecl()->getLocation();
758 llvm::DIFile File = getOrCreateFile(Loc);
759 unsigned Line = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000760 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000761
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000762 llvm::DIDescriptor TypedefContext =
763 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000764
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000765 return
Stephen Hines651f13c2014-04-23 16:59:28 -0700766 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000767}
768
769llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
770 llvm::DIFile Unit) {
771 SmallVector<llvm::Value *, 16> EltTys;
772
773 // Add the result type at least.
Stephen Hines651f13c2014-04-23 16:59:28 -0700774 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000775
776 // Set up remainder of arguments if there is a prototype.
Stephen Hines651f13c2014-04-23 16:59:28 -0700777 // otherwise emit it as a variadic function.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000778 if (isa<FunctionNoProtoType>(Ty))
779 EltTys.push_back(DBuilder.createUnspecifiedParameter());
780 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700781 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
782 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
783 if (FPT->isVariadic())
784 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000785 }
786
787 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
788 return DBuilder.createSubroutineType(Unit, EltTypeArray);
789}
790
791
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000792llvm::DIType CGDebugInfo::createFieldType(StringRef name,
793 QualType type,
794 uint64_t sizeInBitsOverride,
795 SourceLocation loc,
796 AccessSpecifier AS,
797 uint64_t offsetInBits,
798 llvm::DIFile tunit,
Manman Renc23b1db2013-09-08 03:45:05 +0000799 llvm::DIScope scope) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000800 llvm::DIType debugType = getOrCreateType(type, tunit);
801
802 // Get the location for the field.
803 llvm::DIFile file = getOrCreateFile(loc);
804 unsigned line = getLineNumber(loc);
805
806 uint64_t sizeInBits = 0;
807 unsigned alignInBits = 0;
808 if (!type->isIncompleteArrayType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700809 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000810
811 if (sizeInBitsOverride)
812 sizeInBits = sizeInBitsOverride;
813 }
814
815 unsigned flags = 0;
816 if (AS == clang::AS_private)
817 flags |= llvm::DIDescriptor::FlagPrivate;
818 else if (AS == clang::AS_protected)
819 flags |= llvm::DIDescriptor::FlagProtected;
820
821 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
822 alignInBits, offsetInBits, flags, debugType);
823}
824
Eric Christopher0395de32013-01-16 01:22:32 +0000825/// CollectRecordLambdaFields - Helper for CollectRecordFields.
826void CGDebugInfo::
827CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
828 SmallVectorImpl<llvm::Value *> &elements,
829 llvm::DIType RecordTy) {
830 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
831 // has the name and the location of the variable so we should iterate over
832 // both concurrently.
833 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
834 RecordDecl::field_iterator Field = CXXDecl->field_begin();
835 unsigned fieldno = 0;
836 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
837 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700838 const LambdaCapture &C = *I;
Eric Christopher0395de32013-01-16 01:22:32 +0000839 if (C.capturesVariable()) {
840 VarDecl *V = C.getCapturedVar();
841 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
842 StringRef VName = V->getName();
843 uint64_t SizeInBitsOverride = 0;
844 if (Field->isBitField()) {
845 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
846 assert(SizeInBitsOverride && "found named 0-width bitfield");
847 }
848 llvm::DIType fieldType
849 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
850 C.getLocation(), Field->getAccess(),
851 layout.getFieldOffset(fieldno), VUnit, RecordTy);
852 elements.push_back(fieldType);
853 } else {
854 // TODO: Need to handle 'this' in some way by probably renaming the
855 // this of the lambda class and having a field member of 'this' or
856 // by using AT_object_pointer for the function and having that be
857 // used as 'this' for semantic references.
858 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
859 FieldDecl *f = *Field;
860 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
861 QualType type = f->getType();
862 llvm::DIType fieldType
863 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
864 layout.getFieldOffset(fieldno), VUnit, RecordTy);
865
866 elements.push_back(fieldType);
867 }
868 }
869}
870
David Blaikie5434fc22013-08-20 01:28:15 +0000871/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000872llvm::DIDerivedType
873CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
874 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000875 // Create the descriptor for the static variable, with or without
876 // constant initializers.
877 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
878 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
879
Eric Christopher0395de32013-01-16 01:22:32 +0000880 unsigned LineNumber = getLineNumber(Var->getLocation());
881 StringRef VName = Var->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700882 llvm::Constant *C = nullptr;
Eric Christopher0395de32013-01-16 01:22:32 +0000883 if (Var->getInit()) {
884 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000885 if (Value) {
886 if (Value->isInt())
887 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
888 if (Value->isFloat())
889 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
890 }
Eric Christopher0395de32013-01-16 01:22:32 +0000891 }
892
893 unsigned Flags = 0;
894 AccessSpecifier Access = Var->getAccess();
895 if (Access == clang::AS_private)
896 Flags |= llvm::DIDescriptor::FlagPrivate;
897 else if (Access == clang::AS_protected)
898 Flags |= llvm::DIDescriptor::FlagProtected;
899
David Blaikiecbcb0302013-08-15 22:50:29 +0000900 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
901 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000902 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000903 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000904}
905
906/// CollectRecordNormalField - Helper for CollectRecordFields.
907void CGDebugInfo::
908CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
909 llvm::DIFile tunit,
910 SmallVectorImpl<llvm::Value *> &elements,
911 llvm::DIType RecordTy) {
912 StringRef name = field->getName();
913 QualType type = field->getType();
914
915 // Ignore unnamed fields unless they're anonymous structs/unions.
916 if (name.empty() && !type->isRecordType())
917 return;
918
919 uint64_t SizeInBitsOverride = 0;
920 if (field->isBitField()) {
921 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
922 assert(SizeInBitsOverride && "found named 0-width bitfield");
923 }
924
925 llvm::DIType fieldType
926 = createFieldType(name, type, SizeInBitsOverride,
927 field->getLocation(), field->getAccess(),
928 OffsetInBits, tunit, RecordTy);
929
930 elements.push_back(fieldType);
931}
932
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000933/// CollectRecordFields - A helper function to collect debug info for
934/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000935void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
936 llvm::DIFile tunit,
937 SmallVectorImpl<llvm::Value *> &elements,
938 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000939 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
940
Eric Christopher0395de32013-01-16 01:22:32 +0000941 if (CXXDecl && CXXDecl->isLambda())
942 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
943 else {
944 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000945
Eric Christopher0395de32013-01-16 01:22:32 +0000946 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000947 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000948
Eric Christopher0395de32013-01-16 01:22:32 +0000949 // Static and non-static members should appear in the same order as
950 // the corresponding declarations in the source program.
Stephen Hines651f13c2014-04-23 16:59:28 -0700951 for (const auto *I : record->decls())
952 if (const auto *V = dyn_cast<VarDecl>(I)) {
David Blaikie5e6937b2013-08-20 21:49:21 +0000953 // Reuse the existing static member declaration if one exists
954 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
955 StaticDataMemberCache.find(V->getCanonicalDecl());
956 if (MI != StaticDataMemberCache.end()) {
957 assert(MI->second &&
958 "Static data member declaration should still exist");
959 elements.push_back(
960 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
961 } else
962 elements.push_back(CreateRecordStaticField(V, RecordTy));
Stephen Hines651f13c2014-04-23 16:59:28 -0700963 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000964 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
965 tunit, elements, RecordTy);
966
967 // Bump field number for next field.
968 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000969 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000970 }
971}
972
973/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
974/// function type is not updated to include implicit "this" pointer. Use this
975/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000976llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000977CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
978 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000980 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000981 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000982 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
983 Func, Unit);
984}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000985
David Blaikie9a845292013-05-22 23:22:42 +0000986llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000987 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000988 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000989 llvm::DIArray Args = llvm::DICompositeType(
990 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000991 assert (Args.getNumElements() && "Invalid number of arguments!");
992
993 SmallVector<llvm::Value *, 16> Elts;
994
995 // First element is always return type. For 'void' functions it is NULL.
996 Elts.push_back(Args.getElement(0));
997
David Blaikie67f8b5e2013-01-07 22:24:59 +0000998 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000999 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +00001000 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1001 // Create pointer type directly in this case.
1002 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1003 QualType PointeeTy = ThisPtrTy->getPointeeType();
1004 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001005 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001006 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1007 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001008 llvm::DIType ThisPtrType =
1009 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001010 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1011 // TODO: This and the artificial type below are misleading, the
1012 // types aren't artificial the argument is, but the current
1013 // metadata doesn't represent that.
1014 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1015 Elts.push_back(ThisPtrType);
1016 } else {
1017 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1018 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1019 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1020 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001021 }
1022
1023 // Copy rest of the arguments.
1024 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1025 Elts.push_back(Args.getElement(i));
1026
1027 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1028
Stephen Hines651f13c2014-04-23 16:59:28 -07001029 unsigned Flags = 0;
1030 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1031 Flags |= llvm::DIDescriptor::FlagLValueReference;
1032 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1033 Flags |= llvm::DIDescriptor::FlagRValueReference;
1034
1035 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001036}
1037
Eric Christopher6537f082013-05-16 00:45:12 +00001038/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001039/// inside a function.
1040static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1041 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1042 return isFunctionLocalClass(NRD);
1043 if (isa<FunctionDecl>(RD->getDeclContext()))
1044 return true;
1045 return false;
1046}
1047
1048/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1049/// a single member function GlobalDecl.
1050llvm::DISubprogram
1051CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1052 llvm::DIFile Unit,
1053 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001054 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001055 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001056
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001057 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001058 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001059
1060 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1061 // make sense to give a single ctor/dtor a linkage name.
1062 StringRef MethodLinkageName;
1063 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1064 MethodLinkageName = CGM.getMangledName(Method);
1065
1066 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001067 llvm::DIFile MethodDefUnit;
1068 unsigned MethodLine = 0;
1069 if (!Method->isImplicit()) {
1070 MethodDefUnit = getOrCreateFile(Method->getLocation());
1071 MethodLine = getLineNumber(Method->getLocation());
1072 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001073
1074 // Collect virtual method info.
1075 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001076 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001077 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001078
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001079 if (Method->isVirtual()) {
1080 if (Method->isPure())
1081 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1082 else
1083 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001084
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001085 // It doesn't make sense to give a virtual destructor a vtable index,
1086 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001087 // FIXME: Add proper support for debug info for virtual calls in
1088 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1089 // lookup if we have multiple or virtual inheritance.
1090 if (!isa<CXXDestructorDecl>(Method) &&
1091 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +00001092 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001093 ContainingType = RecordTy;
1094 }
1095
1096 unsigned Flags = 0;
1097 if (Method->isImplicit())
1098 Flags |= llvm::DIDescriptor::FlagArtificial;
1099 AccessSpecifier Access = Method->getAccess();
1100 if (Access == clang::AS_private)
1101 Flags |= llvm::DIDescriptor::FlagPrivate;
1102 else if (Access == clang::AS_protected)
1103 Flags |= llvm::DIDescriptor::FlagProtected;
1104 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1105 if (CXXC->isExplicit())
1106 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001107 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001108 dyn_cast<CXXConversionDecl>(Method)) {
1109 if (CXXC->isExplicit())
1110 Flags |= llvm::DIDescriptor::FlagExplicit;
1111 }
1112 if (Method->hasPrototype())
1113 Flags |= llvm::DIDescriptor::FlagPrototyped;
Stephen Hines651f13c2014-04-23 16:59:28 -07001114 if (Method->getRefQualifier() == RQ_LValue)
1115 Flags |= llvm::DIDescriptor::FlagLValueReference;
1116 if (Method->getRefQualifier() == RQ_RValue)
1117 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001118
1119 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1120 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001121 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001122 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001123 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001124 /* isDefinition=*/ false,
1125 Virtuality, VIndex, ContainingType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001126 Flags, CGM.getLangOpts().Optimize, nullptr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001127 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001128
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001129 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1130
1131 return SP;
1132}
1133
1134/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001135/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001136/// a Record.
1137void CGDebugInfo::
1138CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1139 SmallVectorImpl<llvm::Value *> &EltTys,
1140 llvm::DIType RecordTy) {
1141
1142 // Since we want more than just the individual member decls if we
1143 // have templated functions iterate over every declaration to gather
1144 // the functions.
Stephen Hines651f13c2014-04-23 16:59:28 -07001145 for(const auto *I : RD->decls()) {
1146 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001147 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001148 // It may be associated with the declaration of the type & should be
1149 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001150 //
1151 // This situation can arise in the vtable-based debug info reduction where
1152 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001153 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1154 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001155 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001156 // If the member is implicit, lazily create it when we see the
1157 // definition, not before. (an ODR-used implicit default ctor that's
1158 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001159 if (!Method->isImplicit())
1160 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1161 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001162 EltTys.push_back(MI->second);
Stephen Hines651f13c2014-04-23 16:59:28 -07001163 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
David Blaikie11fa7512013-08-28 23:06:52 +00001164 // Add any template specializations that have already been seen. Like
1165 // implicit member functions, these may have been added to a declaration
1166 // in the case of vtable-based debug info reduction.
Stephen Hines651f13c2014-04-23 16:59:28 -07001167 for (const auto *SI : FTD->specializations()) {
David Blaikie11fa7512013-08-28 23:06:52 +00001168 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
Stephen Hines651f13c2014-04-23 16:59:28 -07001169 SPCache.find(cast<CXXMethodDecl>(SI)->getCanonicalDecl());
David Blaikie11fa7512013-08-28 23:06:52 +00001170 if (MI != SPCache.end())
1171 EltTys.push_back(MI->second);
1172 }
David Blaikie5434fc22013-08-20 01:28:15 +00001173 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001174 }
Eric Christopher6537f082013-05-16 00:45:12 +00001175}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001176
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001177/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001178/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001179/// a Record.
1180void CGDebugInfo::
1181CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1182 SmallVectorImpl<llvm::Value *> &EltTys,
1183 llvm::DIType RecordTy) {
1184
1185 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001186 for (const auto &BI : RD->bases()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 unsigned BFlags = 0;
1188 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001189
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001190 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07001191 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001192
Stephen Hines651f13c2014-04-23 16:59:28 -07001193 if (BI.isVirtual()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001194 // virtual base offset offset is -ve. The code generator emits dwarf
1195 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001196 BaseOffset =
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +00001197 0 - CGM.getItaniumVTableContext()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001198 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1199 BFlags = llvm::DIDescriptor::FlagVirtual;
1200 } else
1201 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1202 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1203 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001204
Stephen Hines651f13c2014-04-23 16:59:28 -07001205 AccessSpecifier Access = BI.getAccessSpecifier();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001206 if (Access == clang::AS_private)
1207 BFlags |= llvm::DIDescriptor::FlagPrivate;
1208 else if (Access == clang::AS_protected)
1209 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001210
1211 llvm::DIType DTy =
1212 DBuilder.createInheritance(RecordTy,
Stephen Hines651f13c2014-04-23 16:59:28 -07001213 getOrCreateType(BI.getType(), Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001214 BaseOffset, BFlags);
1215 EltTys.push_back(DTy);
1216 }
1217}
1218
1219/// CollectTemplateParams - A helper function to collect template parameters.
1220llvm::DIArray CGDebugInfo::
1221CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001222 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001223 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001224 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001225 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1226 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001227 StringRef Name;
1228 if (TPList)
1229 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001230 switch (TA.getKind()) {
1231 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001232 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1233 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001234 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001235 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001236 } break;
1237 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001238 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1239 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001240 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001241 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001242 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1243 TemplateParams.push_back(TVP);
1244 } break;
1245 case TemplateArgument::Declaration: {
1246 const ValueDecl *D = TA.getAsDecl();
1247 bool InstanceMember = D->isCXXInstanceMember();
1248 QualType T = InstanceMember
1249 ? CGM.getContext().getMemberPointerType(
1250 D->getType(), cast<RecordDecl>(D->getDeclContext())
1251 ->getTypeForDecl())
1252 : CGM.getContext().getPointerType(D->getType());
1253 llvm::DIType TTy = getOrCreateType(T, Unit);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001254 llvm::Value *V = nullptr;
David Blaikie9dfd2432013-05-10 21:53:14 +00001255 // Variable pointer template parameters have a value that is the address
1256 // of the variable.
1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1258 V = CGM.GetAddrOfGlobalVar(VD);
1259 // Member function pointers have special support for building them, though
1260 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001261 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001262 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1263 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001264 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1265 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001266 // Member data pointers have special handling too to compute the fixed
1267 // offset within the object.
Stephen Hines651f13c2014-04-23 16:59:28 -07001268 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001269 // These five lines (& possibly the above member function pointer
1270 // handling) might be able to be refactored to use similar code in
1271 // CodeGenModule::getMemberPointerConstant
1272 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1273 CharUnits chars =
1274 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1275 V = CGM.getCXXABI().EmitMemberDataPointer(
1276 cast<MemberPointerType>(T.getTypePtr()), chars);
1277 }
1278 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001279 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1280 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001281 TemplateParams.push_back(TVP);
1282 } break;
1283 case TemplateArgument::NullPtr: {
1284 QualType T = TA.getNullPtrType();
1285 llvm::DIType TTy = getOrCreateType(T, Unit);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001286 llvm::Value *V = nullptr;
David Blaikie9dfd2432013-05-10 21:53:14 +00001287 // Special case member data pointer null values since they're actually -1
1288 // instead of zero.
1289 if (const MemberPointerType *MPT =
1290 dyn_cast<MemberPointerType>(T.getTypePtr()))
1291 // But treat member function pointers as simple zero integers because
1292 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1293 // CodeGen grows handling for values of non-null member function
1294 // pointers then perhaps we could remove this special case and rely on
1295 // EmitNullMemberPointer for member function pointers.
1296 if (MPT->isMemberDataPointer())
1297 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1298 if (!V)
1299 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1300 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001301 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001302 TemplateParams.push_back(TVP);
1303 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001304 case TemplateArgument::Template: {
1305 llvm::DITemplateValueParameter TVP =
1306 DBuilder.createTemplateTemplateParameter(
1307 TheCU, Name, llvm::DIType(),
1308 TA.getAsTemplate().getAsTemplateDecl()
1309 ->getQualifiedNameAsString());
1310 TemplateParams.push_back(TVP);
1311 } break;
1312 case TemplateArgument::Pack: {
1313 llvm::DITemplateValueParameter TVP =
1314 DBuilder.createTemplateParameterPack(
1315 TheCU, Name, llvm::DIType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001316 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit));
David Blaikie35178dc2013-06-22 18:59:18 +00001317 TemplateParams.push_back(TVP);
1318 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001319 case TemplateArgument::Expression: {
1320 const Expr *E = TA.getAsExpr();
1321 QualType T = E->getType();
1322 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1323 assert(V && "Expression in template argument isn't constant");
1324 llvm::DIType TTy = getOrCreateType(T, Unit);
1325 llvm::DITemplateValueParameter TVP =
1326 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1327 V->stripPointerCasts());
1328 TemplateParams.push_back(TVP);
1329 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001330 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001331 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001332 case TemplateArgument::Null:
1333 llvm_unreachable(
1334 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001335 }
1336 }
1337 return DBuilder.getOrCreateArray(TemplateParams);
1338}
1339
1340/// CollectFunctionTemplateParams - A helper function to collect debug
1341/// info for function template parameters.
1342llvm::DIArray CGDebugInfo::
1343CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1344 if (FD->getTemplatedKind() ==
1345 FunctionDecl::TK_FunctionTemplateSpecialization) {
1346 const TemplateParameterList *TList =
1347 FD->getTemplateSpecializationInfo()->getTemplate()
1348 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001349 return CollectTemplateParams(
1350 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001351 }
1352 return llvm::DIArray();
1353}
1354
1355/// CollectCXXTemplateParams - A helper function to collect debug info for
1356/// template parameters.
1357llvm::DIArray CGDebugInfo::
1358CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1359 llvm::DIFile Unit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001360 // Always get the full list of parameters, not just the ones from
1361 // the specialization.
1362 TemplateParameterList *TPList =
1363 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1364 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001365 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001366}
1367
1368/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1369llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1370 if (VTablePtrType.isValid())
1371 return VTablePtrType;
1372
1373 ASTContext &Context = CGM.getContext();
1374
1375 /* Function type */
1376 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1377 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1378 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1379 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1380 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1381 "__vtbl_ptr_type");
1382 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1383 return VTablePtrType;
1384}
1385
1386/// getVTableName - Get vtable name for the given Class.
1387StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer84953792013-09-09 16:39:06 +00001388 // Copy the gdb compatible name on the side and use its reference.
1389 return internString("_vptr$", RD->getNameAsString());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001390}
1391
1392
1393/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1394/// debug info entry in EltTys vector.
1395void CGDebugInfo::
1396CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1397 SmallVectorImpl<llvm::Value *> &EltTys) {
1398 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1399
1400 // If there is a primary base then it will hold vtable info.
1401 if (RL.getPrimaryBase())
1402 return;
1403
1404 // If this class is not dynamic then there is not any vtable info to collect.
1405 if (!RD->isDynamicClass())
1406 return;
1407
1408 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1409 llvm::DIType VPTR
1410 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001411 0, Size, 0, 0,
1412 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001413 getOrCreateVTablePtrType(Unit));
1414 EltTys.push_back(VPTR);
1415}
1416
Eric Christopher6537f082013-05-16 00:45:12 +00001417/// getOrCreateRecordType - Emit record type's standalone debug info.
1418llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001419 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001420 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001421 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1422 return T;
1423}
1424
1425/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1426/// debug info.
1427llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001428 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001429 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001430 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001431 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001432 return T;
1433}
1434
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001435void CGDebugInfo::completeType(const EnumDecl *ED) {
1436 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1437 return;
1438 QualType Ty = CGM.getContext().getEnumType(ED);
1439 void* TyPtr = Ty.getAsOpaquePtr();
1440 auto I = TypeCache.find(TyPtr);
1441 if (I == TypeCache.end() ||
1442 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
1443 .isForwardDecl())
1444 return;
1445 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1446 assert(!Res.isForwardDecl());
1447 TypeCache[TyPtr] = Res;
1448}
1449
David Blaikie27804892013-08-15 20:49:17 +00001450void CGDebugInfo::completeType(const RecordDecl *RD) {
1451 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1452 !CGM.getLangOpts().CPlusPlus)
1453 completeRequiredType(RD);
1454}
1455
1456void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001457 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1458 return;
1459
David Blaikie5434fc22013-08-20 01:28:15 +00001460 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1461 if (CXXDecl->isDynamicClass())
1462 return;
1463
David Blaikie27804892013-08-15 20:49:17 +00001464 QualType Ty = CGM.getContext().getRecordType(RD);
1465 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001466 if (T && T.isForwardDecl())
1467 completeClassData(RD);
1468}
1469
1470void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1471 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001472 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001473 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001474 void* TyPtr = Ty.getAsOpaquePtr();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001475 auto I = TypeCache.find(TyPtr);
1476 if (I != TypeCache.end() &&
1477 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
1478 .isForwardDecl())
David Blaikie27804892013-08-15 20:49:17 +00001479 return;
1480 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1481 assert(!Res.isForwardDecl());
David Blaikie27804892013-08-15 20:49:17 +00001482 TypeCache[TyPtr] = Res;
1483}
1484
Stephen Hines651f13c2014-04-23 16:59:28 -07001485static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1486 CXXRecordDecl::method_iterator End) {
1487 for (; I != End; ++I)
1488 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1489 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1490 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1491 return true;
1492 return false;
1493}
1494
1495static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1496 const RecordDecl *RD,
1497 const LangOptions &LangOpts) {
1498 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1499 return false;
1500
1501 if (!LangOpts.CPlusPlus)
1502 return false;
1503
1504 if (!RD->isCompleteDefinitionRequired())
1505 return true;
1506
1507 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1508
1509 if (!CXXDecl)
1510 return false;
1511
1512 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1513 return true;
1514
1515 TemplateSpecializationKind Spec = TSK_Undeclared;
1516 if (const ClassTemplateSpecializationDecl *SD =
1517 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1518 Spec = SD->getSpecializationKind();
1519
1520 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1521 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1522 CXXDecl->method_end()))
1523 return true;
1524
1525 return false;
1526}
1527
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528/// CreateType - get structure or union type.
David Blaikie29b8b682013-09-04 22:03:57 +00001529llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001530 RecordDecl *RD = Ty->getDecl();
David Blaikie74341d82013-09-06 06:45:04 +00001531 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
Stephen Hines651f13c2014-04-23 16:59:28 -07001532 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie74341d82013-09-06 06:45:04 +00001533 if (!T)
Stephen Hines651f13c2014-04-23 16:59:28 -07001534 T = getOrCreateRecordFwdDecl(
1535 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie74341d82013-09-06 06:45:04 +00001536 return T;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001537 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001538
David Blaikie27804892013-08-15 20:49:17 +00001539 return CreateTypeDefinition(Ty);
1540}
1541
1542llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1543 RecordDecl *RD = Ty->getDecl();
1544
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001545 // Get overall information about the record type for the debug info.
1546 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1547
1548 // Records and classes and unions can all be recursive. To handle them, we
1549 // first generate a debug descriptor for the struct as a forward declaration.
1550 // Then (if it is a definition) we go through and get debug info for all of
1551 // its members. Finally, we create a descriptor for the complete type (which
1552 // may refer to the forward decl if the struct is recursive) and replace all
1553 // uses of the forward declaration with the final definition.
1554
David Blaikie4a077162013-08-12 22:24:20 +00001555 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001556 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001557 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001558
1559 if (FwdDecl.isForwardDecl())
1560 return FwdDecl;
1561
David Blaikie498298d2013-08-18 16:55:33 +00001562 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1563 CollectContainingType(CXXDecl, FwdDecl);
1564
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001565 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001566 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001567 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1568
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001569 // Convert all the elements.
1570 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001571 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001572
1573 // Note: The split of CXXDecl information here is intentional, the
1574 // gdb tests will depend on a certain ordering at printout. The debug
1575 // information offsets are still correct if we merge them all together
1576 // though.
1577 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1578 if (CXXDecl) {
1579 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1580 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1581 }
1582
Eric Christopher0395de32013-01-16 01:22:32 +00001583 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001584 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopherd6b52972013-10-11 18:16:51 +00001585 if (CXXDecl)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001586 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001587
1588 LexicalBlockStack.pop_back();
1589 RegionMap.erase(Ty->getDecl());
1590
1591 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001592 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001593
Eric Christopherf068c922013-04-02 22:59:11 +00001594 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1595 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001596}
1597
1598/// CreateType - get objective-c object type.
1599llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1600 llvm::DIFile Unit) {
1601 // Ignore protocols.
1602 return getOrCreateType(Ty->getBaseType(), Unit);
1603}
1604
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001605
1606/// \return true if Getter has the default name for the property PD.
1607static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1608 const ObjCMethodDecl *Getter) {
1609 assert(PD);
1610 if (!Getter)
1611 return true;
1612
1613 assert(Getter->getDeclName().isObjCZeroArgSelector());
1614 return PD->getName() ==
1615 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1616}
1617
1618/// \return true if Setter has the default name for the property PD.
1619static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1620 const ObjCMethodDecl *Setter) {
1621 assert(PD);
1622 if (!Setter)
1623 return true;
1624
1625 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001626 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001627 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1628}
1629
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001630/// CreateType - get objective-c interface type.
1631llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1632 llvm::DIFile Unit) {
1633 ObjCInterfaceDecl *ID = Ty->getDecl();
1634 if (!ID)
1635 return llvm::DIType();
1636
1637 // Get overall information about the record type for the debug info.
1638 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1639 unsigned Line = getLineNumber(ID->getLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001640 llvm::dwarf::SourceLanguage RuntimeLang = TheCU.getLanguage();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001641
1642 // If this is just a forward declaration return a special forward-declaration
1643 // debug type since we won't be able to lay out the entire type.
1644 ObjCInterfaceDecl *Def = ID->getDefinition();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001645 if (!Def || !Def->getImplementation()) {
1646 llvm::DIType FwdDecl = DBuilder.createReplaceableForwardDecl(
1647 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1648 RuntimeLang);
1649 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001650 return FwdDecl;
1651 }
1652
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001653
1654 return CreateTypeDefinition(Ty, Unit);
1655}
1656
1657llvm::DIType CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, llvm::DIFile Unit) {
1658 ObjCInterfaceDecl *ID = Ty->getDecl();
1659 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1660 unsigned Line = getLineNumber(ID->getLocation());
1661 unsigned RuntimeLang = TheCU.getLanguage();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001662
1663 // Bit size, align and offset of the type.
1664 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1665 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1666
1667 unsigned Flags = 0;
1668 if (ID->getImplementation())
1669 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1670
Eric Christopherf068c922013-04-02 22:59:11 +00001671 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001672 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1673 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001674 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001675
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001676 QualType QTy(Ty, 0);
1677 TypeCache[QTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001678
Eric Christopherd3003dc2013-07-14 21:00:07 +00001679 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001680 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001681 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1682
1683 // Convert all the elements.
1684 SmallVector<llvm::Value *, 16> EltTys;
1685
1686 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1687 if (SClass) {
1688 llvm::DIType SClassTy =
1689 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1690 if (!SClassTy.isValid())
1691 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001692
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001693 llvm::DIType InhTag =
1694 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1695 EltTys.push_back(InhTag);
1696 }
1697
Eric Christopherd3003dc2013-07-14 21:00:07 +00001698 // Create entries for all of the properties.
Stephen Hines651f13c2014-04-23 16:59:28 -07001699 for (const auto *PD : ID->properties()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001700 SourceLocation Loc = PD->getLocation();
1701 llvm::DIFile PUnit = getOrCreateFile(Loc);
1702 unsigned PLine = getLineNumber(Loc);
1703 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1704 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1705 llvm::MDNode *PropertyNode =
1706 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001707 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001708 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001709 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001710 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001711 getSelectorName(PD->getSetterName()),
1712 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001713 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 EltTys.push_back(PropertyNode);
1715 }
1716
1717 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1718 unsigned FieldNo = 0;
1719 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1720 Field = Field->getNextIvar(), ++FieldNo) {
1721 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1722 if (!FieldTy.isValid())
1723 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001724
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001725 StringRef FieldName = Field->getName();
1726
1727 // Ignore unnamed fields.
1728 if (FieldName.empty())
1729 continue;
1730
1731 // Get the location for the field.
1732 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1733 unsigned FieldLine = getLineNumber(Field->getLocation());
1734 QualType FType = Field->getType();
1735 uint64_t FieldSize = 0;
1736 unsigned FieldAlign = 0;
1737
1738 if (!FType->isIncompleteArrayType()) {
1739
1740 // Bit size, align and offset of the type.
1741 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001742 ? Field->getBitWidthValue(CGM.getContext())
1743 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001744 FieldAlign = CGM.getContext().getTypeAlign(FType);
1745 }
1746
1747 uint64_t FieldOffset;
1748 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1749 // We don't know the runtime offset of an ivar if we're using the
1750 // non-fragile ABI. For bitfields, use the bit offset into the first
1751 // byte of storage of the bitfield. For other fields, use zero.
1752 if (Field->isBitField()) {
1753 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1754 CGM, ID, Field);
1755 FieldOffset %= CGM.getContext().getCharWidth();
1756 } else {
1757 FieldOffset = 0;
1758 }
1759 } else {
1760 FieldOffset = RL.getFieldOffset(FieldNo);
1761 }
1762
1763 unsigned Flags = 0;
1764 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1765 Flags = llvm::DIDescriptor::FlagProtected;
1766 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1767 Flags = llvm::DIDescriptor::FlagPrivate;
1768
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001769 llvm::MDNode *PropertyNode = nullptr;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001770 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001771 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001772 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1773 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001774 SourceLocation Loc = PD->getLocation();
1775 llvm::DIFile PUnit = getOrCreateFile(Loc);
1776 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001777 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1778 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1779 PropertyNode =
1780 DBuilder.createObjCProperty(PD->getName(),
1781 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001782 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001783 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001784 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001785 getSelectorName(PD->getSetterName()),
1786 PD->getPropertyAttributes(),
1787 getOrCreateType(PD->getType(), PUnit));
1788 }
1789 }
1790 }
1791 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1792 FieldLine, FieldSize, FieldAlign,
1793 FieldOffset, Flags, FieldTy,
1794 PropertyNode);
1795 EltTys.push_back(FieldTy);
1796 }
1797
1798 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001799 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001800
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001801 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001802 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001803}
1804
1805llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1806 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1807 int64_t Count = Ty->getNumElements();
1808 if (Count == 0)
1809 // If number of elements are not known then this is an unbounded array.
1810 // Use Count == -1 to express such arrays.
1811 Count = -1;
1812
1813 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1814 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1815
1816 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1817 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1818
1819 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1820}
1821
1822llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1823 llvm::DIFile Unit) {
1824 uint64_t Size;
1825 uint64_t Align;
1826
1827 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1828 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1829 Size = 0;
1830 Align =
1831 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1832 } else if (Ty->isIncompleteArrayType()) {
1833 Size = 0;
1834 if (Ty->getElementType()->isIncompleteType())
1835 Align = 0;
1836 else
1837 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001838 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839 Size = 0;
1840 Align = 0;
1841 } else {
1842 // Size and align of the whole array, not the element type.
1843 Size = CGM.getContext().getTypeSize(Ty);
1844 Align = CGM.getContext().getTypeAlign(Ty);
1845 }
1846
1847 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1848 // interior arrays, do we care? Why aren't nested arrays represented the
1849 // obvious/recursive way?
1850 SmallVector<llvm::Value *, 8> Subscripts;
1851 QualType EltTy(Ty, 0);
1852 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1853 // If the number of elements is known, then count is that number. Otherwise,
1854 // it's -1. This allows us to represent a subrange with an array of 0
1855 // elements, like this:
1856 //
1857 // struct foo {
1858 // int x[0];
1859 // };
1860 int64_t Count = -1; // Count == -1 is an unbounded array.
1861 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1862 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001863
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001864 // FIXME: Verify this is right for VLAs.
1865 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1866 EltTy = Ty->getElementType();
1867 }
1868
1869 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1870
Eric Christopher6537f082013-05-16 00:45:12 +00001871 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001872 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1873 SubscriptArray);
1874 return DbgTy;
1875}
1876
Eric Christopher6537f082013-05-16 00:45:12 +00001877llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001878 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001879 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 Ty, Ty->getPointeeType(), Unit);
1881}
1882
Eric Christopher6537f082013-05-16 00:45:12 +00001883llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001884 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001885 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001886 Ty, Ty->getPointeeType(), Unit);
1887}
1888
Eric Christopher6537f082013-05-16 00:45:12 +00001889llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001890 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001891 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1892 if (!Ty->getPointeeType()->isFunctionType())
1893 return DBuilder.createMemberPointerType(
David Blaikie29b8b682013-09-04 22:03:57 +00001894 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Stephen Hines651f13c2014-04-23 16:59:28 -07001895
1896 const FunctionProtoType *FPT =
1897 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikiee8d75142013-01-19 19:20:56 +00001898 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Stephen Hines651f13c2014-04-23 16:59:28 -07001899 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1900 FPT->getTypeQuals())),
1901 FPT, U), ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902}
1903
Eric Christopher6537f082013-05-16 00:45:12 +00001904llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001905 llvm::DIFile U) {
1906 // Ignore the atomic wrapping
1907 // FIXME: What is the correct representation?
1908 return getOrCreateType(Ty->getValueType(), U);
1909}
1910
1911/// CreateEnumType - get enumeration type.
Manman Ren0a0be742013-08-28 21:46:36 +00001912llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Renf3327332013-08-28 21:20:28 +00001913 const EnumDecl *ED = Ty->getDecl();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001914 uint64_t Size = 0;
1915 uint64_t Align = 0;
1916 if (!ED->getTypeForDecl()->isIncompleteType()) {
1917 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1918 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1919 }
1920
Manman Ren83369bf2013-08-29 23:19:58 +00001921 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1922
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001923 // If this is just a forward declaration, construct an appropriately
1924 // marked node and just return it.
1925 if (!ED->getDefinition()) {
1926 llvm::DIDescriptor EDContext;
1927 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1928 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1929 unsigned Line = getLineNumber(ED->getLocation());
1930 StringRef EDName = ED->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001931 llvm::DIType RetTy = DBuilder.createReplaceableForwardDecl(
1932 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1933 0, Size, Align, FullName);
1934 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
1935 return RetTy;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001936 }
1937
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001938 return CreateTypeDefinition(Ty);
1939}
1940
1941llvm::DIType CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1942 const EnumDecl *ED = Ty->getDecl();
1943 uint64_t Size = 0;
1944 uint64_t Align = 0;
1945 if (!ED->getTypeForDecl()->isIncompleteType()) {
1946 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1947 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1948 }
1949
1950 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1951
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001952 // Create DIEnumerator elements for each enumerator.
1953 SmallVector<llvm::Value *, 16> Enumerators;
1954 ED = ED->getDefinition();
Stephen Hines651f13c2014-04-23 16:59:28 -07001955 for (const auto *Enum : ED->enumerators()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001956 Enumerators.push_back(
1957 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001958 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001959 }
1960
1961 // Return a CompositeType for the enum itself.
1962 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1963
1964 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1965 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001966 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001968 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001969 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001970 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001971 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1972 Size, Align, EltArray,
Manman Ren83369bf2013-08-29 23:19:58 +00001973 ClassTy, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001974 return DbgTy;
1975}
1976
David Blaikie4b12be62013-01-21 04:37:12 +00001977static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1978 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001979 do {
Adrian Prantl35969ea2013-09-26 21:35:50 +00001980 Qualifiers InnerQuals = T.getLocalQualifiers();
1981 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1982 // that is already there.
1983 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1984 Quals += InnerQuals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001985 QualType LastT = T;
1986 switch (T->getTypeClass()) {
1987 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001988 return C.getQualifiedType(T.getTypePtr(), Quals);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001989 case Type::TemplateSpecialization: {
1990 const auto *Spec = cast<TemplateSpecializationType>(T);
1991 if (Spec->isTypeAlias())
1992 return C.getQualifiedType(T.getTypePtr(), Quals);
1993 T = Spec->desugar();
1994 break; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001995 case Type::TypeOfExpr:
1996 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1997 break;
1998 case Type::TypeOf:
1999 T = cast<TypeOfType>(T)->getUnderlyingType();
2000 break;
2001 case Type::Decltype:
2002 T = cast<DecltypeType>(T)->getUnderlyingType();
2003 break;
2004 case Type::UnaryTransform:
2005 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2006 break;
2007 case Type::Attributed:
2008 T = cast<AttributedType>(T)->getEquivalentType();
2009 break;
2010 case Type::Elaborated:
2011 T = cast<ElaboratedType>(T)->getNamedType();
2012 break;
2013 case Type::Paren:
2014 T = cast<ParenType>(T)->getInnerType();
2015 break;
David Blaikie4b12be62013-01-21 04:37:12 +00002016 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002017 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002018 break;
2019 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00002020 QualType DT = cast<AutoType>(T)->getDeducedType();
2021 if (DT.isNull())
2022 return T;
2023 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002024 break;
2025 }
Eric Christopher6537f082013-05-16 00:45:12 +00002026
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002027 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00002028 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002029 } while (true);
2030}
2031
Eric Christopherf0890c42013-05-16 00:52:20 +00002032/// getType - Get the type from the cache or return null type if it doesn't
2033/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002034llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2035
2036 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002037 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00002038
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002039 auto it = TypeCache.find(Ty.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002040 if (it != TypeCache.end()) {
2041 // Verify that the debug info still exists.
2042 if (llvm::Value *V = it->second)
2043 return llvm::DIType(cast<llvm::MDNode>(V));
2044 }
2045
2046 return llvm::DIType();
2047}
2048
Stephen Hines651f13c2014-04-23 16:59:28 -07002049void CGDebugInfo::completeTemplateDefinition(
2050 const ClassTemplateSpecializationDecl &SD) {
2051 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2052 return;
2053
2054 completeClassData(&SD);
2055 // In case this type has no member function definitions being emitted, ensure
2056 // it is retained
2057 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2058}
2059
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002060/// getOrCreateType - Get the type from the cache or create a new
2061/// one if necessary.
David Blaikie29b8b682013-09-04 22:03:57 +00002062llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002063 if (Ty.isNull())
2064 return llvm::DIType();
2065
2066 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002067 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002069 if (llvm::DIType T = getTypeOrNull(Ty))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002070 return T;
2071
2072 // Otherwise create the type.
David Blaikie29b8b682013-09-04 22:03:57 +00002073 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002074 void* TyPtr = Ty.getAsOpaquePtr();
2075
2076 // And update the type cache.
2077 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002078
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002079 return Res;
2080}
2081
Adrian Prantlb5a50072013-06-07 01:10:41 +00002082/// Currently the checksum of an interface includes the number of
2083/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002084unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002085 // The assumption is that the number of ivars can only increase
2086 // monotonically, so it is safe to just use their current number as
2087 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002088 unsigned Sum = 0;
2089 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002090 Ivar != nullptr; Ivar = Ivar->getNextIvar())
Adrian Prantlb5a50072013-06-07 01:10:41 +00002091 ++Sum;
2092
2093 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002094}
2095
2096ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2097 switch (Ty->getTypeClass()) {
2098 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002099 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2100 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002101 case Type::ObjCInterface:
2102 return cast<ObjCInterfaceType>(Ty)->getDecl();
2103 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002104 return nullptr;
Adrian Prantl4919de62013-03-06 22:03:30 +00002105 }
2106}
2107
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002108/// CreateTypeNode - Create a new debug type node.
David Blaikie29b8b682013-09-04 22:03:57 +00002109llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002110 // Handle qualifiers, which recursively handles what they refer to.
2111 if (Ty.hasLocalQualifiers())
David Blaikie29b8b682013-09-04 22:03:57 +00002112 return CreateQualifiedType(Ty, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002113
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002114 const char *Diag = nullptr;
Eric Christopher6537f082013-05-16 00:45:12 +00002115
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002116 // Work out details of type.
2117 switch (Ty->getTypeClass()) {
2118#define TYPE(Class, Base)
2119#define ABSTRACT_TYPE(Class, Base)
2120#define NON_CANONICAL_TYPE(Class, Base)
2121#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2122#include "clang/AST/TypeNodes.def"
2123 llvm_unreachable("Dependent types cannot show up in debug information");
2124
2125 case Type::ExtVector:
2126 case Type::Vector:
2127 return CreateType(cast<VectorType>(Ty), Unit);
2128 case Type::ObjCObjectPointer:
2129 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2130 case Type::ObjCObject:
2131 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2132 case Type::ObjCInterface:
2133 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2134 case Type::Builtin:
2135 return CreateType(cast<BuiltinType>(Ty));
2136 case Type::Complex:
2137 return CreateType(cast<ComplexType>(Ty));
2138 case Type::Pointer:
2139 return CreateType(cast<PointerType>(Ty), Unit);
Stephen Hines651f13c2014-04-23 16:59:28 -07002140 case Type::Adjusted:
Reid Kleckner12df2462013-06-24 17:51:48 +00002141 case Type::Decayed:
Stephen Hines651f13c2014-04-23 16:59:28 -07002142 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner12df2462013-06-24 17:51:48 +00002143 return CreateType(
Stephen Hines651f13c2014-04-23 16:59:28 -07002144 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002145 case Type::BlockPointer:
2146 return CreateType(cast<BlockPointerType>(Ty), Unit);
2147 case Type::Typedef:
David Blaikie29b8b682013-09-04 22:03:57 +00002148 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002149 case Type::Record:
David Blaikie29b8b682013-09-04 22:03:57 +00002150 return CreateType(cast<RecordType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002151 case Type::Enum:
Manman Renf3327332013-08-28 21:20:28 +00002152 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002153 case Type::FunctionProto:
2154 case Type::FunctionNoProto:
2155 return CreateType(cast<FunctionType>(Ty), Unit);
2156 case Type::ConstantArray:
2157 case Type::VariableArray:
2158 case Type::IncompleteArray:
2159 return CreateType(cast<ArrayType>(Ty), Unit);
2160
2161 case Type::LValueReference:
2162 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2163 case Type::RValueReference:
2164 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2165
2166 case Type::MemberPointer:
2167 return CreateType(cast<MemberPointerType>(Ty), Unit);
2168
2169 case Type::Atomic:
2170 return CreateType(cast<AtomicType>(Ty), Unit);
2171
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002172 case Type::TemplateSpecialization:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002173 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2174
2175 case Type::Attributed:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002176 case Type::Elaborated:
2177 case Type::Paren:
2178 case Type::SubstTemplateTypeParm:
2179 case Type::TypeOfExpr:
2180 case Type::TypeOf:
2181 case Type::Decltype:
2182 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002183 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002184 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002185 case Type::Auto:
2186 Diag = "auto";
2187 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002188 }
Eric Christopher6537f082013-05-16 00:45:12 +00002189
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002190 assert(Diag && "Fall through without a diagnostic?");
2191 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2192 "debug information for %0 is not yet supported");
2193 CGM.getDiags().Report(DiagID)
2194 << Diag;
2195 return llvm::DIType();
2196}
2197
2198/// getOrCreateLimitedType - Get the type from the cache or create a new
2199/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002200llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002201 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002202 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002203
David Blaikieeaacc882013-08-20 21:03:29 +00002204 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002205
2206 // We may have cached a forward decl when we could have created
2207 // a non-forward decl. Go ahead and create a non-forward decl
2208 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002209 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002210
2211 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002212 llvm::DICompositeType Res = CreateLimitedType(Ty);
2213
2214 // Propagate members from the declaration to the definition
2215 // CreateType(const RecordType*) will overwrite this with the members in the
2216 // correct order if the full type is needed.
2217 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002218
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002219 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002220 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002221 return Res;
2222}
2223
2224// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002225llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002226 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002227
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002228 // Get overall information about the record type for the debug info.
2229 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2230 unsigned Line = getLineNumber(RD->getLocation());
2231 StringRef RDName = getClassName(RD);
2232
Eric Christopher89fecb52013-10-15 21:22:34 +00002233 llvm::DIDescriptor RDContext =
2234 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002235
David Blaikiec138ff52013-08-18 17:36:19 +00002236 // If we ended up creating the type during the context chain construction,
2237 // just return that.
David Blaikieeaacc882013-08-20 21:03:29 +00002238 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2239 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002240 return T;
2241
Stephen Hines651f13c2014-04-23 16:59:28 -07002242 // If this is just a forward or incomplete declaration, construct an
2243 // appropriately marked node and just return it.
2244 const RecordDecl *D = RD->getDefinition();
2245 if (!D || !D->isCompleteDefinition())
Manman Renf3327332013-08-28 21:20:28 +00002246 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002247
2248 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2249 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002250 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002251
Manman Ren83369bf2013-08-29 23:19:58 +00002252 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2253
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002254 if (RD->isUnion())
2255 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Ren83369bf2013-08-29 23:19:58 +00002256 Size, Align, 0, llvm::DIArray(), 0,
2257 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002258 else if (RD->isClass()) {
2259 // FIXME: This could be a struct type giving a default visibility different
2260 // than C++ class type, but needs llvm metadata changes first.
2261 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002262 Size, Align, 0, 0, llvm::DIType(),
2263 llvm::DIArray(), llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002264 llvm::DIArray(), FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002265 } else
2266 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002267 Size, Align, 0, llvm::DIType(),
David Blaikie96b7bd42013-11-18 23:38:26 +00002268 llvm::DIArray(), 0, llvm::DIType(),
2269 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002270
2271 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002272 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002273
David Blaikie498298d2013-08-18 16:55:33 +00002274 if (const ClassTemplateSpecializationDecl *TSpecial =
2275 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2276 RealDecl.setTypeArray(llvm::DIArray(),
2277 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002278 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002279}
2280
David Blaikie498298d2013-08-18 16:55:33 +00002281void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2282 llvm::DICompositeType RealDecl) {
2283 // A class's primary base or the class itself contains the vtable.
2284 llvm::DICompositeType ContainingType;
2285 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2286 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002287 // Seek non-virtual primary base root.
David Blaikie498298d2013-08-18 16:55:33 +00002288 while (1) {
2289 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2290 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2291 if (PBT && !BRL.isPrimaryBaseVirtual())
2292 PBase = PBT;
2293 else
2294 break;
2295 }
2296 ContainingType = llvm::DICompositeType(
2297 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2298 getOrCreateFile(RD->getLocation())));
2299 } else if (RD->isDynamicClass())
2300 ContainingType = RealDecl;
2301
2302 RealDecl.setContainingType(ContainingType);
2303}
2304
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002305/// CreateMemberType - Create new member and increase Offset by FType's size.
2306llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2307 StringRef Name,
2308 uint64_t *Offset) {
2309 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2310 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2311 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2312 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2313 FieldSize, FieldAlign,
2314 *Offset, 0, FieldTy);
2315 *Offset += FieldSize;
2316 return Ty;
2317}
2318
Stephen Hines651f13c2014-04-23 16:59:28 -07002319llvm::DIScope CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikie9faebd22013-05-20 04:58:53 +00002320 // We only need a declaration (not a definition) of the type - so use whatever
2321 // we would otherwise do to get a type for a pointee. (forward declarations in
2322 // limited debug info, full definitions (if the type definition is available)
2323 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002324 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2325 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie29b8b682013-09-04 22:03:57 +00002326 getOrCreateFile(TD->getLocation()));
David Blaikie9faebd22013-05-20 04:58:53 +00002327 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2328 // This doesn't handle providing declarations (for functions or variables) for
2329 // entities without definitions in this TU, nor when the definition proceeds
2330 // the call to this function.
2331 // FIXME: This should be split out into more specific maps with support for
2332 // emitting forward declarations and merging definitions with declarations,
2333 // the same way as we do for types.
2334 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2335 DeclCache.find(D->getCanonicalDecl());
2336 if (I == DeclCache.end())
Stephen Hines651f13c2014-04-23 16:59:28 -07002337 return llvm::DIScope();
David Blaikie9faebd22013-05-20 04:58:53 +00002338 llvm::Value *V = I->second;
Stephen Hines651f13c2014-04-23 16:59:28 -07002339 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie9faebd22013-05-20 04:58:53 +00002340}
2341
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002342/// getFunctionDeclaration - Return debug info descriptor to describe method
2343/// declaration for the given method definition.
2344llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002345 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
David Blaikie23e66db2013-06-22 00:09:36 +00002346 return llvm::DISubprogram();
2347
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002348 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2349 if (!FD) return llvm::DISubprogram();
2350
2351 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002352 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002353
2354 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2355 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002356 if (MI == SPCache.end()) {
Eric Christopherac7c25f2013-08-28 23:12:10 +00002357 if (const CXXMethodDecl *MD =
2358 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002359 llvm::DICompositeType T(S);
Eric Christopherac7c25f2013-08-28 23:12:10 +00002360 llvm::DISubprogram SP =
2361 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikied6d5d692013-08-09 17:20:05 +00002362 return SP;
2363 }
2364 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002365 if (MI != SPCache.end()) {
2366 llvm::Value *V = MI->second;
2367 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002368 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002369 return SP;
2370 }
2371
Stephen Hines651f13c2014-04-23 16:59:28 -07002372 for (auto NextFD : FD->redecls()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002373 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2374 MI = SPCache.find(NextFD->getCanonicalDecl());
2375 if (MI != SPCache.end()) {
2376 llvm::Value *V = MI->second;
2377 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002378 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002379 return SP;
2380 }
2381 }
2382 return llvm::DISubprogram();
2383}
2384
2385// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2386// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002387llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2388 QualType FnType,
2389 llvm::DIFile F) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002390 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
David Blaikie23e66db2013-06-22 00:09:36 +00002391 // Create fake but valid subroutine type. Otherwise
2392 // llvm::DISubprogram::Verify() would return false, and
2393 // subprogram DIE will miss DW_AT_decl_file and
2394 // DW_AT_decl_line fields.
2395 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002396
2397 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2398 return getOrCreateMethodType(Method, F);
2399 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2400 // Add "self" and "_cmd"
2401 SmallVector<llvm::Value *, 16> Elts;
2402
2403 // First element is always return type. For 'void' functions it is NULL.
Stephen Hines651f13c2014-04-23 16:59:28 -07002404 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl0cb00022013-05-22 21:37:49 +00002405
2406 // Replace the instancetype keyword with the actual type.
2407 if (ResultTy == CGM.getContext().getObjCInstanceType())
2408 ResultTy = CGM.getContext().getPointerType(
2409 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2410
Adrian Prantl566a9c32013-05-10 21:08:31 +00002411 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002412 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002413 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2414 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2415 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002416 // "_cmd" pointer is always second argument.
2417 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2418 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2419 // Get rest of the arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07002420 for (const auto *PI : OMethod->params())
2421 Elts.push_back(getOrCreateType(PI->getType(), F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002422
2423 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2424 return DBuilder.createSubroutineType(F, EltTypeArray);
2425 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002426
2427 // Handle variadic function types; they need an additional
2428 // unspecified parameter.
2429 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2430 if (FD->isVariadic()) {
2431 SmallVector<llvm::Value *, 16> EltTys;
2432 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2433 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2434 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2435 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2436 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2437 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2438 return DBuilder.createSubroutineType(F, EltTypeArray);
2439 }
2440
David Blaikie9a845292013-05-22 23:22:42 +00002441 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002442}
2443
2444/// EmitFunctionStart - Constructs the debug code for entering a function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002445void CGDebugInfo::EmitFunctionStart(GlobalDecl GD,
2446 SourceLocation Loc,
2447 SourceLocation ScopeLoc,
2448 QualType FnType,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002449 llvm::Function *Fn,
2450 CGBuilderTy &Builder) {
2451
2452 StringRef Name;
2453 StringRef LinkageName;
2454
2455 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2456
2457 const Decl *D = GD.getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002458 bool HasDecl = (D != nullptr);
Stephen Hines651f13c2014-04-23 16:59:28 -07002459
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002460 unsigned Flags = 0;
2461 llvm::DIFile Unit = getOrCreateFile(Loc);
2462 llvm::DIDescriptor FDContext(Unit);
2463 llvm::DIArray TParamsArray;
2464 if (!HasDecl) {
2465 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002466 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002467 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2468 // If there is a DISubprogram for this function available then use it.
2469 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2470 FI = SPCache.find(FD->getCanonicalDecl());
2471 if (FI != SPCache.end()) {
2472 llvm::Value *V = FI->second;
2473 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2474 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2475 llvm::MDNode *SPN = SP;
2476 LexicalBlockStack.push_back(SPN);
2477 RegionMap[D] = llvm::WeakVH(SP);
2478 return;
2479 }
2480 }
2481 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002482 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002483 if (FD->hasPrototype()) {
2484 LinkageName = CGM.getMangledName(GD);
2485 Flags |= llvm::DIDescriptor::FlagPrototyped;
2486 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002487 // No need to replicate the linkage name if it isn't different from the
2488 // subprogram name, no need to have it at all unless coverage is enabled or
2489 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002490 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002491 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2492 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002493 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002494 LinkageName = StringRef();
2495
Eric Christopher13c97672013-05-16 00:45:23 +00002496 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002497 if (const NamespaceDecl *NSDecl =
Eric Christopher2e3fd942013-10-17 01:31:21 +00002498 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002499 FDContext = getOrCreateNameSpace(NSDecl);
2500 else if (const RecordDecl *RDecl =
Eric Christopher2e3fd942013-10-17 01:31:21 +00002501 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2502 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002503
2504 // Collect template parameters.
2505 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2506 }
2507 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2508 Name = getObjCMethodName(OMD);
2509 Flags |= llvm::DIDescriptor::FlagPrototyped;
2510 } else {
2511 // Use llvm function name.
2512 Name = Fn->getName();
2513 Flags |= llvm::DIDescriptor::FlagPrototyped;
2514 }
2515 if (!Name.empty() && Name[0] == '\01')
2516 Name = Name.substr(1);
2517
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002518 if (!HasDecl || D->isImplicit()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002519 Flags |= llvm::DIDescriptor::FlagArtificial;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002520 // Artificial functions without a location should not silently reuse CurLoc.
2521 if (Loc.isInvalid())
2522 CurLoc = SourceLocation();
2523 }
2524 unsigned LineNo = getLineNumber(Loc);
2525 unsigned ScopeLine = getLineNumber(ScopeLoc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002526
Stephen Hines651f13c2014-04-23 16:59:28 -07002527 // FIXME: The function declaration we're constructing here is mostly reusing
2528 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2529 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2530 // all subprograms instead of the actual context since subprogram definitions
2531 // are emitted as CU level entities by the backend.
Eric Christopher2e3fd942013-10-17 01:31:21 +00002532 llvm::DISubprogram SP =
2533 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2534 getOrCreateFunctionType(D, FnType, Unit),
2535 Fn->hasInternalLinkage(), true /*definition*/,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002536 ScopeLine, Flags,
Eric Christopher2e3fd942013-10-17 01:31:21 +00002537 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2538 getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002539 if (HasDecl)
2540 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002541
Stephen Hines651f13c2014-04-23 16:59:28 -07002542 // Push the function onto the lexical block stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002543 llvm::MDNode *SPN = SP;
2544 LexicalBlockStack.push_back(SPN);
Stephen Hines651f13c2014-04-23 16:59:28 -07002545
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002546 if (HasDecl)
2547 RegionMap[D] = llvm::WeakVH(SP);
2548}
2549
2550/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002551/// information in the source file. If the location is invalid, the
2552/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002553void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2554 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002555 // Update our current location
2556 setLocation(Loc);
2557
2558 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2559
2560 // Don't bother if things are the same as last time.
2561 SourceManager &SM = CGM.getContext().getSourceManager();
2562 if (CurLoc == PrevLoc ||
2563 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2564 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002565 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2566 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2567 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002568 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002569
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002570 // Update last state.
2571 PrevLoc = CurLoc;
2572
2573 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002574 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2575 (getLineNumber(CurLoc),
2576 getColumnNumber(CurLoc, ForceColumnInfo),
2577 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002578}
2579
2580/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2581/// the stack.
2582void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002583 llvm::DIDescriptor D = DBuilder.createLexicalBlock(
2584 llvm::DIDescriptor(LexicalBlockStack.empty() ? nullptr
2585 : LexicalBlockStack.back()),
2586 getOrCreateFile(CurLoc), getLineNumber(CurLoc), getColumnNumber(CurLoc),
2587 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002588 llvm::MDNode *DN = D;
2589 LexicalBlockStack.push_back(DN);
2590}
2591
2592/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2593/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002594void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2595 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002596 // Set our current location.
2597 setLocation(Loc);
2598
2599 // Create a new lexical block and push it on the stack.
2600 CreateLexicalBlock(Loc);
2601
2602 // Emit a line table change for the current location inside the new scope.
2603 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2604 getColumnNumber(Loc),
2605 LexicalBlockStack.back()));
2606}
2607
2608/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2609/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002610void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2611 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002612 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2613
2614 // Provide an entry in the line table for the end of the block.
2615 EmitLocation(Builder, Loc);
2616
2617 LexicalBlockStack.pop_back();
2618}
2619
2620/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2621void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2622 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2623 unsigned RCount = FnBeginRegionCount.back();
2624 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2625
2626 // Pop all regions for this function.
2627 while (LexicalBlockStack.size() != RCount)
2628 EmitLexicalBlockEnd(Builder, CurLoc);
2629 FnBeginRegionCount.pop_back();
2630}
2631
Eric Christopher6537f082013-05-16 00:45:12 +00002632// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002633// See BuildByRefType.
2634llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2635 uint64_t *XOffset) {
2636
2637 SmallVector<llvm::Value *, 5> EltTys;
2638 QualType FType;
2639 uint64_t FieldSize, FieldOffset;
2640 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002641
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002643 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002644
2645 FieldOffset = 0;
2646 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2647 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2648 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2649 FType = CGM.getContext().IntTy;
2650 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2651 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2652
2653 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2654 if (HasCopyAndDispose) {
2655 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2656 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2657 &FieldOffset));
2658 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2659 &FieldOffset));
2660 }
2661 bool HasByrefExtendedLayout;
2662 Qualifiers::ObjCLifetime Lifetime;
2663 if (CGM.getContext().getByrefLifetime(Type,
2664 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002665 && HasByrefExtendedLayout) {
2666 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002667 EltTys.push_back(CreateMemberType(Unit, FType,
2668 "__byref_variable_layout",
2669 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002670 }
Eric Christopher6537f082013-05-16 00:45:12 +00002671
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002672 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2673 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002674 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002675 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002676 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2677 CharUnits AlignedOffsetInBytes
2678 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2679 CharUnits NumPaddingBytes
2680 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002681
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002682 if (NumPaddingBytes.isPositive()) {
2683 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2684 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2685 pad, ArrayType::Normal, 0);
2686 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2687 }
2688 }
Eric Christopher6537f082013-05-16 00:45:12 +00002689
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002690 FType = Type;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002691 llvm::DIType FieldTy = getOrCreateType(FType, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002692 FieldSize = CGM.getContext().getTypeSize(FType);
2693 FieldAlign = CGM.getContext().toBits(Align);
2694
Eric Christopher6537f082013-05-16 00:45:12 +00002695 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2697 0, FieldSize, FieldAlign,
2698 FieldOffset, 0, FieldTy);
2699 EltTys.push_back(FieldTy);
2700 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002701
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002702 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002703
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002705
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002706 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002707 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002708}
2709
2710/// EmitDeclare - Emit local variable declaration debug info.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002711void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::LLVMConstants Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002712 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002713 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002714 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002715 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2716
David Blaikiefc946272013-08-19 03:37:48 +00002717 bool Unwritten =
2718 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2719 cast<Decl>(VD->getDeclContext())->isImplicit());
2720 llvm::DIFile Unit;
2721 if (!Unwritten)
2722 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002723 llvm::DIType Ty;
2724 uint64_t XOffset = 0;
2725 if (VD->hasAttr<BlocksAttr>())
2726 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002727 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728 Ty = getOrCreateType(VD->getType(), Unit);
2729
2730 // If there is no debug info for this type then do not emit debug info
2731 // for this variable.
2732 if (!Ty)
2733 return;
2734
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002735 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002736 unsigned Line = 0;
2737 unsigned Column = 0;
2738 if (!Unwritten) {
2739 Line = getLineNumber(VD->getLocation());
2740 Column = getColumnNumber(VD->getLocation());
2741 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002742 unsigned Flags = 0;
2743 if (VD->isImplicit())
2744 Flags |= llvm::DIDescriptor::FlagArtificial;
2745 // If this is the first argument and it is implicit then
2746 // give it an object pointer flag.
2747 // FIXME: There has to be a better way to do this, but for static
2748 // functions there won't be an implicit param at arg1 and
2749 // otherwise it is 'self' or 'this'.
2750 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2751 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002752 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002753 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2754 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002755 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002756
2757 llvm::MDNode *Scope = LexicalBlockStack.back();
2758
2759 StringRef Name = VD->getName();
2760 if (!Name.empty()) {
2761 if (VD->hasAttr<BlocksAttr>()) {
2762 CharUnits offset = CharUnits::fromQuantity(32);
2763 SmallVector<llvm::Value *, 9> addr;
2764 llvm::Type *Int64Ty = CGM.Int64Ty;
2765 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2766 // offset of __forwarding field
2767 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002768 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002769 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2770 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2771 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2772 // offset of x field
2773 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2774 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2775
2776 // Create the descriptor for the variable.
2777 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002778 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002779 llvm::DIDescriptor(Scope),
2780 VD->getName(), Unit, Line, Ty,
2781 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002782
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002783 // Insert an llvm.dbg.declare into the current block.
2784 llvm::Instruction *Call =
2785 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2786 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2787 return;
Adrian Prantl39232cd2013-09-18 22:18:17 +00002788 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl95d3d1a2013-09-18 22:08:57 +00002789 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikie436653b2013-01-05 05:58:35 +00002790 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2791 // If VD is an anonymous union then Storage represents value for
2792 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002793 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002794 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002795 for (const auto *Field : RD->fields()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002796 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2797 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002798
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 // Ignore unnamed fields. Do not ignore unnamed records.
2800 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2801 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002802
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002803 // Use VarDecl's Tag, Scope and Line number.
2804 llvm::DIVariable D =
2805 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002806 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002807 CGM.getLangOpts().Optimize, Flags,
2808 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002809
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002810 // Insert an llvm.dbg.declare into the current block.
2811 llvm::Instruction *Call =
2812 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2813 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2814 }
David Blaikied8180cf2013-01-05 20:03:07 +00002815 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002816 }
2817 }
David Blaikie436653b2013-01-05 05:58:35 +00002818
2819 // Create the descriptor for the variable.
2820 llvm::DIVariable D =
2821 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2822 Name, Unit, Line, Ty,
2823 CGM.getLangOpts().Optimize, Flags, ArgNo);
2824
2825 // Insert an llvm.dbg.declare into the current block.
2826 llvm::Instruction *Call =
2827 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2828 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002829}
2830
2831void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2832 llvm::Value *Storage,
2833 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002834 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002835 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2836}
2837
Adrian Prantle86fcc42013-03-29 19:20:29 +00002838/// Look up the completed type for a self pointer in the TypeCache and
2839/// create a copy of it with the ObjectPointer and Artificial flags
2840/// set. If the type is not cached, a new one is created. This should
2841/// never happen though, since creating a type for the implicit self
2842/// argument implies that we already parsed the interface definition
2843/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002844llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2845 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002846 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002847 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002848 return DBuilder.createObjectPointerType(Ty);
2849}
2850
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002851void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2852 llvm::Value *Storage,
2853 CGBuilderTy &Builder,
2854 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002855 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002856 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002857
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002858 if (Builder.GetInsertBlock() == nullptr)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002859 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002860
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002861 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002862
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002863 uint64_t XOffset = 0;
2864 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2865 llvm::DIType Ty;
2866 if (isByRef)
2867 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002868 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002869 Ty = getOrCreateType(VD->getType(), Unit);
2870
2871 // Self is passed along as an implicit non-arg variable in a
2872 // block. Mark it as the object pointer.
2873 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002874 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002875
2876 // Get location information.
2877 unsigned Line = getLineNumber(VD->getLocation());
2878 unsigned Column = getColumnNumber(VD->getLocation());
2879
2880 const llvm::DataLayout &target = CGM.getDataLayout();
2881
2882 CharUnits offset = CharUnits::fromQuantity(
2883 target.getStructLayout(blockInfo.StructureType)
2884 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2885
2886 SmallVector<llvm::Value *, 9> addr;
2887 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002888 if (isa<llvm::AllocaInst>(Storage))
2889 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002890 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2891 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2892 if (isByRef) {
2893 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2894 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2895 // offset of __forwarding field
2896 offset = CGM.getContext()
2897 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2898 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2899 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2900 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2901 // offset of x field
2902 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2903 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2904 }
2905
2906 // Create the descriptor for the variable.
2907 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002908 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002909 llvm::DIDescriptor(LexicalBlockStack.back()),
2910 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002911
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002912 // Insert an llvm.dbg.declare into the current block.
2913 llvm::Instruction *Call =
2914 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2915 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2916 LexicalBlockStack.back()));
2917}
2918
2919/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2920/// variable declaration.
2921void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2922 unsigned ArgNo,
2923 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002924 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002925 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2926}
2927
2928namespace {
2929 struct BlockLayoutChunk {
2930 uint64_t OffsetInBits;
2931 const BlockDecl::Capture *Capture;
2932 };
2933 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2934 return l.OffsetInBits < r.OffsetInBits;
2935 }
2936}
2937
2938void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002939 llvm::Value *Arg,
2940 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002941 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002942 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002943 ASTContext &C = CGM.getContext();
2944 const BlockDecl *blockDecl = block.getBlockDecl();
2945
2946 // Collect some general information about the block's location.
2947 SourceLocation loc = blockDecl->getCaretLocation();
2948 llvm::DIFile tunit = getOrCreateFile(loc);
2949 unsigned line = getLineNumber(loc);
2950 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002951
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002952 // Build the debug-info type for the block literal.
2953 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2954
2955 const llvm::StructLayout *blockLayout =
2956 CGM.getDataLayout().getStructLayout(block.StructureType);
2957
2958 SmallVector<llvm::Value*, 16> fields;
2959 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2960 blockLayout->getElementOffsetInBits(0),
2961 tunit, tunit));
2962 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2963 blockLayout->getElementOffsetInBits(1),
2964 tunit, tunit));
2965 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2966 blockLayout->getElementOffsetInBits(2),
2967 tunit, tunit));
2968 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2969 blockLayout->getElementOffsetInBits(3),
2970 tunit, tunit));
2971 fields.push_back(createFieldType("__descriptor",
2972 C.getPointerType(block.NeedsCopyDispose ?
2973 C.getBlockDescriptorExtendedType() :
2974 C.getBlockDescriptorType()),
2975 0, loc, AS_public,
2976 blockLayout->getElementOffsetInBits(4),
2977 tunit, tunit));
2978
2979 // We want to sort the captures by offset, not because DWARF
2980 // requires this, but because we're paranoid about debuggers.
2981 SmallVector<BlockLayoutChunk, 8> chunks;
2982
2983 // 'this' capture.
2984 if (blockDecl->capturesCXXThis()) {
2985 BlockLayoutChunk chunk;
2986 chunk.OffsetInBits =
2987 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002988 chunk.Capture = nullptr;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002989 chunks.push_back(chunk);
2990 }
2991
2992 // Variable captures.
Stephen Hines651f13c2014-04-23 16:59:28 -07002993 for (const auto &capture : blockDecl->captures()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002994 const VarDecl *variable = capture.getVariable();
2995 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2996
2997 // Ignore constant captures.
2998 if (captureInfo.isConstant())
2999 continue;
3000
3001 BlockLayoutChunk chunk;
3002 chunk.OffsetInBits =
3003 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3004 chunk.Capture = &capture;
3005 chunks.push_back(chunk);
3006 }
3007
3008 // Sort by offset.
3009 llvm::array_pod_sort(chunks.begin(), chunks.end());
3010
3011 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3012 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3013 uint64_t offsetInBits = i->OffsetInBits;
3014 const BlockDecl::Capture *capture = i->Capture;
3015
3016 // If we have a null capture, this must be the C++ 'this' capture.
3017 if (!capture) {
3018 const CXXMethodDecl *method =
3019 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3020 QualType type = method->getThisType(C);
3021
3022 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3023 offsetInBits, tunit, tunit));
3024 continue;
3025 }
3026
3027 const VarDecl *variable = capture->getVariable();
3028 StringRef name = variable->getName();
3029
3030 llvm::DIType fieldType;
3031 if (capture->isByRef()) {
3032 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3033
3034 // FIXME: this creates a second copy of this type!
3035 uint64_t xoffset;
3036 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3037 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3038 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3039 ptrInfo.first, ptrInfo.second,
3040 offsetInBits, 0, fieldType);
3041 } else {
3042 fieldType = createFieldType(name, variable->getType(), 0,
3043 loc, AS_public, offsetInBits, tunit, tunit);
3044 }
3045 fields.push_back(fieldType);
3046 }
3047
3048 SmallString<36> typeName;
3049 llvm::raw_svector_ostream(typeName)
3050 << "__block_literal_" << CGM.getUniqueBlockCount();
3051
3052 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3053
3054 llvm::DIType type =
3055 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3056 CGM.getContext().toBits(block.BlockSize),
3057 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003058 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003059 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3060
3061 // Get overall information about the block.
3062 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3063 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003064
3065 // Create the descriptor for the parameter.
3066 llvm::DIVariable debugVar =
3067 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003068 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003069 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003070 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003071 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3072
Adrian Prantlbea407c2013-03-14 21:52:59 +00003073 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003074 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003075 llvm::Instruction *DbgVal =
3076 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003077 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003078 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3079 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003080
Adrian Prantlbea407c2013-03-14 21:52:59 +00003081 // Insert an llvm.dbg.declare into the current block.
3082 llvm::Instruction *DbgDecl =
3083 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3084 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003085}
3086
David Blaikie5434fc22013-08-20 01:28:15 +00003087/// If D is an out-of-class definition of a static data member of a class, find
3088/// its corresponding in-class declaration.
3089llvm::DIDerivedType
3090CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3091 if (!D->isStaticDataMember())
3092 return llvm::DIDerivedType();
3093 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3094 StaticDataMemberCache.find(D->getCanonicalDecl());
3095 if (MI != StaticDataMemberCache.end()) {
3096 assert(MI->second && "Static data member declaration should still exist");
3097 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003098 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003099
3100 // If the member wasn't found in the cache, lazily construct and add it to the
3101 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003102 llvm::DICompositeType Ctxt(
3103 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3104 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie5434fc22013-08-20 01:28:15 +00003105 return T;
3106}
3107
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003108/// Recursively collect all of the member fields of a global anonymous decl and
3109/// create static variables for them. The first time this is called it needs
3110/// to be on a union and then from there we can have additional unnamed fields.
3111llvm::DIGlobalVariable
3112CGDebugInfo::CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit,
3113 unsigned LineNo, StringRef LinkageName,
3114 llvm::GlobalVariable *Var,
3115 llvm::DIDescriptor DContext) {
3116 llvm::DIGlobalVariable GV;
3117
3118 for (const auto *Field : RD->fields()) {
3119 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
3120 StringRef FieldName = Field->getName();
3121
3122 // Ignore unnamed fields, but recurse into anonymous records.
3123 if (FieldName.empty()) {
3124 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3125 if (RT)
3126 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3127 Var, DContext);
3128 continue;
3129 }
3130 // Use VarDecl's Tag, Scope and Line number.
3131 GV = DBuilder.createStaticVariable(DContext, FieldName, LinkageName, Unit,
3132 LineNo, FieldTy,
3133 Var->hasInternalLinkage(), Var,
3134 llvm::DIDerivedType());
3135 }
3136 return GV;
3137}
3138
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003139/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003140void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003141 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003142 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003143 // Create global variable debug descriptor.
3144 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3145 unsigned LineNo = getLineNumber(D->getLocation());
3146
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003147 setLocation(D->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003148
3149 QualType T = D->getType();
3150 if (T->isIncompleteArrayType()) {
3151
3152 // CodeGen turns int[] into int[1] so we'll do the same here.
3153 llvm::APInt ConstVal(32, 1);
3154 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3155
3156 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3157 ArrayType::Normal, 0);
3158 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003159
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003160 StringRef DeclName = D->getName();
3161 StringRef LinkageName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003162 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) &&
3163 !isa<ObjCMethodDecl>(D->getDeclContext()))
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003164 LinkageName = Var->getName();
3165 if (LinkageName == DeclName)
3166 LinkageName = StringRef();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003167
Eric Christopher6537f082013-05-16 00:45:12 +00003168 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003169 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003170
3171 // Attempt to store one global variable for the declaration - even if we
3172 // emit a lot of fields.
3173 llvm::DIGlobalVariable GV;
3174
3175 // If this is an anonymous union then we'll want to emit a global
3176 // variable for each member of the anonymous union so that it's possible
3177 // to find the name of any field in the union.
3178 if (T->isUnionType() && DeclName.empty()) {
3179 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3180 assert(RD->isAnonymousStructOrUnion() && "unnamed non-anonymous struct or union?");
3181 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3182 } else {
3183 GV = DBuilder.createStaticVariable(
3184 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3185 Var->hasInternalLinkage(), Var,
3186 getOrCreateStaticDataMemberDeclarationOrNull(D));
3187 }
David Blaikie9faebd22013-05-20 04:58:53 +00003188 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003189}
3190
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003191/// EmitGlobalVariable - Emit global variable's debug info.
3192void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3193 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003194 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003195 // Create the descriptor for the variable.
3196 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3197 StringRef Name = VD->getName();
3198 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3199 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3200 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3201 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3202 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3203 }
3204 // Do not use DIGlobalVariable for enums.
3205 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3206 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003207 // Do not emit separate definitions for function local const/statics.
3208 if (isa<FunctionDecl>(VD->getDeclContext()))
3209 return;
3210 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3211 auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH()));
3212 if (!pair.second)
3213 return;
3214 llvm::DIDescriptor DContext =
3215 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003216 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003217 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3218 true, Init,
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003219 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003220 pair.first->second = llvm::WeakVH(GV);
David Blaikie9faebd22013-05-20 04:58:53 +00003221}
3222
3223llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3224 if (!LexicalBlockStack.empty())
3225 return llvm::DIScope(LexicalBlockStack.back());
3226 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003227}
3228
David Blaikie957dac52013-04-22 06:13:21 +00003229void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003230 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3231 return;
David Blaikie957dac52013-04-22 06:13:21 +00003232 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003233 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3234 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003235 getLineNumber(UD.getLocation()));
3236}
3237
David Blaikie9faebd22013-05-20 04:58:53 +00003238void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3239 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3240 return;
3241 assert(UD.shadow_size() &&
3242 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3243 // Emitting one decl is sufficient - debuggers can detect that this is an
3244 // overloaded name & provide lookup for all the overloads.
3245 const UsingShadowDecl &USD = **UD.shadow_begin();
Stephen Hines651f13c2014-04-23 16:59:28 -07003246 if (llvm::DIScope Target =
Eric Christopher56b108a2013-06-07 22:54:39 +00003247 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003248 DBuilder.createImportedDeclaration(
3249 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3250 getLineNumber(USD.getLocation()));
3251}
3252
David Blaikiefc46ebc2013-05-20 22:50:41 +00003253llvm::DIImportedEntity
3254CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3255 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003256 return llvm::DIImportedEntity(nullptr);
David Blaikiefc46ebc2013-05-20 22:50:41 +00003257 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3258 if (VH)
3259 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003260 llvm::DIImportedEntity R(nullptr);
David Blaikiefc46ebc2013-05-20 22:50:41 +00003261 if (const NamespaceAliasDecl *Underlying =
3262 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3263 // This could cache & dedup here rather than relying on metadata deduping.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003264 R = DBuilder.createImportedDeclaration(
David Blaikiefc46ebc2013-05-20 22:50:41 +00003265 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3266 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3267 NA.getName());
3268 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003269 R = DBuilder.createImportedDeclaration(
David Blaikiefc46ebc2013-05-20 22:50:41 +00003270 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3271 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3272 getLineNumber(NA.getLocation()), NA.getName());
3273 VH = R;
3274 return R;
3275}
3276
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003277/// getOrCreateNamesSpace - Return namespace descriptor for the given
3278/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003279llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003280CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003281 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003282 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003283 NameSpaceCache.find(NSDecl);
3284 if (I != NameSpaceCache.end())
3285 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003286
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003287 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3288 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003289 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003290 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3291 llvm::DINameSpace NS =
3292 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3293 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3294 return NS;
3295}
3296
3297void CGDebugInfo::finalize() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003298 // Creating types might create further types - invalidating the current
3299 // element and the size(), so don't cache/reference them.
3300 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3301 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3302 E.Decl.replaceAllUsesWith(CGM.getLLVMContext(),
3303 E.Type->getDecl()->getDefinition()
3304 ? CreateTypeDefinition(E.Type, E.Unit)
3305 : E.Decl);
3306 }
Eric Christopher6537f082013-05-16 00:45:12 +00003307
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003308 for (auto p : ReplaceMap) {
3309 assert(p.second);
3310 llvm::DIType Ty(cast<llvm::MDNode>(p.second));
3311 assert(Ty.isForwardDecl());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003312
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003313 auto it = TypeCache.find(p.first);
3314 assert(it != TypeCache.end());
3315 assert(it->second);
3316
3317 llvm::DIType RepTy(cast<llvm::MDNode>(it->second));
3318 Ty.replaceAllUsesWith(CGM.getLLVMContext(), RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003319 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003320
3321 // We keep our own list of retained types, because we need to look
3322 // up the final type in the type cache.
3323 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3324 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Ren18760452013-08-29 20:48:48 +00003325 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003326
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003327 DBuilder.finalize();
3328}