blob: d7321791d861794df1a6c96c480d090869556f37 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
Adrian Prantl0630eb72013-12-18 21:48:18 +000040#include "llvm/Support/Path.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Eric Christopher0a1301f2014-02-26 02:49:36 +000055SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
56 CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000058 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
Adrian Prantl2e0637f2013-07-18 00:28:02 +000061 }
62}
63
Adrian Prantld1b151e2014-01-17 00:15:10 +000064SaveAndRestoreLocation::~SaveAndRestoreLocation() {
65 if (DI)
66 DI->EmitLocation(Builder, SavedLoc);
67}
68
69NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
70 : SaveAndRestoreLocation(CGF, B) {
71 if (DI)
72 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
73}
74
Adrian Prantl2e0637f2013-07-18 00:28:02 +000075NoLocation::~NoLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000076 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000077 assert(Builder.getCurrentDebugLocation().isUnknown());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000078}
79
Adrian Prantlb75016d2013-07-18 01:36:04 +000080ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantld1b151e2014-01-17 00:15:10 +000081 : SaveAndRestoreLocation(CGF, B) {
82 if (DI)
Adrian Prantl49a78562013-07-24 20:34:39 +000083 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Adrian Prantl49a78562013-07-24 20:34:39 +000084}
85
86void ArtificialLocation::Emit() {
87 if (DI) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000088 // Sync the Builder.
89 DI->EmitLocation(Builder, SavedLoc);
90 DI->CurLoc = SourceLocation();
91 // Construct a location that has a valid scope, but no line info.
Adrian Prantl49a78562013-07-24 20:34:39 +000092 assert(!DI->LexicalBlockStack.empty());
93 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000094 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
95 }
96}
97
Adrian Prantlb75016d2013-07-18 01:36:04 +000098ArtificialLocation::~ArtificialLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000099 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000100 assert(Builder.getCurrentDebugLocation().getLine() == 0);
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000101}
102
Guy Benyei11169dd2012-12-18 14:30:41 +0000103void CGDebugInfo::setLocation(SourceLocation Loc) {
104 // If the new location isn't valid return.
Adrian Prantlb1b3bfc2013-07-18 00:27:56 +0000105 if (Loc.isInvalid()) return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000106
107 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
108
109 // If we've changed files in the middle of a lexical scope go ahead
110 // and create a new lexical scope with file node if it's different
111 // from the one in the scope.
112 if (LexicalBlockStack.empty()) return;
113
114 SourceManager &SM = CGM.getContext().getSourceManager();
115 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
116 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
117
118 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
119 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
120 return;
121
122 llvm::MDNode *LB = LexicalBlockStack.back();
123 llvm::DIScope Scope = llvm::DIScope(LB);
124 if (Scope.isLexicalBlockFile()) {
125 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
126 llvm::DIDescriptor D
127 = DBuilder.createLexicalBlockFile(LBF.getScope(),
128 getOrCreateFile(CurLoc));
129 llvm::MDNode *N = D;
130 LexicalBlockStack.pop_back();
131 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +0000132 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000133 llvm::DIDescriptor D
134 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
135 llvm::MDNode *N = D;
136 LexicalBlockStack.pop_back();
137 LexicalBlockStack.push_back(N);
138 }
139}
140
141/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +0000142llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000143 if (!Context)
144 return TheCU;
145
146 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
147 I = RegionMap.find(Context);
148 if (I != RegionMap.end()) {
149 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000150 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 }
152
153 // Check namespace.
154 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000155 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000156
David Blaikiebfa52742013-04-19 06:56:38 +0000157 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
158 if (!RDecl->isDependentType())
159 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000161 return TheCU;
162}
163
164/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramer60509af2013-09-09 14:48:42 +0000165/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei11169dd2012-12-18 14:30:41 +0000166/// is stored on the side.
167StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
168 assert (FD && "Invalid FunctionDecl!");
169 IdentifierInfo *FII = FD->getIdentifier();
170 FunctionTemplateSpecializationInfo *Info
171 = FD->getTemplateSpecializationInfo();
172 if (!Info && FII)
173 return FII->getName();
174
175 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000176 SmallString<128> NS;
177 llvm::raw_svector_ostream OS(NS);
178 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000179
180 // Add any template specialization args.
181 if (Info) {
182 const TemplateArgumentList *TArgs = Info->TemplateArguments;
183 const TemplateArgument *Args = TArgs->data();
184 unsigned NumArgs = TArgs->size();
185 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000186 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
187 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 }
189
190 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000191 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000192}
193
194StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
195 SmallString<256> MethodName;
196 llvm::raw_svector_ostream OS(MethodName);
197 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
198 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000199 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCImplementationDecl>(DC)) {
201 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000202 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCInterfaceDecl>(DC)) {
204 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000205 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 dyn_cast<const ObjCCategoryImplDecl>(DC)){
207 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
208 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000209 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000210 // We can extract the type of the class from the self pointer.
211 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
212 QualType ClassTy =
213 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
214 ClassTy.print(OS, PrintingPolicy(LangOptions()));
215 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 }
217 OS << ' ' << OMD->getSelector().getAsString() << ']';
218
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000219 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000220}
221
222/// getSelectorName - Return selector name. This is used for debugging
223/// info.
224StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000225 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000226}
227
228/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000229StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000230CGDebugInfo::getClassName(const RecordDecl *RD) {
231 const ClassTemplateSpecializationDecl *Spec
232 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
233 if (!Spec)
234 return RD->getName();
235
236 const TemplateArgument *Args;
237 unsigned NumArgs;
238 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
239 const TemplateSpecializationType *TST =
240 cast<TemplateSpecializationType>(TAW->getType());
241 Args = TST->getArgs();
242 NumArgs = TST->getNumArgs();
243 } else {
244 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
245 Args = TemplateArgs.data();
246 NumArgs = TemplateArgs.size();
247 }
248 StringRef Name = RD->getIdentifier()->getName();
249 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000250 SmallString<128> TemplateArgList;
251 {
252 llvm::raw_svector_ostream OS(TemplateArgList);
253 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
254 Policy);
255 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000256
257 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000258 return internString(Name, TemplateArgList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000259}
260
261/// getOrCreateFile - Get the file debug info descriptor for the input location.
262llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
263 if (!Loc.isValid())
264 // If Location is not valid then use main input file.
265 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
266
267 SourceManager &SM = CGM.getContext().getSourceManager();
268 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
269
270 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
271 // If the location is not valid then use main input file.
272 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
273
274 // Cache the results.
275 const char *fname = PLoc.getFilename();
276 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
277 DIFileCache.find(fname);
278
279 if (it != DIFileCache.end()) {
280 // Verify that the information still exists.
281 if (llvm::Value *V = it->second)
282 return llvm::DIFile(cast<llvm::MDNode>(V));
283 }
284
285 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
286
287 DIFileCache[fname] = F;
288 return F;
289}
290
291/// getOrCreateMainFile - Get the file info for main compile unit.
292llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
293 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
294}
295
296/// getLineNumber - Get line number for the location. If location is invalid
297/// then use current location.
298unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
299 if (Loc.isInvalid() && CurLoc.isInvalid())
300 return 0;
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
303 return PLoc.isValid()? PLoc.getLine() : 0;
304}
305
306/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000307unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000309 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 return 0;
311
312 // If the location is invalid then use the current column.
313 if (Loc.isInvalid() && CurLoc.isInvalid())
314 return 0;
315 SourceManager &SM = CGM.getContext().getSourceManager();
316 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
317 return PLoc.isValid()? PLoc.getColumn() : 0;
318}
319
320StringRef CGDebugInfo::getCurrentDirname() {
321 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
322 return CGM.getCodeGenOpts().DebugCompilationDir;
323
324 if (!CWDName.empty())
325 return CWDName;
326 SmallString<256> CWD;
327 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000328 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329}
330
331/// CreateCompileUnit - Create new compile unit.
332void CGDebugInfo::CreateCompileUnit() {
333
334 // Get absolute path name.
335 SourceManager &SM = CGM.getContext().getSourceManager();
336 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
337 if (MainFileName.empty())
338 MainFileName = "<unknown>";
339
340 // The main file name provided via the "-main-file-name" option contains just
341 // the file name itself with no path information. This file name may have had
342 // a relative path, so we look into the actual file entry for the main
343 // file to determine the real absolute path for the file.
344 std::string MainFileDir;
345 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
346 MainFileDir = MainFile->getDir()->getName();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000347 if (MainFileDir != ".") {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000348 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
349 llvm::sys::path::append(MainFileDirSS, MainFileName);
350 MainFileName = MainFileDirSS.str();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000351 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 }
353
354 // Save filename string.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000355 StringRef Filename = internString(MainFileName);
Eric Christopherf1545832013-02-22 23:50:16 +0000356
357 // Save split dwarf file string.
358 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000359 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000360
Guy Benyei11169dd2012-12-18 14:30:41 +0000361 unsigned LangTag;
362 const LangOptions &LO = CGM.getLangOpts();
363 if (LO.CPlusPlus) {
364 if (LO.ObjC1)
365 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
366 else
367 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
368 } else if (LO.ObjC1) {
369 LangTag = llvm::dwarf::DW_LANG_ObjC;
370 } else if (LO.C99) {
371 LangTag = llvm::dwarf::DW_LANG_C99;
372 } else {
373 LangTag = llvm::dwarf::DW_LANG_C89;
374 }
375
376 std::string Producer = getClangFullVersion();
377
378 // Figure out which version of the ObjC runtime we have.
379 unsigned RuntimeVers = 0;
380 if (LO.ObjC1)
381 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
382
383 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 // FIXME - Eliminate TheCU.
Eric Christophere4200a22014-02-27 01:25:08 +0000385 TheCU = DBuilder.createCompileUnit(
386 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
387 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
388 DebugKind == CodeGenOptions::DebugLineTablesOnly
389 ? llvm::DIBuilder::LineTablesOnly
390 : llvm::DIBuilder::FullDebug);
Guy Benyei11169dd2012-12-18 14:30:41 +0000391}
392
393/// CreateType - Get the Basic type from the cache or create a new
394/// one if necessary.
395llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
396 unsigned Encoding = 0;
397 StringRef BTName;
398 switch (BT->getKind()) {
399#define BUILTIN_TYPE(Id, SingletonId)
400#define PLACEHOLDER_TYPE(Id, SingletonId) \
401 case BuiltinType::Id:
402#include "clang/AST/BuiltinTypes.def"
403 case BuiltinType::Dependent:
404 llvm_unreachable("Unexpected builtin type");
405 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000406 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 case BuiltinType::Void:
408 return llvm::DIType();
409 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000410 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000411 return ClassTy;
412 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413 "objc_class", TheCU,
414 getOrCreateMainFile(), 0);
415 return ClassTy;
416 case BuiltinType::ObjCId: {
417 // typedef struct objc_class *Class;
418 // typedef struct objc_object {
419 // Class isa;
420 // } *id;
421
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000422 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000423 return ObjTy;
424
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000425 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000426 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
427 "objc_class", TheCU,
428 getOrCreateMainFile(), 0);
429
430 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000431
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
433
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000434 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000435 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
436 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000437
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000438 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
439 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 return ObjTy;
441 }
442 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000443 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000444 return SelTy;
445 SelTy =
446 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
447 "objc_selector", TheCU, getOrCreateMainFile(),
448 0);
449 return SelTy;
450 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000451
452 case BuiltinType::OCLImage1d:
453 return getOrCreateStructPtrType("opencl_image1d_t",
454 OCLImage1dDITy);
455 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000456 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000457 OCLImage1dArrayDITy);
458 case BuiltinType::OCLImage1dBuffer:
459 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
460 OCLImage1dBufferDITy);
461 case BuiltinType::OCLImage2d:
462 return getOrCreateStructPtrType("opencl_image2d_t",
463 OCLImage2dDITy);
464 case BuiltinType::OCLImage2dArray:
465 return getOrCreateStructPtrType("opencl_image2d_array_t",
466 OCLImage2dArrayDITy);
467 case BuiltinType::OCLImage3d:
468 return getOrCreateStructPtrType("opencl_image3d_t",
469 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000470 case BuiltinType::OCLSampler:
471 return DBuilder.createBasicType("opencl_sampler_t",
472 CGM.getContext().getTypeSize(BT),
473 CGM.getContext().getTypeAlign(BT),
474 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000475 case BuiltinType::OCLEvent:
476 return getOrCreateStructPtrType("opencl_event_t",
477 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000478
Guy Benyei11169dd2012-12-18 14:30:41 +0000479 case BuiltinType::UChar:
480 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
481 case BuiltinType::Char_S:
482 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
483 case BuiltinType::Char16:
484 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
485 case BuiltinType::UShort:
486 case BuiltinType::UInt:
487 case BuiltinType::UInt128:
488 case BuiltinType::ULong:
489 case BuiltinType::WChar_U:
490 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
491 case BuiltinType::Short:
492 case BuiltinType::Int:
493 case BuiltinType::Int128:
494 case BuiltinType::Long:
495 case BuiltinType::WChar_S:
496 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
497 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
498 case BuiltinType::Half:
499 case BuiltinType::Float:
500 case BuiltinType::LongDouble:
501 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
502 }
503
504 switch (BT->getKind()) {
505 case BuiltinType::Long: BTName = "long int"; break;
506 case BuiltinType::LongLong: BTName = "long long int"; break;
507 case BuiltinType::ULong: BTName = "long unsigned int"; break;
508 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
509 default:
510 BTName = BT->getName(CGM.getLangOpts());
511 break;
512 }
513 // Bit size, align and offset of the type.
514 uint64_t Size = CGM.getContext().getTypeSize(BT);
515 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000516 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 DBuilder.createBasicType(BTName, Size, Align, Encoding);
518 return DbgTy;
519}
520
521llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
522 // Bit size, align and offset of the type.
523 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
524 if (Ty->isComplexIntegerType())
525 Encoding = llvm::dwarf::DW_ATE_lo_user;
526
527 uint64_t Size = CGM.getContext().getTypeSize(Ty);
528 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000529 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 DBuilder.createBasicType("complex", Size, Align, Encoding);
531
532 return DbgTy;
533}
534
535/// CreateCVRType - Get the qualified type from the cache or create
536/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000537llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000538 QualifierCollector Qc;
539 const Type *T = Qc.strip(Ty);
540
541 // Ignore these qualifiers for now.
542 Qc.removeObjCGCAttr();
543 Qc.removeAddressSpace();
544 Qc.removeObjCLifetime();
545
546 // We will create one Derived type for one qualifier and recurse to handle any
547 // additional ones.
548 unsigned Tag;
549 if (Qc.hasConst()) {
550 Tag = llvm::dwarf::DW_TAG_const_type;
551 Qc.removeConst();
552 } else if (Qc.hasVolatile()) {
553 Tag = llvm::dwarf::DW_TAG_volatile_type;
554 Qc.removeVolatile();
555 } else if (Qc.hasRestrict()) {
556 Tag = llvm::dwarf::DW_TAG_restrict_type;
557 Qc.removeRestrict();
558 } else {
559 assert(Qc.empty() && "Unknown type qualifier for debug info");
560 return getOrCreateType(QualType(T, 0), Unit);
561 }
562
David Blaikie99dab3b2013-09-04 22:03:57 +0000563 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000564
565 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
566 // CVR derived types.
567 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000568
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 return DbgTy;
570}
571
572llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
573 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000574
575 // The frontend treats 'id' as a typedef to an ObjCObjectType,
576 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
577 // debug info, we want to emit 'id' in both cases.
578 if (Ty->isObjCQualifiedIdType())
579 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000582 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 Ty->getPointeeType(), Unit);
584 return DbgTy;
585}
586
587llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
588 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000589 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 Ty->getPointeeType(), Unit);
591}
592
Manman Rene0064d82013-08-29 23:19:58 +0000593/// In C++ mode, types have linkage, so we can rely on the ODR and
594/// on their mangled names, if they're external.
595static SmallString<256>
596getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
597 llvm::DICompileUnit TheCU) {
598 SmallString<256> FullName;
599 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
600 // For now, only apply ODR with C++.
601 const TagDecl *TD = Ty->getDecl();
602 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
603 !TD->isExternallyVisible())
604 return FullName;
605 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
606 if (CGM.getTarget().getCXXABI().isMicrosoft())
607 return FullName;
608
609 // TODO: This is using the RTTI name. Is there a better way to get
610 // a unique string for a type?
611 llvm::raw_svector_ostream Out(FullName);
612 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
613 Out.flush();
614 return FullName;
615}
616
Guy Benyei11169dd2012-12-18 14:30:41 +0000617// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000618llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000619CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000620 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000621 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000622 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000623 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
625 unsigned Line = getLineNumber(RD->getLocation());
626 StringRef RDName = getClassName(RD);
627
628 unsigned Tag = 0;
629 if (RD->isStruct() || RD->isInterface())
630 Tag = llvm::dwarf::DW_TAG_structure_type;
631 else if (RD->isUnion())
632 Tag = llvm::dwarf::DW_TAG_union_type;
633 else {
634 assert(RD->isClass());
635 Tag = llvm::dwarf::DW_TAG_class_type;
636 }
637
638 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000639 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
640 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
641 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000642}
643
Guy Benyei11169dd2012-12-18 14:30:41 +0000644llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000645 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 QualType PointeeTy,
647 llvm::DIFile Unit) {
648 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
649 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000650 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000651
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 // Bit size, align and offset of the type.
653 // Size is always the size of a pointer. We can't use getTypeSize here
654 // because that does not return the correct value for references.
655 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000656 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
658
David Blaikie99dab3b2013-09-04 22:03:57 +0000659 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
660 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000661}
662
Eric Christopher0fdcb312013-05-16 00:52:20 +0000663llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
664 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000665 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000666 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000667 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
668 TheCU, getOrCreateMainFile(), 0);
669 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
670 Cache = DBuilder.createPointerType(Cache, Size);
671 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000672}
673
Guy Benyei11169dd2012-12-18 14:30:41 +0000674llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
675 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000676 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 return BlockLiteralGeneric;
678
679 SmallVector<llvm::Value *, 8> EltTys;
680 llvm::DIType FieldTy;
681 QualType FType;
682 uint64_t FieldSize, FieldOffset;
683 unsigned FieldAlign;
684 llvm::DIArray Elements;
685 llvm::DIType EltTy, DescTy;
686
687 FieldOffset = 0;
688 FType = CGM.getContext().UnsignedLongTy;
689 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
690 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
691
692 Elements = DBuilder.getOrCreateArray(EltTys);
693 EltTys.clear();
694
695 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
696 unsigned LineNo = getLineNumber(CurLoc);
697
698 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
699 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000700 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Bit size, align and offset of the type.
703 uint64_t Size = CGM.getContext().getTypeSize(Ty);
704
705 DescTy = DBuilder.createPointerType(EltTy, Size);
706
707 FieldOffset = 0;
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
710 FType = CGM.getContext().IntTy;
711 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
712 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
713 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
714 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
715
716 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
717 FieldTy = DescTy;
718 FieldSize = CGM.getContext().getTypeSize(Ty);
719 FieldAlign = CGM.getContext().getTypeAlign(Ty);
720 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
721 LineNo, FieldSize, FieldAlign,
722 FieldOffset, 0, FieldTy);
723 EltTys.push_back(FieldTy);
724
725 FieldOffset += FieldSize;
726 Elements = DBuilder.getOrCreateArray(EltTys);
727
728 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
729 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000730 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
733 return BlockLiteralGeneric;
734}
735
David Blaikie99dab3b2013-09-04 22:03:57 +0000736llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 // Typedefs are derived from some other type. If we have a typedef of a
738 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000739 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000740 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 return llvm::DIType();
742 // We don't set size information, but do specify where the typedef was
743 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000744 SourceLocation Loc = Ty->getDecl()->getLocation();
745 llvm::DIFile File = getOrCreateFile(Loc);
746 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000748
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 llvm::DIDescriptor TypedefContext =
750 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000751
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000753 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000754}
755
756llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
757 llvm::DIFile Unit) {
758 SmallVector<llvm::Value *, 16> EltTys;
759
760 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000761 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000762
763 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000764 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000765 if (isa<FunctionNoProtoType>(Ty))
766 EltTys.push_back(DBuilder.createUnspecifiedParameter());
767 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
769 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000770 if (FPT->isVariadic())
771 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 }
773
774 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
775 return DBuilder.createSubroutineType(Unit, EltTypeArray);
776}
777
778
Guy Benyei11169dd2012-12-18 14:30:41 +0000779llvm::DIType CGDebugInfo::createFieldType(StringRef name,
780 QualType type,
781 uint64_t sizeInBitsOverride,
782 SourceLocation loc,
783 AccessSpecifier AS,
784 uint64_t offsetInBits,
785 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000786 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 llvm::DIType debugType = getOrCreateType(type, tunit);
788
789 // Get the location for the field.
790 llvm::DIFile file = getOrCreateFile(loc);
791 unsigned line = getLineNumber(loc);
792
793 uint64_t sizeInBits = 0;
794 unsigned alignInBits = 0;
795 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000796 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797
798 if (sizeInBitsOverride)
799 sizeInBits = sizeInBitsOverride;
800 }
801
802 unsigned flags = 0;
803 if (AS == clang::AS_private)
804 flags |= llvm::DIDescriptor::FlagPrivate;
805 else if (AS == clang::AS_protected)
806 flags |= llvm::DIDescriptor::FlagProtected;
807
808 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
809 alignInBits, offsetInBits, flags, debugType);
810}
811
Eric Christopher91a31902013-01-16 01:22:32 +0000812/// CollectRecordLambdaFields - Helper for CollectRecordFields.
813void CGDebugInfo::
814CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
815 SmallVectorImpl<llvm::Value *> &elements,
816 llvm::DIType RecordTy) {
817 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
818 // has the name and the location of the variable so we should iterate over
819 // both concurrently.
820 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
821 RecordDecl::field_iterator Field = CXXDecl->field_begin();
822 unsigned fieldno = 0;
823 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
824 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
825 const LambdaExpr::Capture C = *I;
826 if (C.capturesVariable()) {
827 VarDecl *V = C.getCapturedVar();
828 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
829 StringRef VName = V->getName();
830 uint64_t SizeInBitsOverride = 0;
831 if (Field->isBitField()) {
832 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
833 assert(SizeInBitsOverride && "found named 0-width bitfield");
834 }
835 llvm::DIType fieldType
836 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
837 C.getLocation(), Field->getAccess(),
838 layout.getFieldOffset(fieldno), VUnit, RecordTy);
839 elements.push_back(fieldType);
840 } else {
841 // TODO: Need to handle 'this' in some way by probably renaming the
842 // this of the lambda class and having a field member of 'this' or
843 // by using AT_object_pointer for the function and having that be
844 // used as 'this' for semantic references.
845 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
846 FieldDecl *f = *Field;
847 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
848 QualType type = f->getType();
849 llvm::DIType fieldType
850 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
851 layout.getFieldOffset(fieldno), VUnit, RecordTy);
852
853 elements.push_back(fieldType);
854 }
855 }
856}
857
David Blaikie6943dea2013-08-20 01:28:15 +0000858/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000859llvm::DIDerivedType
860CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
861 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000862 // Create the descriptor for the static variable, with or without
863 // constant initializers.
864 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
865 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
866
Eric Christopher91a31902013-01-16 01:22:32 +0000867 unsigned LineNumber = getLineNumber(Var->getLocation());
868 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000869 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000870 if (Var->getInit()) {
871 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000872 if (Value) {
873 if (Value->isInt())
874 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
875 if (Value->isFloat())
876 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
877 }
Eric Christopher91a31902013-01-16 01:22:32 +0000878 }
879
880 unsigned Flags = 0;
881 AccessSpecifier Access = Var->getAccess();
882 if (Access == clang::AS_private)
883 Flags |= llvm::DIDescriptor::FlagPrivate;
884 else if (Access == clang::AS_protected)
885 Flags |= llvm::DIDescriptor::FlagProtected;
886
David Blaikieae019462013-08-15 22:50:29 +0000887 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
888 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000889 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000890 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000891}
892
893/// CollectRecordNormalField - Helper for CollectRecordFields.
894void CGDebugInfo::
895CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
896 llvm::DIFile tunit,
897 SmallVectorImpl<llvm::Value *> &elements,
898 llvm::DIType RecordTy) {
899 StringRef name = field->getName();
900 QualType type = field->getType();
901
902 // Ignore unnamed fields unless they're anonymous structs/unions.
903 if (name.empty() && !type->isRecordType())
904 return;
905
906 uint64_t SizeInBitsOverride = 0;
907 if (field->isBitField()) {
908 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
909 assert(SizeInBitsOverride && "found named 0-width bitfield");
910 }
911
912 llvm::DIType fieldType
913 = createFieldType(name, type, SizeInBitsOverride,
914 field->getLocation(), field->getAccess(),
915 OffsetInBits, tunit, RecordTy);
916
917 elements.push_back(fieldType);
918}
919
Guy Benyei11169dd2012-12-18 14:30:41 +0000920/// CollectRecordFields - A helper function to collect debug info for
921/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000922void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
923 llvm::DIFile tunit,
924 SmallVectorImpl<llvm::Value *> &elements,
925 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
927
Eric Christopher91a31902013-01-16 01:22:32 +0000928 if (CXXDecl && CXXDecl->isLambda())
929 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
930 else {
931 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000932
Eric Christopher91a31902013-01-16 01:22:32 +0000933 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000934 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000935
Eric Christopher91a31902013-01-16 01:22:32 +0000936 // Static and non-static members should appear in the same order as
937 // the corresponding declarations in the source program.
938 for (RecordDecl::decl_iterator I = record->decls_begin(),
939 E = record->decls_end(); I != E; ++I)
David Blaikiece763042013-08-20 21:49:21 +0000940 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
941 // Reuse the existing static member declaration if one exists
942 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
943 StaticDataMemberCache.find(V->getCanonicalDecl());
944 if (MI != StaticDataMemberCache.end()) {
945 assert(MI->second &&
946 "Static data member declaration should still exist");
947 elements.push_back(
948 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
949 } else
950 elements.push_back(CreateRecordStaticField(V, RecordTy));
951 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000952 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
953 tunit, elements, RecordTy);
954
955 // Bump field number for next field.
956 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 }
959}
960
961/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
962/// function type is not updated to include implicit "this" pointer. Use this
963/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000964llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000965CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
966 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000967 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000968 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000969 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000970 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
971 Func, Unit);
972}
David Blaikie2aaf0652013-01-07 22:24:59 +0000973
David Blaikie469f0792013-05-22 23:22:42 +0000974llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000975 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000977 llvm::DIArray Args = llvm::DICompositeType(
978 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 assert (Args.getNumElements() && "Invalid number of arguments!");
980
981 SmallVector<llvm::Value *, 16> Elts;
982
983 // First element is always return type. For 'void' functions it is NULL.
984 Elts.push_back(Args.getElement(0));
985
David Blaikie2aaf0652013-01-07 22:24:59 +0000986 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000987 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000988 if (isa<ClassTemplateSpecializationDecl>(RD)) {
989 // Create pointer type directly in this case.
990 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
991 QualType PointeeTy = ThisPtrTy->getPointeeType();
992 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000993 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000994 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
995 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000996 llvm::DIType ThisPtrType =
997 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000998 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
999 // TODO: This and the artificial type below are misleading, the
1000 // types aren't artificial the argument is, but the current
1001 // metadata doesn't represent that.
1002 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1003 Elts.push_back(ThisPtrType);
1004 } else {
1005 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1007 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1008 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 }
1010
1011 // Copy rest of the arguments.
1012 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1013 Elts.push_back(Args.getElement(i));
1014
1015 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1016
Adrian Prantl0630eb72013-12-18 21:48:18 +00001017 unsigned Flags = 0;
1018 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1019 Flags |= llvm::DIDescriptor::FlagLValueReference;
1020 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1021 Flags |= llvm::DIDescriptor::FlagRValueReference;
1022
1023 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001024}
1025
Eric Christopherb2a008c2013-05-16 00:45:12 +00001026/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001027/// inside a function.
1028static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1029 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1030 return isFunctionLocalClass(NRD);
1031 if (isa<FunctionDecl>(RD->getDeclContext()))
1032 return true;
1033 return false;
1034}
1035
1036/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1037/// a single member function GlobalDecl.
1038llvm::DISubprogram
1039CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1040 llvm::DIFile Unit,
1041 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001042 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001043 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001044
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001046 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001047
1048 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1049 // make sense to give a single ctor/dtor a linkage name.
1050 StringRef MethodLinkageName;
1051 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1052 MethodLinkageName = CGM.getMangledName(Method);
1053
1054 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001055 llvm::DIFile MethodDefUnit;
1056 unsigned MethodLine = 0;
1057 if (!Method->isImplicit()) {
1058 MethodDefUnit = getOrCreateFile(Method->getLocation());
1059 MethodLine = getLineNumber(Method->getLocation());
1060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001061
1062 // Collect virtual method info.
1063 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001064 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001066
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 if (Method->isVirtual()) {
1068 if (Method->isPure())
1069 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1070 else
1071 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001072
Guy Benyei11169dd2012-12-18 14:30:41 +00001073 // It doesn't make sense to give a virtual destructor a vtable index,
1074 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001075 // FIXME: Add proper support for debug info for virtual calls in
1076 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1077 // lookup if we have multiple or virtual inheritance.
1078 if (!isa<CXXDestructorDecl>(Method) &&
1079 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001080 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 ContainingType = RecordTy;
1082 }
1083
1084 unsigned Flags = 0;
1085 if (Method->isImplicit())
1086 Flags |= llvm::DIDescriptor::FlagArtificial;
1087 AccessSpecifier Access = Method->getAccess();
1088 if (Access == clang::AS_private)
1089 Flags |= llvm::DIDescriptor::FlagPrivate;
1090 else if (Access == clang::AS_protected)
1091 Flags |= llvm::DIDescriptor::FlagProtected;
1092 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1093 if (CXXC->isExplicit())
1094 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001095 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 dyn_cast<CXXConversionDecl>(Method)) {
1097 if (CXXC->isExplicit())
1098 Flags |= llvm::DIDescriptor::FlagExplicit;
1099 }
1100 if (Method->hasPrototype())
1101 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001102 if (Method->getRefQualifier() == RQ_LValue)
1103 Flags |= llvm::DIDescriptor::FlagLValueReference;
1104 if (Method->getRefQualifier() == RQ_RValue)
1105 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001106
1107 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1108 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001109 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001111 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 /* isDefinition=*/ false,
1113 Virtuality, VIndex, ContainingType,
1114 Flags, CGM.getLangOpts().Optimize, NULL,
1115 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001116
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1118
1119 return SP;
1120}
1121
1122/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001123/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001124/// a Record.
1125void CGDebugInfo::
1126CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1127 SmallVectorImpl<llvm::Value *> &EltTys,
1128 llvm::DIType RecordTy) {
1129
1130 // Since we want more than just the individual member decls if we
1131 // have templated functions iterate over every declaration to gather
1132 // the functions.
1133 for(DeclContext::decl_iterator I = RD->decls_begin(),
1134 E = RD->decls_end(); I != E; ++I) {
David Blaikiefae219a2013-08-28 17:27:13 +00001135 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001136 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001137 // It may be associated with the declaration of the type & should be
1138 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001139 //
1140 // This situation can arise in the vtable-based debug info reduction where
1141 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001142 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1143 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001144 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001145 // If the member is implicit, lazily create it when we see the
1146 // definition, not before. (an ODR-used implicit default ctor that's
1147 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001148 if (!Method->isImplicit())
1149 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1150 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001151 EltTys.push_back(MI->second);
Eric Christopherf86c4052013-08-28 23:12:10 +00001152 } else if (const FunctionTemplateDecl *FTD =
1153 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001154 // Add any template specializations that have already been seen. Like
1155 // implicit member functions, these may have been added to a declaration
1156 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001157 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1158 SE = FTD->spec_end();
1159 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001160 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1161 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1162 if (MI != SPCache.end())
1163 EltTys.push_back(MI->second);
1164 }
David Blaikie6943dea2013-08-20 01:28:15 +00001165 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001167}
Guy Benyei11169dd2012-12-18 14:30:41 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001170/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001171/// a Record.
1172void CGDebugInfo::
1173CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1174 SmallVectorImpl<llvm::Value *> &EltTys,
1175 llvm::DIType RecordTy) {
1176
1177 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1178 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1179 BE = RD->bases_end(); BI != BE; ++BI) {
1180 unsigned BFlags = 0;
1181 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 const CXXRecordDecl *Base =
1184 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001185
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 if (BI->isVirtual()) {
1187 // virtual base offset offset is -ve. The code generator emits dwarf
1188 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001189 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001190 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1192 BFlags = llvm::DIDescriptor::FlagVirtual;
1193 } else
1194 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1195 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1196 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001197
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 AccessSpecifier Access = BI->getAccessSpecifier();
1199 if (Access == clang::AS_private)
1200 BFlags |= llvm::DIDescriptor::FlagPrivate;
1201 else if (Access == clang::AS_protected)
1202 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001203
1204 llvm::DIType DTy =
1205 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 getOrCreateType(BI->getType(), Unit),
1207 BaseOffset, BFlags);
1208 EltTys.push_back(DTy);
1209 }
1210}
1211
1212/// CollectTemplateParams - A helper function to collect template parameters.
1213llvm::DIArray CGDebugInfo::
1214CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001215 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001217 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1219 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001220 StringRef Name;
1221 if (TPList)
1222 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001223 switch (TA.getKind()) {
1224 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001225 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1226 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001227 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001229 } break;
1230 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1232 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001233 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001234 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001235 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1236 TemplateParams.push_back(TVP);
1237 } break;
1238 case TemplateArgument::Declaration: {
1239 const ValueDecl *D = TA.getAsDecl();
1240 bool InstanceMember = D->isCXXInstanceMember();
1241 QualType T = InstanceMember
1242 ? CGM.getContext().getMemberPointerType(
1243 D->getType(), cast<RecordDecl>(D->getDeclContext())
1244 ->getTypeForDecl())
1245 : CGM.getContext().getPointerType(D->getType());
1246 llvm::DIType TTy = getOrCreateType(T, Unit);
1247 llvm::Value *V = 0;
1248 // Variable pointer template parameters have a value that is the address
1249 // of the variable.
1250 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1251 V = CGM.GetAddrOfGlobalVar(VD);
1252 // Member function pointers have special support for building them, though
1253 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001254 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001255 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1256 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001257 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1258 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001259 // Member data pointers have special handling too to compute the fixed
1260 // offset within the object.
1261 if (isa<FieldDecl>(D)) {
1262 // These five lines (& possibly the above member function pointer
1263 // handling) might be able to be refactored to use similar code in
1264 // CodeGenModule::getMemberPointerConstant
1265 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1266 CharUnits chars =
1267 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1268 V = CGM.getCXXABI().EmitMemberDataPointer(
1269 cast<MemberPointerType>(T.getTypePtr()), chars);
1270 }
1271 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001272 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1273 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001274 TemplateParams.push_back(TVP);
1275 } break;
1276 case TemplateArgument::NullPtr: {
1277 QualType T = TA.getNullPtrType();
1278 llvm::DIType TTy = getOrCreateType(T, Unit);
1279 llvm::Value *V = 0;
1280 // Special case member data pointer null values since they're actually -1
1281 // instead of zero.
1282 if (const MemberPointerType *MPT =
1283 dyn_cast<MemberPointerType>(T.getTypePtr()))
1284 // But treat member function pointers as simple zero integers because
1285 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1286 // CodeGen grows handling for values of non-null member function
1287 // pointers then perhaps we could remove this special case and rely on
1288 // EmitNullMemberPointer for member function pointers.
1289 if (MPT->isMemberDataPointer())
1290 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1291 if (!V)
1292 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1293 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001294 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001295 TemplateParams.push_back(TVP);
1296 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001297 case TemplateArgument::Template: {
1298 llvm::DITemplateValueParameter TVP =
1299 DBuilder.createTemplateTemplateParameter(
1300 TheCU, Name, llvm::DIType(),
1301 TA.getAsTemplate().getAsTemplateDecl()
1302 ->getQualifiedNameAsString());
1303 TemplateParams.push_back(TVP);
1304 } break;
1305 case TemplateArgument::Pack: {
1306 llvm::DITemplateValueParameter TVP =
1307 DBuilder.createTemplateParameterPack(
1308 TheCU, Name, llvm::DIType(),
1309 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1310 TemplateParams.push_back(TVP);
1311 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001312 case TemplateArgument::Expression: {
1313 const Expr *E = TA.getAsExpr();
1314 QualType T = E->getType();
1315 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1316 assert(V && "Expression in template argument isn't constant");
1317 llvm::DIType TTy = getOrCreateType(T, Unit);
1318 llvm::DITemplateValueParameter TVP =
1319 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1320 V->stripPointerCasts());
1321 TemplateParams.push_back(TVP);
1322 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001323 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001324 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001325 case TemplateArgument::Null:
1326 llvm_unreachable(
1327 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 }
1329 }
1330 return DBuilder.getOrCreateArray(TemplateParams);
1331}
1332
1333/// CollectFunctionTemplateParams - A helper function to collect debug
1334/// info for function template parameters.
1335llvm::DIArray CGDebugInfo::
1336CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1337 if (FD->getTemplatedKind() ==
1338 FunctionDecl::TK_FunctionTemplateSpecialization) {
1339 const TemplateParameterList *TList =
1340 FD->getTemplateSpecializationInfo()->getTemplate()
1341 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001342 return CollectTemplateParams(
1343 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 }
1345 return llvm::DIArray();
1346}
1347
1348/// CollectCXXTemplateParams - A helper function to collect debug info for
1349/// template parameters.
1350llvm::DIArray CGDebugInfo::
1351CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1352 llvm::DIFile Unit) {
1353 llvm::PointerUnion<ClassTemplateDecl *,
1354 ClassTemplatePartialSpecializationDecl *>
1355 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001356
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1358 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1359 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1360 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001361 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001362}
1363
1364/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1365llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1366 if (VTablePtrType.isValid())
1367 return VTablePtrType;
1368
1369 ASTContext &Context = CGM.getContext();
1370
1371 /* Function type */
1372 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1373 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1374 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1375 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1376 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1377 "__vtbl_ptr_type");
1378 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1379 return VTablePtrType;
1380}
1381
1382/// getVTableName - Get vtable name for the given Class.
1383StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001384 // Copy the gdb compatible name on the side and use its reference.
1385 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001386}
1387
1388
1389/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1390/// debug info entry in EltTys vector.
1391void CGDebugInfo::
1392CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1393 SmallVectorImpl<llvm::Value *> &EltTys) {
1394 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1395
1396 // If there is a primary base then it will hold vtable info.
1397 if (RL.getPrimaryBase())
1398 return;
1399
1400 // If this class is not dynamic then there is not any vtable info to collect.
1401 if (!RD->isDynamicClass())
1402 return;
1403
1404 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1405 llvm::DIType VPTR
1406 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001407 0, Size, 0, 0,
1408 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 getOrCreateVTablePtrType(Unit));
1410 EltTys.push_back(VPTR);
1411}
1412
Eric Christopherb2a008c2013-05-16 00:45:12 +00001413/// getOrCreateRecordType - Emit record type's standalone debug info.
1414llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001416 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1418 return T;
1419}
1420
1421/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1422/// debug info.
1423llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001424 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001425 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001427 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 return T;
1429}
1430
David Blaikieb2e86eb2013-08-15 20:49:17 +00001431void CGDebugInfo::completeType(const RecordDecl *RD) {
1432 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1433 !CGM.getLangOpts().CPlusPlus)
1434 completeRequiredType(RD);
1435}
1436
1437void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie6943dea2013-08-20 01:28:15 +00001438 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1439 if (CXXDecl->isDynamicClass())
1440 return;
1441
David Blaikieb2e86eb2013-08-15 20:49:17 +00001442 QualType Ty = CGM.getContext().getRecordType(RD);
1443 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001444 if (T && T.isForwardDecl())
1445 completeClassData(RD);
1446}
1447
1448void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1449 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001450 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001451 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001452 void* TyPtr = Ty.getAsOpaquePtr();
1453 if (CompletedTypeCache.count(TyPtr))
1454 return;
1455 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1456 assert(!Res.isForwardDecl());
1457 CompletedTypeCache[TyPtr] = Res;
1458 TypeCache[TyPtr] = Res;
1459}
1460
Guy Benyei11169dd2012-12-18 14:30:41 +00001461/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001462llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 RecordDecl *RD = Ty->getDecl();
David Blaikie6943dea2013-08-20 01:28:15 +00001464 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie99dab3b2013-09-04 22:03:57 +00001465 // Always emit declarations for types that aren't required to be complete when
1466 // in limit-debug-info mode. If the type is later found to be required to be
1467 // complete this declaration will be upgraded to a definition by
1468 // `completeRequiredType`.
1469 // If the type is dynamic, only emit the definition in TUs that require class
1470 // data. This is handled by `completeClassData`.
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001471 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1472 // If we've already emitted the type, just use that, even if it's only a
1473 // declaration. The completeType, completeRequiredType, and completeClassData
1474 // callbacks will handle promoting the declaration to a definition.
1475 if (T ||
Adrian Prantld09906f2014-01-07 02:40:59 +00001476 // Under -fno-standalone-debug:
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001477 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
Adrian Prantla7634472014-01-07 01:19:08 +00001478 // Emit only a forward declaration unless the type is required.
1479 ((!RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
Eric Christopher0a1301f2014-02-26 02:49:36 +00001480 // If the class is dynamic, only emit a declaration. A definition will
1481 // be emitted whenever the vtable is emitted.
Adrian Prantla7634472014-01-07 01:19:08 +00001482 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())))) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001483 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001484 T = getOrCreateRecordFwdDecl(
1485 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001486 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001487 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001488
David Blaikieb2e86eb2013-08-15 20:49:17 +00001489 return CreateTypeDefinition(Ty);
1490}
1491
1492llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1493 RecordDecl *RD = Ty->getDecl();
1494
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 // Get overall information about the record type for the debug info.
1496 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1497
1498 // Records and classes and unions can all be recursive. To handle them, we
1499 // first generate a debug descriptor for the struct as a forward declaration.
1500 // Then (if it is a definition) we go through and get debug info for all of
1501 // its members. Finally, we create a descriptor for the complete type (which
1502 // may refer to the forward decl if the struct is recursive) and replace all
1503 // uses of the forward declaration with the final definition.
1504
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001505 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001506 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001507 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001508
1509 if (FwdDecl.isForwardDecl())
1510 return FwdDecl;
1511
David Blaikieadfbf992013-08-18 16:55:33 +00001512 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1513 CollectContainingType(CXXDecl, FwdDecl);
1514
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001516 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1518
Adrian Prantla03a85a2013-03-06 22:03:30 +00001519 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1521
1522 // Convert all the elements.
1523 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001524 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001525
1526 // Note: The split of CXXDecl information here is intentional, the
1527 // gdb tests will depend on a certain ordering at printout. The debug
1528 // information offsets are still correct if we merge them all together
1529 // though.
1530 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1531 if (CXXDecl) {
1532 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1533 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1534 }
1535
Eric Christopher91a31902013-01-16 01:22:32 +00001536 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001538 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001540
1541 LexicalBlockStack.pop_back();
1542 RegionMap.erase(Ty->getDecl());
1543
1544 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001545 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001546
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001547 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1548 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001549}
1550
1551/// CreateType - get objective-c object type.
1552llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1553 llvm::DIFile Unit) {
1554 // Ignore protocols.
1555 return getOrCreateType(Ty->getBaseType(), Unit);
1556}
1557
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001558
1559/// \return true if Getter has the default name for the property PD.
1560static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1561 const ObjCMethodDecl *Getter) {
1562 assert(PD);
1563 if (!Getter)
1564 return true;
1565
1566 assert(Getter->getDeclName().isObjCZeroArgSelector());
1567 return PD->getName() ==
1568 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1569}
1570
1571/// \return true if Setter has the default name for the property PD.
1572static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1573 const ObjCMethodDecl *Setter) {
1574 assert(PD);
1575 if (!Setter)
1576 return true;
1577
1578 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001579 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001580 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1581}
1582
Guy Benyei11169dd2012-12-18 14:30:41 +00001583/// CreateType - get objective-c interface type.
1584llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1585 llvm::DIFile Unit) {
1586 ObjCInterfaceDecl *ID = Ty->getDecl();
1587 if (!ID)
1588 return llvm::DIType();
1589
1590 // Get overall information about the record type for the debug info.
1591 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1592 unsigned Line = getLineNumber(ID->getLocation());
1593 unsigned RuntimeLang = TheCU.getLanguage();
1594
1595 // If this is just a forward declaration return a special forward-declaration
1596 // debug type since we won't be able to lay out the entire type.
1597 ObjCInterfaceDecl *Def = ID->getDefinition();
1598 if (!Def) {
1599 llvm::DIType FwdDecl =
1600 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001601 ID->getName(), TheCU, DefUnit, Line,
1602 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 return FwdDecl;
1604 }
1605
1606 ID = Def;
1607
1608 // Bit size, align and offset of the type.
1609 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1610 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1611
1612 unsigned Flags = 0;
1613 if (ID->getImplementation())
1614 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1615
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001616 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001617 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1618 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001619 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001620
1621 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1622 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001623 QualType QualTy = QualType(Ty, 0);
1624 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001625
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001626 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001627 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1629
1630 // Convert all the elements.
1631 SmallVector<llvm::Value *, 16> EltTys;
1632
1633 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1634 if (SClass) {
1635 llvm::DIType SClassTy =
1636 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1637 if (!SClassTy.isValid())
1638 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001639
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 llvm::DIType InhTag =
1641 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1642 EltTys.push_back(InhTag);
1643 }
1644
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001645 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1647 E = ID->prop_end(); I != E; ++I) {
1648 const ObjCPropertyDecl *PD = *I;
1649 SourceLocation Loc = PD->getLocation();
1650 llvm::DIFile PUnit = getOrCreateFile(Loc);
1651 unsigned PLine = getLineNumber(Loc);
1652 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1653 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1654 llvm::MDNode *PropertyNode =
1655 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001656 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001657 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001659 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 getSelectorName(PD->getSetterName()),
1661 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001662 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 EltTys.push_back(PropertyNode);
1664 }
1665
1666 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1667 unsigned FieldNo = 0;
1668 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1669 Field = Field->getNextIvar(), ++FieldNo) {
1670 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1671 if (!FieldTy.isValid())
1672 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001673
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 StringRef FieldName = Field->getName();
1675
1676 // Ignore unnamed fields.
1677 if (FieldName.empty())
1678 continue;
1679
1680 // Get the location for the field.
1681 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1682 unsigned FieldLine = getLineNumber(Field->getLocation());
1683 QualType FType = Field->getType();
1684 uint64_t FieldSize = 0;
1685 unsigned FieldAlign = 0;
1686
1687 if (!FType->isIncompleteArrayType()) {
1688
1689 // Bit size, align and offset of the type.
1690 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001691 ? Field->getBitWidthValue(CGM.getContext())
1692 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 FieldAlign = CGM.getContext().getTypeAlign(FType);
1694 }
1695
1696 uint64_t FieldOffset;
1697 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1698 // We don't know the runtime offset of an ivar if we're using the
1699 // non-fragile ABI. For bitfields, use the bit offset into the first
1700 // byte of storage of the bitfield. For other fields, use zero.
1701 if (Field->isBitField()) {
1702 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1703 CGM, ID, Field);
1704 FieldOffset %= CGM.getContext().getCharWidth();
1705 } else {
1706 FieldOffset = 0;
1707 }
1708 } else {
1709 FieldOffset = RL.getFieldOffset(FieldNo);
1710 }
1711
1712 unsigned Flags = 0;
1713 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1714 Flags = llvm::DIDescriptor::FlagProtected;
1715 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1716 Flags = llvm::DIDescriptor::FlagPrivate;
1717
1718 llvm::MDNode *PropertyNode = NULL;
1719 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001720 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1722 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001723 SourceLocation Loc = PD->getLocation();
1724 llvm::DIFile PUnit = getOrCreateFile(Loc);
1725 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001726 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1727 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1728 PropertyNode =
1729 DBuilder.createObjCProperty(PD->getName(),
1730 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001731 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001733 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 getSelectorName(PD->getSetterName()),
1735 PD->getPropertyAttributes(),
1736 getOrCreateType(PD->getType(), PUnit));
1737 }
1738 }
1739 }
1740 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1741 FieldLine, FieldSize, FieldAlign,
1742 FieldOffset, Flags, FieldTy,
1743 PropertyNode);
1744 EltTys.push_back(FieldTy);
1745 }
1746
1747 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001748 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001749
1750 // If the implementation is not yet set, we do not want to mark it
1751 // as complete. An implementation may declare additional
1752 // private ivars that we would miss otherwise.
1753 if (ID->getImplementation() == 0)
1754 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001755
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001757 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001758}
1759
1760llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1761 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1762 int64_t Count = Ty->getNumElements();
1763 if (Count == 0)
1764 // If number of elements are not known then this is an unbounded array.
1765 // Use Count == -1 to express such arrays.
1766 Count = -1;
1767
1768 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1769 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1770
1771 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1772 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1773
1774 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1775}
1776
1777llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1778 llvm::DIFile Unit) {
1779 uint64_t Size;
1780 uint64_t Align;
1781
1782 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1783 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1784 Size = 0;
1785 Align =
1786 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1787 } else if (Ty->isIncompleteArrayType()) {
1788 Size = 0;
1789 if (Ty->getElementType()->isIncompleteType())
1790 Align = 0;
1791 else
1792 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001793 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 Size = 0;
1795 Align = 0;
1796 } else {
1797 // Size and align of the whole array, not the element type.
1798 Size = CGM.getContext().getTypeSize(Ty);
1799 Align = CGM.getContext().getTypeAlign(Ty);
1800 }
1801
1802 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1803 // interior arrays, do we care? Why aren't nested arrays represented the
1804 // obvious/recursive way?
1805 SmallVector<llvm::Value *, 8> Subscripts;
1806 QualType EltTy(Ty, 0);
1807 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1808 // If the number of elements is known, then count is that number. Otherwise,
1809 // it's -1. This allows us to represent a subrange with an array of 0
1810 // elements, like this:
1811 //
1812 // struct foo {
1813 // int x[0];
1814 // };
1815 int64_t Count = -1; // Count == -1 is an unbounded array.
1816 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1817 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001818
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 // FIXME: Verify this is right for VLAs.
1820 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1821 EltTy = Ty->getElementType();
1822 }
1823
1824 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1825
Eric Christopherb2a008c2013-05-16 00:45:12 +00001826 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1828 SubscriptArray);
1829 return DbgTy;
1830}
1831
Eric Christopherb2a008c2013-05-16 00:45:12 +00001832llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001834 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 Ty, Ty->getPointeeType(), Unit);
1836}
1837
Eric Christopherb2a008c2013-05-16 00:45:12 +00001838llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001839 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001840 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 Ty, Ty->getPointeeType(), Unit);
1842}
1843
Eric Christopherb2a008c2013-05-16 00:45:12 +00001844llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001846 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1847 if (!Ty->getPointeeType()->isFunctionType())
1848 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001849 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001850
1851 const FunctionProtoType *FPT =
1852 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001853 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001854 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1855 FPT->getTypeQuals())),
1856 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001857}
1858
Eric Christopherb2a008c2013-05-16 00:45:12 +00001859llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 llvm::DIFile U) {
1861 // Ignore the atomic wrapping
1862 // FIXME: What is the correct representation?
1863 return getOrCreateType(Ty->getValueType(), U);
1864}
1865
1866/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001867llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001868 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001869 uint64_t Size = 0;
1870 uint64_t Align = 0;
1871 if (!ED->getTypeForDecl()->isIncompleteType()) {
1872 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1873 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1874 }
1875
Manman Rene0064d82013-08-29 23:19:58 +00001876 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1877
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 // If this is just a forward declaration, construct an appropriately
1879 // marked node and just return it.
1880 if (!ED->getDefinition()) {
1881 llvm::DIDescriptor EDContext;
1882 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1883 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1884 unsigned Line = getLineNumber(ED->getLocation());
1885 StringRef EDName = ED->getName();
1886 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1887 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001888 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 }
1890
1891 // Create DIEnumerator elements for each enumerator.
1892 SmallVector<llvm::Value *, 16> Enumerators;
1893 ED = ED->getDefinition();
1894 for (EnumDecl::enumerator_iterator
1895 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1896 Enum != EnumEnd; ++Enum) {
1897 Enumerators.push_back(
1898 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001899 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 }
1901
1902 // Return a CompositeType for the enum itself.
1903 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1904
1905 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1906 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001907 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001909 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001911 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1913 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001914 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 return DbgTy;
1916}
1917
David Blaikie05491062013-01-21 04:37:12 +00001918static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1919 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001920 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001921 Qualifiers InnerQuals = T.getLocalQualifiers();
1922 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1923 // that is already there.
1924 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1925 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 QualType LastT = T;
1927 switch (T->getTypeClass()) {
1928 default:
David Blaikie05491062013-01-21 04:37:12 +00001929 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 case Type::TemplateSpecialization:
1931 T = cast<TemplateSpecializationType>(T)->desugar();
1932 break;
1933 case Type::TypeOfExpr:
1934 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1935 break;
1936 case Type::TypeOf:
1937 T = cast<TypeOfType>(T)->getUnderlyingType();
1938 break;
1939 case Type::Decltype:
1940 T = cast<DecltypeType>(T)->getUnderlyingType();
1941 break;
1942 case Type::UnaryTransform:
1943 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1944 break;
1945 case Type::Attributed:
1946 T = cast<AttributedType>(T)->getEquivalentType();
1947 break;
1948 case Type::Elaborated:
1949 T = cast<ElaboratedType>(T)->getNamedType();
1950 break;
1951 case Type::Paren:
1952 T = cast<ParenType>(T)->getInnerType();
1953 break;
David Blaikie05491062013-01-21 04:37:12 +00001954 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001955 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 break;
1957 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001958 QualType DT = cast<AutoType>(T)->getDeducedType();
1959 if (DT.isNull())
1960 return T;
1961 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001962 break;
1963 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001964
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001966 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001967 } while (true);
1968}
1969
Eric Christopher0fdcb312013-05-16 00:52:20 +00001970/// getType - Get the type from the cache or return null type if it doesn't
1971/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001972llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1973
1974 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001975 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001976
Guy Benyei11169dd2012-12-18 14:30:41 +00001977 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001978 if (Ty->getTypeClass() == Type::ObjCInterface) {
1979 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1980 if (V)
1981 return llvm::DIType(cast<llvm::MDNode>(V));
1982 else return llvm::DIType();
1983 }
1984
Guy Benyei11169dd2012-12-18 14:30:41 +00001985 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1986 TypeCache.find(Ty.getAsOpaquePtr());
1987 if (it != TypeCache.end()) {
1988 // Verify that the debug info still exists.
1989 if (llvm::Value *V = it->second)
1990 return llvm::DIType(cast<llvm::MDNode>(V));
1991 }
1992
1993 return llvm::DIType();
1994}
1995
1996/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1997/// doesn't exist.
1998llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1999
2000 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002001 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002002
2003 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002004 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2006 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002007 if (it != CompletedTypeCache.end())
2008 V = it->second;
2009 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002010 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002011 }
2012
Adrian Prantla03a85a2013-03-06 22:03:30 +00002013 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002014 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002015}
2016
Adrian Prantl73409ce2013-03-11 18:33:46 +00002017/// getCachedInterfaceTypeOrNull - Get the type from the interface
2018/// cache, unless it needs to regenerated. Otherwise return null.
2019llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2020 // Is there a cached interface that hasn't changed?
2021 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2022 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2023
2024 if (it1 != ObjCInterfaceCache.end())
2025 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2026 if (Checksum(Decl) == it1->second.second)
2027 // Return cached forward declaration.
2028 return it1->second.first;
2029
2030 return 0;
2031}
Guy Benyei11169dd2012-12-18 14:30:41 +00002032
2033/// getOrCreateType - Get the type from the cache or create a new
2034/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002035llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 if (Ty.isNull())
2037 return llvm::DIType();
2038
2039 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002040 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002041
David Blaikie99dab3b2013-09-04 22:03:57 +00002042 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 return T;
2044
2045 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002046 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002047 void* TyPtr = Ty.getAsOpaquePtr();
2048
2049 // And update the type cache.
2050 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002051
David Blaikie6a723442013-08-15 21:21:19 +00002052 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2053 // into the cache - but getTypeOrNull has a special case for cached interface
2054 // types. We should probably just pull that out as a special case for the
2055 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002056 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002057 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002058 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2059 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2060 // Interface types may have elements added to them by a
2061 // subsequent implementation or extension, so we keep them in
2062 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002063 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002064 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002065 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2066 if (V.first)
2067 return llvm::DIType(cast<llvm::MDNode>(V.first));
2068 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2069 Decl->getName(), TheCU, Unit,
2070 getLineNumber(Decl->getLocation()),
2071 TheCU.getLanguage());
2072 // Store the forward declaration in the cache.
2073 V.first = TC;
2074 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002075
David Blaikie8e5939b2013-05-21 18:29:40 +00002076 // Register the type for replacement in finalize().
2077 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2078
Adrian Prantl73409ce2013-03-11 18:33:46 +00002079 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002080 }
2081
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002083 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002084
2085 return Res;
2086}
2087
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002088/// Currently the checksum of an interface includes the number of
2089/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002090unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002091 // The assumption is that the number of ivars can only increase
2092 // monotonically, so it is safe to just use their current number as
2093 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002094 unsigned Sum = 0;
2095 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2096 Ivar != 0; Ivar = Ivar->getNextIvar())
2097 ++Sum;
2098
2099 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002100}
2101
2102ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2103 switch (Ty->getTypeClass()) {
2104 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002105 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2106 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002107 case Type::ObjCInterface:
2108 return cast<ObjCInterfaceType>(Ty)->getDecl();
2109 default:
2110 return 0;
2111 }
2112}
2113
Guy Benyei11169dd2012-12-18 14:30:41 +00002114/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002115llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 // Handle qualifiers, which recursively handles what they refer to.
2117 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002118 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002119
2120 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002121
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 // Work out details of type.
2123 switch (Ty->getTypeClass()) {
2124#define TYPE(Class, Base)
2125#define ABSTRACT_TYPE(Class, Base)
2126#define NON_CANONICAL_TYPE(Class, Base)
2127#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2128#include "clang/AST/TypeNodes.def"
2129 llvm_unreachable("Dependent types cannot show up in debug information");
2130
2131 case Type::ExtVector:
2132 case Type::Vector:
2133 return CreateType(cast<VectorType>(Ty), Unit);
2134 case Type::ObjCObjectPointer:
2135 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2136 case Type::ObjCObject:
2137 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2138 case Type::ObjCInterface:
2139 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2140 case Type::Builtin:
2141 return CreateType(cast<BuiltinType>(Ty));
2142 case Type::Complex:
2143 return CreateType(cast<ComplexType>(Ty));
2144 case Type::Pointer:
2145 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002146 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002147 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002148 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002149 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002150 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 case Type::BlockPointer:
2152 return CreateType(cast<BlockPointerType>(Ty), Unit);
2153 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002154 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002156 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002157 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002158 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 case Type::FunctionProto:
2160 case Type::FunctionNoProto:
2161 return CreateType(cast<FunctionType>(Ty), Unit);
2162 case Type::ConstantArray:
2163 case Type::VariableArray:
2164 case Type::IncompleteArray:
2165 return CreateType(cast<ArrayType>(Ty), Unit);
2166
2167 case Type::LValueReference:
2168 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2169 case Type::RValueReference:
2170 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2171
2172 case Type::MemberPointer:
2173 return CreateType(cast<MemberPointerType>(Ty), Unit);
2174
2175 case Type::Atomic:
2176 return CreateType(cast<AtomicType>(Ty), Unit);
2177
2178 case Type::Attributed:
2179 case Type::TemplateSpecialization:
2180 case Type::Elaborated:
2181 case Type::Paren:
2182 case Type::SubstTemplateTypeParm:
2183 case Type::TypeOfExpr:
2184 case Type::TypeOf:
2185 case Type::Decltype:
2186 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002187 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002188 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002189 case Type::Auto:
2190 Diag = "auto";
2191 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002193
Guy Benyei11169dd2012-12-18 14:30:41 +00002194 assert(Diag && "Fall through without a diagnostic?");
2195 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2196 "debug information for %0 is not yet supported");
2197 CGM.getDiags().Report(DiagID)
2198 << Diag;
2199 return llvm::DIType();
2200}
2201
2202/// getOrCreateLimitedType - Get the type from the cache or create a new
2203/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002204llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002205 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002206 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002207
David Blaikie8d5e1282013-08-20 21:03:29 +00002208 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002209
2210 // We may have cached a forward decl when we could have created
2211 // a non-forward decl. Go ahead and create a non-forward decl
2212 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002213 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002214
2215 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002216 llvm::DICompositeType Res = CreateLimitedType(Ty);
2217
2218 // Propagate members from the declaration to the definition
2219 // CreateType(const RecordType*) will overwrite this with the members in the
2220 // correct order if the full type is needed.
2221 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002222
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002223 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002224 ReplaceMap.push_back(
2225 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002226
2227 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002228 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 return Res;
2230}
2231
2232// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002233llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002235
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 // Get overall information about the record type for the debug info.
2237 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2238 unsigned Line = getLineNumber(RD->getLocation());
2239 StringRef RDName = getClassName(RD);
2240
Eric Christopher07429ff2013-10-15 21:22:34 +00002241 llvm::DIDescriptor RDContext =
2242 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002243
David Blaikied2785892013-08-18 17:36:19 +00002244 // If we ended up creating the type during the context chain construction,
2245 // just return that.
2246 // FIXME: this could be dealt with better if the type was recorded as
2247 // completed before we started this (see the CompletedTypeCache usage in
2248 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2249 // be pushed to before context creation, but after it was known to be
2250 // destined for completion (might still have an issue if this caller only
2251 // required a declaration but the context construction ended up creating a
2252 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002253 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2254 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002255 return T;
2256
Adrian Prantl381e7552014-02-04 21:29:50 +00002257 // If this is just a forward or incomplete declaration, construct an
2258 // appropriately marked node and just return it.
2259 const RecordDecl *D = RD->getDefinition();
2260 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002261 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002262
2263 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2264 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002265 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002266
Manman Rene0064d82013-08-29 23:19:58 +00002267 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2268
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 if (RD->isUnion())
2270 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002271 Size, Align, 0, llvm::DIArray(), 0,
2272 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 else if (RD->isClass()) {
2274 // FIXME: This could be a struct type giving a default visibility different
2275 // than C++ class type, but needs llvm metadata changes first.
2276 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002277 Size, Align, 0, 0, llvm::DIType(),
2278 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002279 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 } else
2281 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002282 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002283 llvm::DIArray(), 0, llvm::DIType(),
2284 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002285
2286 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002287 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002288
David Blaikieadfbf992013-08-18 16:55:33 +00002289 if (const ClassTemplateSpecializationDecl *TSpecial =
2290 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2291 RealDecl.setTypeArray(llvm::DIArray(),
2292 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002293 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002294}
2295
David Blaikieadfbf992013-08-18 16:55:33 +00002296void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2297 llvm::DICompositeType RealDecl) {
2298 // A class's primary base or the class itself contains the vtable.
2299 llvm::DICompositeType ContainingType;
2300 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2301 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002302 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002303 while (1) {
2304 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2305 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2306 if (PBT && !BRL.isPrimaryBaseVirtual())
2307 PBase = PBT;
2308 else
2309 break;
2310 }
2311 ContainingType = llvm::DICompositeType(
2312 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2313 getOrCreateFile(RD->getLocation())));
2314 } else if (RD->isDynamicClass())
2315 ContainingType = RealDecl;
2316
2317 RealDecl.setContainingType(ContainingType);
2318}
2319
Guy Benyei11169dd2012-12-18 14:30:41 +00002320/// CreateMemberType - Create new member and increase Offset by FType's size.
2321llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2322 StringRef Name,
2323 uint64_t *Offset) {
2324 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2325 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2326 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2327 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2328 FieldSize, FieldAlign,
2329 *Offset, 0, FieldTy);
2330 *Offset += FieldSize;
2331 return Ty;
2332}
2333
David Blaikiebd483762013-05-20 04:58:53 +00002334llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2335 // We only need a declaration (not a definition) of the type - so use whatever
2336 // we would otherwise do to get a type for a pointee. (forward declarations in
2337 // limited debug info, full definitions (if the type definition is available)
2338 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002339 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2340 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002341 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002342 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2343 // This doesn't handle providing declarations (for functions or variables) for
2344 // entities without definitions in this TU, nor when the definition proceeds
2345 // the call to this function.
2346 // FIXME: This should be split out into more specific maps with support for
2347 // emitting forward declarations and merging definitions with declarations,
2348 // the same way as we do for types.
2349 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2350 DeclCache.find(D->getCanonicalDecl());
2351 if (I == DeclCache.end())
2352 return llvm::DIDescriptor();
2353 llvm::Value *V = I->second;
2354 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2355}
2356
Guy Benyei11169dd2012-12-18 14:30:41 +00002357/// getFunctionDeclaration - Return debug info descriptor to describe method
2358/// declaration for the given method definition.
2359llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002360 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2361 return llvm::DISubprogram();
2362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2364 if (!FD) return llvm::DISubprogram();
2365
2366 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002367 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002368
2369 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2370 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002371 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002372 if (const CXXMethodDecl *MD =
2373 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002374 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002375 llvm::DISubprogram SP =
2376 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002377 return SP;
2378 }
2379 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 if (MI != SPCache.end()) {
2381 llvm::Value *V = MI->second;
2382 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002383 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 return SP;
2385 }
2386
2387 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2388 E = FD->redecls_end(); I != E; ++I) {
2389 const FunctionDecl *NextFD = *I;
2390 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2391 MI = SPCache.find(NextFD->getCanonicalDecl());
2392 if (MI != SPCache.end()) {
2393 llvm::Value *V = MI->second;
2394 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002395 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 return SP;
2397 }
2398 }
2399 return llvm::DISubprogram();
2400}
2401
2402// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2403// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002404llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2405 QualType FnType,
2406 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002407 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2408 // Create fake but valid subroutine type. Otherwise
2409 // llvm::DISubprogram::Verify() would return false, and
2410 // subprogram DIE will miss DW_AT_decl_file and
2411 // DW_AT_decl_line fields.
2412 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002413
2414 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2415 return getOrCreateMethodType(Method, F);
2416 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2417 // Add "self" and "_cmd"
2418 SmallVector<llvm::Value *, 16> Elts;
2419
2420 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002421 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002422
2423 // Replace the instancetype keyword with the actual type.
2424 if (ResultTy == CGM.getContext().getObjCInstanceType())
2425 ResultTy = CGM.getContext().getPointerType(
2426 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2427
Adrian Prantl7bec9032013-05-10 21:08:31 +00002428 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002430 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2431 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2432 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 // "_cmd" pointer is always second argument.
2434 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2435 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2436 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002437 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 PE = OMethod->param_end(); PI != PE; ++PI)
2439 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2440
2441 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2442 return DBuilder.createSubroutineType(F, EltTypeArray);
2443 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002444
Adrian Prantl800faef2014-02-25 23:42:18 +00002445 // Handle variadic function types; they need an additional
2446 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002447 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2448 if (FD->isVariadic()) {
2449 SmallVector<llvm::Value *, 16> EltTys;
2450 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2451 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2452 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2453 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2454 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2455 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2456 return DBuilder.createSubroutineType(F, EltTypeArray);
2457 }
2458
David Blaikie469f0792013-05-22 23:22:42 +00002459 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002460}
2461
2462/// EmitFunctionStart - Constructs the debug code for entering a function.
2463void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2464 llvm::Function *Fn,
2465 CGBuilderTy &Builder) {
2466
2467 StringRef Name;
2468 StringRef LinkageName;
2469
2470 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2471
2472 const Decl *D = GD.getDecl();
2473 // Function may lack declaration in source code if it is created by Clang
2474 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2475 bool HasDecl = (D != 0);
2476 // Use the location of the declaration.
2477 SourceLocation Loc;
2478 if (HasDecl)
2479 Loc = D->getLocation();
2480
2481 unsigned Flags = 0;
2482 llvm::DIFile Unit = getOrCreateFile(Loc);
2483 llvm::DIDescriptor FDContext(Unit);
2484 llvm::DIArray TParamsArray;
2485 if (!HasDecl) {
2486 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002487 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2489 // If there is a DISubprogram for this function available then use it.
2490 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2491 FI = SPCache.find(FD->getCanonicalDecl());
2492 if (FI != SPCache.end()) {
2493 llvm::Value *V = FI->second;
2494 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2495 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2496 llvm::MDNode *SPN = SP;
2497 LexicalBlockStack.push_back(SPN);
2498 RegionMap[D] = llvm::WeakVH(SP);
2499 return;
2500 }
2501 }
2502 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002503 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 if (FD->hasPrototype()) {
2505 LinkageName = CGM.getMangledName(GD);
2506 Flags |= llvm::DIDescriptor::FlagPrototyped;
2507 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002508 // No need to replicate the linkage name if it isn't different from the
2509 // subprogram name, no need to have it at all unless coverage is enabled or
2510 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002512 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2513 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002514 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 LinkageName = StringRef();
2516
Eric Christopher75e17682013-05-16 00:45:23 +00002517 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002519 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 FDContext = getOrCreateNameSpace(NSDecl);
2521 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002522 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2523 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002524
2525 // Collect template parameters.
2526 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2527 }
2528 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2529 Name = getObjCMethodName(OMD);
2530 Flags |= llvm::DIDescriptor::FlagPrototyped;
2531 } else {
2532 // Use llvm function name.
2533 Name = Fn->getName();
2534 Flags |= llvm::DIDescriptor::FlagPrototyped;
2535 }
2536 if (!Name.empty() && Name[0] == '\01')
2537 Name = Name.substr(1);
2538
2539 unsigned LineNo = getLineNumber(Loc);
2540 if (!HasDecl || D->isImplicit())
2541 Flags |= llvm::DIDescriptor::FlagArtificial;
2542
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002543 llvm::DISubprogram SP =
2544 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2545 getOrCreateFunctionType(D, FnType, Unit),
2546 Fn->hasInternalLinkage(), true /*definition*/,
2547 getLineNumber(CurLoc), Flags,
2548 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2549 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002550 if (HasDecl)
2551 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002552
2553 // Push function on region stack.
2554 llvm::MDNode *SPN = SP;
2555 LexicalBlockStack.push_back(SPN);
2556 if (HasDecl)
2557 RegionMap[D] = llvm::WeakVH(SP);
2558}
2559
2560/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002561/// information in the source file. If the location is invalid, the
2562/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002563void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002564 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 // Update our current location
2566 setLocation(Loc);
2567
2568 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2569
2570 // Don't bother if things are the same as last time.
2571 SourceManager &SM = CGM.getContext().getSourceManager();
2572 if (CurLoc == PrevLoc ||
2573 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2574 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002575 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2576 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2577 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002579
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 // Update last state.
2581 PrevLoc = CurLoc;
2582
Adrian Prantle83b1302014-01-07 22:05:52 +00002583 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002584 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2585 (getLineNumber(CurLoc),
2586 getColumnNumber(CurLoc, ForceColumnInfo),
2587 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002588}
2589
2590/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2591/// the stack.
2592void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2593 llvm::DIDescriptor D =
2594 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2595 llvm::DIDescriptor() :
2596 llvm::DIDescriptor(LexicalBlockStack.back()),
2597 getOrCreateFile(CurLoc),
2598 getLineNumber(CurLoc),
2599 getColumnNumber(CurLoc));
2600 llvm::MDNode *DN = D;
2601 LexicalBlockStack.push_back(DN);
2602}
2603
2604/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2605/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002606void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2607 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 // Set our current location.
2609 setLocation(Loc);
2610
2611 // Create a new lexical block and push it on the stack.
2612 CreateLexicalBlock(Loc);
2613
2614 // Emit a line table change for the current location inside the new scope.
2615 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2616 getColumnNumber(Loc),
2617 LexicalBlockStack.back()));
2618}
2619
2620/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2621/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002622void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2623 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2625
2626 // Provide an entry in the line table for the end of the block.
2627 EmitLocation(Builder, Loc);
2628
2629 LexicalBlockStack.pop_back();
2630}
2631
2632/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2633void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2634 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2635 unsigned RCount = FnBeginRegionCount.back();
2636 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2637
2638 // Pop all regions for this function.
2639 while (LexicalBlockStack.size() != RCount)
2640 EmitLexicalBlockEnd(Builder, CurLoc);
2641 FnBeginRegionCount.pop_back();
2642}
2643
Eric Christopherb2a008c2013-05-16 00:45:12 +00002644// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002645// See BuildByRefType.
2646llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2647 uint64_t *XOffset) {
2648
2649 SmallVector<llvm::Value *, 5> EltTys;
2650 QualType FType;
2651 uint64_t FieldSize, FieldOffset;
2652 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002653
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002655 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002656
2657 FieldOffset = 0;
2658 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2659 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2660 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2661 FType = CGM.getContext().IntTy;
2662 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2663 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2664
2665 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2666 if (HasCopyAndDispose) {
2667 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2668 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2669 &FieldOffset));
2670 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2671 &FieldOffset));
2672 }
2673 bool HasByrefExtendedLayout;
2674 Qualifiers::ObjCLifetime Lifetime;
2675 if (CGM.getContext().getByrefLifetime(Type,
2676 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002677 && HasByrefExtendedLayout) {
2678 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 EltTys.push_back(CreateMemberType(Unit, FType,
2680 "__byref_variable_layout",
2681 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002682 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002683
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2685 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002686 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002687 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2689 CharUnits AlignedOffsetInBytes
2690 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2691 CharUnits NumPaddingBytes
2692 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002693
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 if (NumPaddingBytes.isPositive()) {
2695 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2696 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2697 pad, ArrayType::Normal, 0);
2698 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2699 }
2700 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002701
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 FType = Type;
2703 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2704 FieldSize = CGM.getContext().getTypeSize(FType);
2705 FieldAlign = CGM.getContext().toBits(Align);
2706
Eric Christopherb2a008c2013-05-16 00:45:12 +00002707 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2709 0, FieldSize, FieldAlign,
2710 FieldOffset, 0, FieldTy);
2711 EltTys.push_back(FieldTy);
2712 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002713
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002715
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002717
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002719 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002720}
2721
2722/// EmitDeclare - Emit local variable declaration debug info.
2723void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002724 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002726 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2728
David Blaikie7fceebf2013-08-19 03:37:48 +00002729 bool Unwritten =
2730 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2731 cast<Decl>(VD->getDeclContext())->isImplicit());
2732 llvm::DIFile Unit;
2733 if (!Unwritten)
2734 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 llvm::DIType Ty;
2736 uint64_t XOffset = 0;
2737 if (VD->hasAttr<BlocksAttr>())
2738 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002739 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 Ty = getOrCreateType(VD->getType(), Unit);
2741
2742 // If there is no debug info for this type then do not emit debug info
2743 // for this variable.
2744 if (!Ty)
2745 return;
2746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002748 unsigned Line = 0;
2749 unsigned Column = 0;
2750 if (!Unwritten) {
2751 Line = getLineNumber(VD->getLocation());
2752 Column = getColumnNumber(VD->getLocation());
2753 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 unsigned Flags = 0;
2755 if (VD->isImplicit())
2756 Flags |= llvm::DIDescriptor::FlagArtificial;
2757 // If this is the first argument and it is implicit then
2758 // give it an object pointer flag.
2759 // FIXME: There has to be a better way to do this, but for static
2760 // functions there won't be an implicit param at arg1 and
2761 // otherwise it is 'self' or 'this'.
2762 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2763 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002764 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002765 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2766 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002767 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002768
2769 llvm::MDNode *Scope = LexicalBlockStack.back();
2770
2771 StringRef Name = VD->getName();
2772 if (!Name.empty()) {
2773 if (VD->hasAttr<BlocksAttr>()) {
2774 CharUnits offset = CharUnits::fromQuantity(32);
2775 SmallVector<llvm::Value *, 9> addr;
2776 llvm::Type *Int64Ty = CGM.Int64Ty;
2777 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2778 // offset of __forwarding field
2779 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002780 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2782 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2783 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2784 // offset of x field
2785 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2786 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2787
2788 // Create the descriptor for the variable.
2789 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002790 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 llvm::DIDescriptor(Scope),
2792 VD->getName(), Unit, Line, Ty,
2793 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002794
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 // Insert an llvm.dbg.declare into the current block.
2796 llvm::Instruction *Call =
2797 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2798 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2799 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002800 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002801 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002802 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2803 // If VD is an anonymous union then Storage represents value for
2804 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002806 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 for (RecordDecl::field_iterator I = RD->field_begin(),
2808 E = RD->field_end();
2809 I != E; ++I) {
2810 FieldDecl *Field = *I;
2811 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2812 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002813
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 // Ignore unnamed fields. Do not ignore unnamed records.
2815 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2816 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002817
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 // Use VarDecl's Tag, Scope and Line number.
2819 llvm::DIVariable D =
2820 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002821 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 CGM.getLangOpts().Optimize, Flags,
2823 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002824
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 // 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));
2829 }
David Blaikie219c7d92013-01-05 20:03:07 +00002830 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 }
2832 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002833
2834 // Create the descriptor for the variable.
2835 llvm::DIVariable D =
2836 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2837 Name, Unit, Line, Ty,
2838 CGM.getLangOpts().Optimize, Flags, ArgNo);
2839
2840 // Insert an llvm.dbg.declare into the current block.
2841 llvm::Instruction *Call =
2842 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2843 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002844}
2845
2846void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2847 llvm::Value *Storage,
2848 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002849 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2851}
2852
Adrian Prantlde17db32013-03-29 19:20:29 +00002853/// Look up the completed type for a self pointer in the TypeCache and
2854/// create a copy of it with the ObjectPointer and Artificial flags
2855/// set. If the type is not cached, a new one is created. This should
2856/// never happen though, since creating a type for the implicit self
2857/// argument implies that we already parsed the interface definition
2858/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002859llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2860 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002861 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002862 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002863 else DEBUG(llvm::dbgs() << "No cached type for self.");
2864 return DBuilder.createObjectPointerType(Ty);
2865}
2866
Guy Benyei11169dd2012-12-18 14:30:41 +00002867void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2868 llvm::Value *Storage,
2869 CGBuilderTy &Builder,
2870 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002871 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002873
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 if (Builder.GetInsertBlock() == 0)
2875 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002876
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002878
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 uint64_t XOffset = 0;
2880 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2881 llvm::DIType Ty;
2882 if (isByRef)
2883 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002884 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 Ty = getOrCreateType(VD->getType(), Unit);
2886
2887 // Self is passed along as an implicit non-arg variable in a
2888 // block. Mark it as the object pointer.
2889 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002890 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002891
2892 // Get location information.
2893 unsigned Line = getLineNumber(VD->getLocation());
2894 unsigned Column = getColumnNumber(VD->getLocation());
2895
2896 const llvm::DataLayout &target = CGM.getDataLayout();
2897
2898 CharUnits offset = CharUnits::fromQuantity(
2899 target.getStructLayout(blockInfo.StructureType)
2900 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2901
2902 SmallVector<llvm::Value *, 9> addr;
2903 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002904 if (isa<llvm::AllocaInst>(Storage))
2905 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2907 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2908 if (isByRef) {
2909 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2910 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2911 // offset of __forwarding field
2912 offset = CGM.getContext()
2913 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2914 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2915 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2916 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2917 // offset of x field
2918 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2919 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2920 }
2921
2922 // Create the descriptor for the variable.
2923 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002924 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 llvm::DIDescriptor(LexicalBlockStack.back()),
2926 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002927
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 // Insert an llvm.dbg.declare into the current block.
2929 llvm::Instruction *Call =
2930 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2931 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2932 LexicalBlockStack.back()));
2933}
2934
2935/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2936/// variable declaration.
2937void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2938 unsigned ArgNo,
2939 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002940 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2942}
2943
2944namespace {
2945 struct BlockLayoutChunk {
2946 uint64_t OffsetInBits;
2947 const BlockDecl::Capture *Capture;
2948 };
2949 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2950 return l.OffsetInBits < r.OffsetInBits;
2951 }
2952}
2953
2954void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002955 llvm::Value *Arg,
2956 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002958 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 ASTContext &C = CGM.getContext();
2960 const BlockDecl *blockDecl = block.getBlockDecl();
2961
2962 // Collect some general information about the block's location.
2963 SourceLocation loc = blockDecl->getCaretLocation();
2964 llvm::DIFile tunit = getOrCreateFile(loc);
2965 unsigned line = getLineNumber(loc);
2966 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002967
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 // Build the debug-info type for the block literal.
2969 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2970
2971 const llvm::StructLayout *blockLayout =
2972 CGM.getDataLayout().getStructLayout(block.StructureType);
2973
2974 SmallVector<llvm::Value*, 16> fields;
2975 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2976 blockLayout->getElementOffsetInBits(0),
2977 tunit, tunit));
2978 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2979 blockLayout->getElementOffsetInBits(1),
2980 tunit, tunit));
2981 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2982 blockLayout->getElementOffsetInBits(2),
2983 tunit, tunit));
2984 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2985 blockLayout->getElementOffsetInBits(3),
2986 tunit, tunit));
2987 fields.push_back(createFieldType("__descriptor",
2988 C.getPointerType(block.NeedsCopyDispose ?
2989 C.getBlockDescriptorExtendedType() :
2990 C.getBlockDescriptorType()),
2991 0, loc, AS_public,
2992 blockLayout->getElementOffsetInBits(4),
2993 tunit, tunit));
2994
2995 // We want to sort the captures by offset, not because DWARF
2996 // requires this, but because we're paranoid about debuggers.
2997 SmallVector<BlockLayoutChunk, 8> chunks;
2998
2999 // 'this' capture.
3000 if (blockDecl->capturesCXXThis()) {
3001 BlockLayoutChunk chunk;
3002 chunk.OffsetInBits =
3003 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3004 chunk.Capture = 0;
3005 chunks.push_back(chunk);
3006 }
3007
3008 // Variable captures.
3009 for (BlockDecl::capture_const_iterator
3010 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3011 i != e; ++i) {
3012 const BlockDecl::Capture &capture = *i;
3013 const VarDecl *variable = capture.getVariable();
3014 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3015
3016 // Ignore constant captures.
3017 if (captureInfo.isConstant())
3018 continue;
3019
3020 BlockLayoutChunk chunk;
3021 chunk.OffsetInBits =
3022 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3023 chunk.Capture = &capture;
3024 chunks.push_back(chunk);
3025 }
3026
3027 // Sort by offset.
3028 llvm::array_pod_sort(chunks.begin(), chunks.end());
3029
3030 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3031 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3032 uint64_t offsetInBits = i->OffsetInBits;
3033 const BlockDecl::Capture *capture = i->Capture;
3034
3035 // If we have a null capture, this must be the C++ 'this' capture.
3036 if (!capture) {
3037 const CXXMethodDecl *method =
3038 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3039 QualType type = method->getThisType(C);
3040
3041 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3042 offsetInBits, tunit, tunit));
3043 continue;
3044 }
3045
3046 const VarDecl *variable = capture->getVariable();
3047 StringRef name = variable->getName();
3048
3049 llvm::DIType fieldType;
3050 if (capture->isByRef()) {
3051 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3052
3053 // FIXME: this creates a second copy of this type!
3054 uint64_t xoffset;
3055 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3056 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3057 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3058 ptrInfo.first, ptrInfo.second,
3059 offsetInBits, 0, fieldType);
3060 } else {
3061 fieldType = createFieldType(name, variable->getType(), 0,
3062 loc, AS_public, offsetInBits, tunit, tunit);
3063 }
3064 fields.push_back(fieldType);
3065 }
3066
3067 SmallString<36> typeName;
3068 llvm::raw_svector_ostream(typeName)
3069 << "__block_literal_" << CGM.getUniqueBlockCount();
3070
3071 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3072
3073 llvm::DIType type =
3074 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3075 CGM.getContext().toBits(block.BlockSize),
3076 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003077 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3079
3080 // Get overall information about the block.
3081 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3082 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003083
3084 // Create the descriptor for the parameter.
3085 llvm::DIVariable debugVar =
3086 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003087 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003088 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003090 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3091
Adrian Prantl616bef42013-03-14 21:52:59 +00003092 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003093 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003094 llvm::Instruction *DbgVal =
3095 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003096 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003097 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3098 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003099
Adrian Prantl616bef42013-03-14 21:52:59 +00003100 // Insert an llvm.dbg.declare into the current block.
3101 llvm::Instruction *DbgDecl =
3102 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3103 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003104}
3105
David Blaikie6943dea2013-08-20 01:28:15 +00003106/// If D is an out-of-class definition of a static data member of a class, find
3107/// its corresponding in-class declaration.
3108llvm::DIDerivedType
3109CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3110 if (!D->isStaticDataMember())
3111 return llvm::DIDerivedType();
3112 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3113 StaticDataMemberCache.find(D->getCanonicalDecl());
3114 if (MI != StaticDataMemberCache.end()) {
3115 assert(MI->second && "Static data member declaration should still exist");
3116 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003117 }
David Blaikiece763042013-08-20 21:49:21 +00003118
3119 // If the member wasn't found in the cache, lazily construct and add it to the
3120 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003121 llvm::DICompositeType Ctxt(
3122 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3123 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003124 return T;
3125}
3126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003128void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003130 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 // Create global variable debug descriptor.
3132 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3133 unsigned LineNo = getLineNumber(D->getLocation());
3134
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003135 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003136
3137 QualType T = D->getType();
3138 if (T->isIncompleteArrayType()) {
3139
3140 // CodeGen turns int[] into int[1] so we'll do the same here.
3141 llvm::APInt ConstVal(32, 1);
3142 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3143
3144 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3145 ArrayType::Normal, 0);
3146 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003147 StringRef DeclName = D->getName();
3148 StringRef LinkageName;
3149 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3150 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3151 LinkageName = Var->getName();
3152 if (LinkageName == DeclName)
3153 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003154 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003156 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3157 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003158 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003159 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003160 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003161}
3162
3163/// EmitGlobalVariable - Emit information about an objective-c interface.
3164void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3165 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003166 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 // Create global variable debug descriptor.
3168 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3169 unsigned LineNo = getLineNumber(ID->getLocation());
3170
3171 StringRef Name = ID->getName();
3172
3173 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3174 if (T->isIncompleteArrayType()) {
3175
3176 // CodeGen turns int[] into int[1] so we'll do the same here.
3177 llvm::APInt ConstVal(32, 1);
3178 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3179
3180 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3181 ArrayType::Normal, 0);
3182 }
3183
3184 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3185 getOrCreateType(T, Unit),
3186 Var->hasInternalLinkage(), Var);
3187}
3188
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003189/// EmitGlobalVariable - Emit global variable's debug info.
3190void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3191 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003192 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003193 // Create the descriptor for the variable.
3194 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3195 StringRef Name = VD->getName();
3196 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3197 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3198 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3199 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3200 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3201 }
3202 // Do not use DIGlobalVariable for enums.
3203 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3204 return;
3205 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3206 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3207 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3208 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003209}
3210
3211llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3212 if (!LexicalBlockStack.empty())
3213 return llvm::DIScope(LexicalBlockStack.back());
3214 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003215}
3216
David Blaikie9f88fe82013-04-22 06:13:21 +00003217void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003218 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3219 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003220 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003221 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3222 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003223 getLineNumber(UD.getLocation()));
3224}
3225
David Blaikiebd483762013-05-20 04:58:53 +00003226void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3227 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3228 return;
3229 assert(UD.shadow_size() &&
3230 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3231 // Emitting one decl is sufficient - debuggers can detect that this is an
3232 // overloaded name & provide lookup for all the overloads.
3233 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003234 if (llvm::DIDescriptor Target =
3235 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003236 DBuilder.createImportedDeclaration(
3237 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3238 getLineNumber(USD.getLocation()));
3239}
3240
David Blaikief121b932013-05-20 22:50:41 +00003241llvm::DIImportedEntity
3242CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3243 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3244 return llvm::DIImportedEntity(0);
3245 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3246 if (VH)
3247 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3248 llvm::DIImportedEntity R(0);
3249 if (const NamespaceAliasDecl *Underlying =
3250 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3251 // This could cache & dedup here rather than relying on metadata deduping.
3252 R = DBuilder.createImportedModule(
3253 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3254 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3255 NA.getName());
3256 else
3257 R = DBuilder.createImportedModule(
3258 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3259 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3260 getLineNumber(NA.getLocation()), NA.getName());
3261 VH = R;
3262 return R;
3263}
3264
Guy Benyei11169dd2012-12-18 14:30:41 +00003265/// getOrCreateNamesSpace - Return namespace descriptor for the given
3266/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003267llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003268CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003269 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003270 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 NameSpaceCache.find(NSDecl);
3272 if (I != NameSpaceCache.end())
3273 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3276 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003277 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3279 llvm::DINameSpace NS =
3280 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3281 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3282 return NS;
3283}
3284
3285void CGDebugInfo::finalize() {
3286 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3287 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3288 llvm::DIType Ty, RepTy;
3289 // Verify that the debug info still exists.
3290 if (llvm::Value *V = VI->second)
3291 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3294 TypeCache.find(VI->first);
3295 if (it != TypeCache.end()) {
3296 // Verify that the debug info still exists.
3297 if (llvm::Value *V = it->second)
3298 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3299 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003300
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003301 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003304
3305 // We keep our own list of retained types, because we need to look
3306 // up the final type in the type cache.
3307 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3308 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf801f802013-08-29 20:48:48 +00003309 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003310
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 DBuilder.finalize();
3312}