blob: feed2b48afc269b5456abcc5a805bcbace2c6003 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
Adrian Prantled6bbe42013-07-18 00:28:02 +000054
55NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
56 : DI(CGF.getDebugInfo()), Builder(B) {
57 if (DI) {
58 SavedLoc = DI->getLocation();
59 DI->CurLoc = SourceLocation();
60 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
61 }
62}
63
64NoLocation::~NoLocation() {
65 if (DI) {
66 assert(Builder.getCurrentDebugLocation().isUnknown());
67 DI->CurLoc = SavedLoc;
68 }
69}
70
Adrian Prantlb061ce22013-07-18 01:36:04 +000071ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantled6bbe42013-07-18 00:28:02 +000072 : DI(CGF.getDebugInfo()), Builder(B) {
73 if (DI) {
74 SavedLoc = DI->getLocation();
75 // Sync the Builder.
76 DI->EmitLocation(Builder, SavedLoc);
77 DI->CurLoc = SourceLocation();
78 // Construct a location that has a valid scope, but no line info.
Adrian Prantl0a103232013-07-18 00:47:12 +000079 llvm::DIDescriptor Scope = DI->LexicalBlockStack.empty() ?
80 llvm::DIDescriptor(DI->TheCU) :
81 llvm::DIDescriptor(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000082 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
83 }
84}
85
Adrian Prantlb061ce22013-07-18 01:36:04 +000086ArtificialLocation::~ArtificialLocation() {
Adrian Prantled6bbe42013-07-18 00:28:02 +000087 if (DI) {
88 assert(Builder.getCurrentDebugLocation().getLine() == 0);
89 DI->CurLoc = SavedLoc;
90 }
91}
92
Guy Benyei7f92f2d2012-12-18 14:30:41 +000093void CGDebugInfo::setLocation(SourceLocation Loc) {
94 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +000095 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000096
97 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
98
99 // If we've changed files in the middle of a lexical scope go ahead
100 // and create a new lexical scope with file node if it's different
101 // from the one in the scope.
102 if (LexicalBlockStack.empty()) return;
103
104 SourceManager &SM = CGM.getContext().getSourceManager();
105 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
106 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
107
108 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
109 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
110 return;
111
112 llvm::MDNode *LB = LexicalBlockStack.back();
113 llvm::DIScope Scope = llvm::DIScope(LB);
114 if (Scope.isLexicalBlockFile()) {
115 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
116 llvm::DIDescriptor D
117 = DBuilder.createLexicalBlockFile(LBF.getScope(),
118 getOrCreateFile(CurLoc));
119 llvm::MDNode *N = D;
120 LexicalBlockStack.pop_back();
121 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000122 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000123 llvm::DIDescriptor D
124 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
125 llvm::MDNode *N = D;
126 LexicalBlockStack.pop_back();
127 LexicalBlockStack.push_back(N);
128 }
129}
130
131/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000132llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000133 if (!Context)
134 return TheCU;
135
136 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
137 I = RegionMap.find(Context);
138 if (I != RegionMap.end()) {
139 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000140 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000141 }
142
143 // Check namespace.
144 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000145 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000146
David Blaikiebb000792013-04-19 06:56:38 +0000147 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
148 if (!RDecl->isDependentType())
149 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000150 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000151 return TheCU;
152}
153
154/// getFunctionName - Get function name for the given FunctionDecl. If the
155/// name is constructred on demand (e.g. C++ destructor) then the name
156/// is stored on the side.
157StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
158 assert (FD && "Invalid FunctionDecl!");
159 IdentifierInfo *FII = FD->getIdentifier();
160 FunctionTemplateSpecializationInfo *Info
161 = FD->getTemplateSpecializationInfo();
162 if (!Info && FII)
163 return FII->getName();
164
165 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000166 SmallString<128> NS;
167 llvm::raw_svector_ostream OS(NS);
168 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000169
170 // Add any template specialization args.
171 if (Info) {
172 const TemplateArgumentList *TArgs = Info->TemplateArguments;
173 const TemplateArgument *Args = TArgs->data();
174 unsigned NumArgs = TArgs->size();
175 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000176 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
177 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000178 }
179
180 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000181 OS.flush();
182 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
183 memcpy(StrPtr, NS.data(), NS.size());
184 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000185}
186
187StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
188 SmallString<256> MethodName;
189 llvm::raw_svector_ostream OS(MethodName);
190 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
191 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000192 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000193 dyn_cast<const ObjCImplementationDecl>(DC)) {
194 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000195 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000196 dyn_cast<const ObjCInterfaceDecl>(DC)) {
197 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000198 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCCategoryImplDecl>(DC)){
200 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
201 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000202 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000203 // We can extract the type of the class from the self pointer.
204 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
205 QualType ClassTy =
206 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
207 ClassTy.print(OS, PrintingPolicy(LangOptions()));
208 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000209 }
210 OS << ' ' << OMD->getSelector().getAsString() << ']';
211
212 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
213 memcpy(StrPtr, MethodName.begin(), OS.tell());
214 return StringRef(StrPtr, OS.tell());
215}
216
217/// getSelectorName - Return selector name. This is used for debugging
218/// info.
219StringRef CGDebugInfo::getSelectorName(Selector S) {
220 const std::string &SName = S.getAsString();
221 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
222 memcpy(StrPtr, SName.data(), SName.size());
223 return StringRef(StrPtr, SName.size());
224}
225
226/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000227StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000228CGDebugInfo::getClassName(const RecordDecl *RD) {
229 const ClassTemplateSpecializationDecl *Spec
230 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
231 if (!Spec)
232 return RD->getName();
233
234 const TemplateArgument *Args;
235 unsigned NumArgs;
236 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
237 const TemplateSpecializationType *TST =
238 cast<TemplateSpecializationType>(TAW->getType());
239 Args = TST->getArgs();
240 NumArgs = TST->getNumArgs();
241 } else {
242 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
243 Args = TemplateArgs.data();
244 NumArgs = TemplateArgs.size();
245 }
246 StringRef Name = RD->getIdentifier()->getName();
247 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000248 SmallString<128> TemplateArgList;
249 {
250 llvm::raw_svector_ostream OS(TemplateArgList);
251 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
252 Policy);
253 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000254
255 // Copy this name on the side and use its reference.
256 size_t Length = Name.size() + TemplateArgList.size();
257 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
258 memcpy(StrPtr, Name.data(), Name.size());
259 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
260 return StringRef(StrPtr, Length);
261}
262
263/// getOrCreateFile - Get the file debug info descriptor for the input location.
264llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
265 if (!Loc.isValid())
266 // If Location is not valid then use main input file.
267 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
268
269 SourceManager &SM = CGM.getContext().getSourceManager();
270 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
271
272 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
273 // If the location is not valid then use main input file.
274 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
275
276 // Cache the results.
277 const char *fname = PLoc.getFilename();
278 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
279 DIFileCache.find(fname);
280
281 if (it != DIFileCache.end()) {
282 // Verify that the information still exists.
283 if (llvm::Value *V = it->second)
284 return llvm::DIFile(cast<llvm::MDNode>(V));
285 }
286
287 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
288
289 DIFileCache[fname] = F;
290 return F;
291}
292
293/// getOrCreateMainFile - Get the file info for main compile unit.
294llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
295 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
296}
297
298/// getLineNumber - Get line number for the location. If location is invalid
299/// then use current location.
300unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
301 if (Loc.isInvalid() && CurLoc.isInvalid())
302 return 0;
303 SourceManager &SM = CGM.getContext().getSourceManager();
304 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
305 return PLoc.isValid()? PLoc.getLine() : 0;
306}
307
308/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000309unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000310 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000311 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000312 return 0;
313
314 // If the location is invalid then use the current column.
315 if (Loc.isInvalid() && CurLoc.isInvalid())
316 return 0;
317 SourceManager &SM = CGM.getContext().getSourceManager();
318 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
319 return PLoc.isValid()? PLoc.getColumn() : 0;
320}
321
322StringRef CGDebugInfo::getCurrentDirname() {
323 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
324 return CGM.getCodeGenOpts().DebugCompilationDir;
325
326 if (!CWDName.empty())
327 return CWDName;
328 SmallString<256> CWD;
329 llvm::sys::fs::current_path(CWD);
330 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
331 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
332 return CWDName = StringRef(CompDirnamePtr, CWD.size());
333}
334
335/// CreateCompileUnit - Create new compile unit.
336void CGDebugInfo::CreateCompileUnit() {
337
338 // Get absolute path name.
339 SourceManager &SM = CGM.getContext().getSourceManager();
340 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
341 if (MainFileName.empty())
342 MainFileName = "<unknown>";
343
344 // The main file name provided via the "-main-file-name" option contains just
345 // the file name itself with no path information. This file name may have had
346 // a relative path, so we look into the actual file entry for the main
347 // file to determine the real absolute path for the file.
348 std::string MainFileDir;
349 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
350 MainFileDir = MainFile->getDir()->getName();
351 if (MainFileDir != ".")
352 MainFileName = MainFileDir + "/" + MainFileName;
353 }
354
355 // Save filename string.
356 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
357 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
358 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000359
360 // Save split dwarf file string.
361 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
362 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
363 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
364 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000365
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000366 unsigned LangTag;
367 const LangOptions &LO = CGM.getLangOpts();
368 if (LO.CPlusPlus) {
369 if (LO.ObjC1)
370 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
371 else
372 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
373 } else if (LO.ObjC1) {
374 LangTag = llvm::dwarf::DW_LANG_ObjC;
375 } else if (LO.C99) {
376 LangTag = llvm::dwarf::DW_LANG_C99;
377 } else {
378 LangTag = llvm::dwarf::DW_LANG_C89;
379 }
380
381 std::string Producer = getClangFullVersion();
382
383 // Figure out which version of the ObjC runtime we have.
384 unsigned RuntimeVers = 0;
385 if (LO.ObjC1)
386 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
387
388 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000389 // FIXME - Eliminate TheCU.
Eric Christopher8fed3f42013-07-19 00:51:58 +0000390 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
391 Producer, LO.Optimize,
392 CGM.getCodeGenOpts().DwarfDebugFlags,
393 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000394}
395
396/// CreateType - Get the Basic type from the cache or create a new
397/// one if necessary.
398llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
399 unsigned Encoding = 0;
400 StringRef BTName;
401 switch (BT->getKind()) {
402#define BUILTIN_TYPE(Id, SingletonId)
403#define PLACEHOLDER_TYPE(Id, SingletonId) \
404 case BuiltinType::Id:
405#include "clang/AST/BuiltinTypes.def"
406 case BuiltinType::Dependent:
407 llvm_unreachable("Unexpected builtin type");
408 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000409 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000410 case BuiltinType::Void:
411 return llvm::DIType();
412 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000413 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000414 return ClassTy;
415 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
416 "objc_class", TheCU,
417 getOrCreateMainFile(), 0);
418 return ClassTy;
419 case BuiltinType::ObjCId: {
420 // typedef struct objc_class *Class;
421 // typedef struct objc_object {
422 // Class isa;
423 // } *id;
424
Eric Christopherb2d13922013-07-18 00:52:50 +0000425 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000426 return ObjTy;
427
Eric Christopherb2d13922013-07-18 00:52:50 +0000428 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000429 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
430 "objc_class", TheCU,
431 getOrCreateMainFile(), 0);
432
433 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000434
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000435 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
436
Eric Christopherf068c922013-04-02 22:59:11 +0000437 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000438 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
439 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000440
Eric Christopherf068c922013-04-02 22:59:11 +0000441 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
442 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000443 return ObjTy;
444 }
445 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000446 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000447 return SelTy;
448 SelTy =
449 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
450 "objc_selector", TheCU, getOrCreateMainFile(),
451 0);
452 return SelTy;
453 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000454
455 case BuiltinType::OCLImage1d:
456 return getOrCreateStructPtrType("opencl_image1d_t",
457 OCLImage1dDITy);
458 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000459 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000460 OCLImage1dArrayDITy);
461 case BuiltinType::OCLImage1dBuffer:
462 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
463 OCLImage1dBufferDITy);
464 case BuiltinType::OCLImage2d:
465 return getOrCreateStructPtrType("opencl_image2d_t",
466 OCLImage2dDITy);
467 case BuiltinType::OCLImage2dArray:
468 return getOrCreateStructPtrType("opencl_image2d_array_t",
469 OCLImage2dArrayDITy);
470 case BuiltinType::OCLImage3d:
471 return getOrCreateStructPtrType("opencl_image3d_t",
472 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000473 case BuiltinType::OCLSampler:
474 return DBuilder.createBasicType("opencl_sampler_t",
475 CGM.getContext().getTypeSize(BT),
476 CGM.getContext().getTypeAlign(BT),
477 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000478 case BuiltinType::OCLEvent:
479 return getOrCreateStructPtrType("opencl_event_t",
480 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000481
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000482 case BuiltinType::UChar:
483 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
484 case BuiltinType::Char_S:
485 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
486 case BuiltinType::Char16:
487 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
488 case BuiltinType::UShort:
489 case BuiltinType::UInt:
490 case BuiltinType::UInt128:
491 case BuiltinType::ULong:
492 case BuiltinType::WChar_U:
493 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
494 case BuiltinType::Short:
495 case BuiltinType::Int:
496 case BuiltinType::Int128:
497 case BuiltinType::Long:
498 case BuiltinType::WChar_S:
499 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
500 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
501 case BuiltinType::Half:
502 case BuiltinType::Float:
503 case BuiltinType::LongDouble:
504 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
505 }
506
507 switch (BT->getKind()) {
508 case BuiltinType::Long: BTName = "long int"; break;
509 case BuiltinType::LongLong: BTName = "long long int"; break;
510 case BuiltinType::ULong: BTName = "long unsigned int"; break;
511 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
512 default:
513 BTName = BT->getName(CGM.getLangOpts());
514 break;
515 }
516 // Bit size, align and offset of the type.
517 uint64_t Size = CGM.getContext().getTypeSize(BT);
518 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000519 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000520 DBuilder.createBasicType(BTName, Size, Align, Encoding);
521 return DbgTy;
522}
523
524llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
525 // Bit size, align and offset of the type.
526 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
527 if (Ty->isComplexIntegerType())
528 Encoding = llvm::dwarf::DW_ATE_lo_user;
529
530 uint64_t Size = CGM.getContext().getTypeSize(Ty);
531 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000532 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000533 DBuilder.createBasicType("complex", Size, Align, Encoding);
534
535 return DbgTy;
536}
537
538/// CreateCVRType - Get the qualified type from the cache or create
539/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000540llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
541 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000542 QualifierCollector Qc;
543 const Type *T = Qc.strip(Ty);
544
545 // Ignore these qualifiers for now.
546 Qc.removeObjCGCAttr();
547 Qc.removeAddressSpace();
548 Qc.removeObjCLifetime();
549
550 // We will create one Derived type for one qualifier and recurse to handle any
551 // additional ones.
552 unsigned Tag;
553 if (Qc.hasConst()) {
554 Tag = llvm::dwarf::DW_TAG_const_type;
555 Qc.removeConst();
556 } else if (Qc.hasVolatile()) {
557 Tag = llvm::dwarf::DW_TAG_volatile_type;
558 Qc.removeVolatile();
559 } else if (Qc.hasRestrict()) {
560 Tag = llvm::dwarf::DW_TAG_restrict_type;
561 Qc.removeRestrict();
562 } else {
563 assert(Qc.empty() && "Unknown type qualifier for debug info");
564 return getOrCreateType(QualType(T, 0), Unit);
565 }
566
Eric Christopher56b108a2013-06-07 22:54:39 +0000567 llvm::DIType FromTy =
568 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000569
570 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
571 // CVR derived types.
572 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000573
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000574 return DbgTy;
575}
576
577llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
578 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000579
580 // The frontend treats 'id' as a typedef to an ObjCObjectType,
581 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
582 // debug info, we want to emit 'id' in both cases.
583 if (Ty->isObjCQualifiedIdType())
584 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
585
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000586 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000587 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000588 Ty->getPointeeType(), Unit);
589 return DbgTy;
590}
591
592llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
593 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000594 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 Ty->getPointeeType(), Unit);
596}
597
598// Creates a forward declaration for a RecordDecl in the given context.
599llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
600 llvm::DIDescriptor Ctx) {
601 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
602 unsigned Line = getLineNumber(RD->getLocation());
603 StringRef RDName = getClassName(RD);
604
605 unsigned Tag = 0;
606 if (RD->isStruct() || RD->isInterface())
607 Tag = llvm::dwarf::DW_TAG_structure_type;
608 else if (RD->isUnion())
609 Tag = llvm::dwarf::DW_TAG_union_type;
610 else {
611 assert(RD->isClass());
612 Tag = llvm::dwarf::DW_TAG_class_type;
613 }
614
615 // Create the type.
616 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
617}
618
619// Walk up the context chain and create forward decls for record decls,
620// and normal descriptors for namespaces.
621llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
622 if (!Context)
623 return TheCU;
624
625 // See if we already have the parent.
626 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
627 I = RegionMap.find(Context);
628 if (I != RegionMap.end()) {
629 llvm::Value *V = I->second;
630 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
631 }
Eric Christopher6537f082013-05-16 00:45:12 +0000632
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000633 // Check namespace.
634 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
635 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
636
637 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
638 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000639 llvm::DIType Ty =
640 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
641 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000642 return llvm::DIDescriptor(Ty);
643 }
644 }
645 return TheCU;
646}
647
David Blaikieb0f77b02013-05-24 21:33:22 +0000648/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000649/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000650llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
651 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000652 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653 return getOrCreateType(PointeeTy, Unit);
David Blaikie5f6e2f42013-06-05 05:32:23 +0000654 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000655}
656
657llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000658 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000659 QualType PointeeTy,
660 llvm::DIFile Unit) {
661 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
662 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000663 return DBuilder.createReferenceType(
664 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000665
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000666 // Bit size, align and offset of the type.
667 // Size is always the size of a pointer. We can't use getTypeSize here
668 // because that does not return the correct value for references.
669 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000670 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000671 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
672
David Blaikieb0f77b02013-05-24 21:33:22 +0000673 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000674 Size, Align);
675}
676
Eric Christopherf0890c42013-05-16 00:52:20 +0000677llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
678 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000679 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000680 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000681 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
682 TheCU, getOrCreateMainFile(), 0);
683 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
684 Cache = DBuilder.createPointerType(Cache, Size);
685 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000686}
687
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000688llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
689 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000690 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000691 return BlockLiteralGeneric;
692
693 SmallVector<llvm::Value *, 8> EltTys;
694 llvm::DIType FieldTy;
695 QualType FType;
696 uint64_t FieldSize, FieldOffset;
697 unsigned FieldAlign;
698 llvm::DIArray Elements;
699 llvm::DIType EltTy, DescTy;
700
701 FieldOffset = 0;
702 FType = CGM.getContext().UnsignedLongTy;
703 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
704 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
705
706 Elements = DBuilder.getOrCreateArray(EltTys);
707 EltTys.clear();
708
709 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
710 unsigned LineNo = getLineNumber(CurLoc);
711
712 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
713 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000714 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000715
716 // Bit size, align and offset of the type.
717 uint64_t Size = CGM.getContext().getTypeSize(Ty);
718
719 DescTy = DBuilder.createPointerType(EltTy, Size);
720
721 FieldOffset = 0;
722 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
723 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
724 FType = CGM.getContext().IntTy;
725 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
726 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
727 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
728 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
729
730 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
731 FieldTy = DescTy;
732 FieldSize = CGM.getContext().getTypeSize(Ty);
733 FieldAlign = CGM.getContext().getTypeAlign(Ty);
734 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
735 LineNo, FieldSize, FieldAlign,
736 FieldOffset, 0, FieldTy);
737 EltTys.push_back(FieldTy);
738
739 FieldOffset += FieldSize;
740 Elements = DBuilder.getOrCreateArray(EltTys);
741
742 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
743 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000744 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000745
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000746 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
747 return BlockLiteralGeneric;
748}
749
David Blaikie5f6e2f42013-06-05 05:32:23 +0000750llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
751 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000752 // Typedefs are derived from some other type. If we have a typedef of a
753 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000754 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000755 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherb2d13922013-07-18 00:52:50 +0000756 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000757 return llvm::DIType();
758 // We don't set size information, but do specify where the typedef was
759 // declared.
760 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
761 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000762
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000763 llvm::DIDescriptor TypedefContext =
764 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000765
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000766 return
767 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
768}
769
770llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
771 llvm::DIFile Unit) {
772 SmallVector<llvm::Value *, 16> EltTys;
773
774 // Add the result type at least.
775 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
776
777 // Set up remainder of arguments if there is a prototype.
778 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
779 if (isa<FunctionNoProtoType>(Ty))
780 EltTys.push_back(DBuilder.createUnspecifiedParameter());
781 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
782 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
783 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
784 }
785
786 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
787 return DBuilder.createSubroutineType(Unit, EltTypeArray);
788}
789
790
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000791llvm::DIType CGDebugInfo::createFieldType(StringRef name,
792 QualType type,
793 uint64_t sizeInBitsOverride,
794 SourceLocation loc,
795 AccessSpecifier AS,
796 uint64_t offsetInBits,
797 llvm::DIFile tunit,
798 llvm::DIDescriptor scope) {
799 llvm::DIType debugType = getOrCreateType(type, tunit);
800
801 // Get the location for the field.
802 llvm::DIFile file = getOrCreateFile(loc);
803 unsigned line = getLineNumber(loc);
804
805 uint64_t sizeInBits = 0;
806 unsigned alignInBits = 0;
807 if (!type->isIncompleteArrayType()) {
808 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
809
810 if (sizeInBitsOverride)
811 sizeInBits = sizeInBitsOverride;
812 }
813
814 unsigned flags = 0;
815 if (AS == clang::AS_private)
816 flags |= llvm::DIDescriptor::FlagPrivate;
817 else if (AS == clang::AS_protected)
818 flags |= llvm::DIDescriptor::FlagProtected;
819
820 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
821 alignInBits, offsetInBits, flags, debugType);
822}
823
Eric Christopher0395de32013-01-16 01:22:32 +0000824/// CollectRecordLambdaFields - Helper for CollectRecordFields.
825void CGDebugInfo::
826CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
827 SmallVectorImpl<llvm::Value *> &elements,
828 llvm::DIType RecordTy) {
829 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
830 // has the name and the location of the variable so we should iterate over
831 // both concurrently.
832 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
833 RecordDecl::field_iterator Field = CXXDecl->field_begin();
834 unsigned fieldno = 0;
835 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
836 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
837 const LambdaExpr::Capture C = *I;
838 if (C.capturesVariable()) {
839 VarDecl *V = C.getCapturedVar();
840 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
841 StringRef VName = V->getName();
842 uint64_t SizeInBitsOverride = 0;
843 if (Field->isBitField()) {
844 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
845 assert(SizeInBitsOverride && "found named 0-width bitfield");
846 }
847 llvm::DIType fieldType
848 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
849 C.getLocation(), Field->getAccess(),
850 layout.getFieldOffset(fieldno), VUnit, RecordTy);
851 elements.push_back(fieldType);
852 } else {
853 // TODO: Need to handle 'this' in some way by probably renaming the
854 // this of the lambda class and having a field member of 'this' or
855 // by using AT_object_pointer for the function and having that be
856 // used as 'this' for semantic references.
857 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
858 FieldDecl *f = *Field;
859 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
860 QualType type = f->getType();
861 llvm::DIType fieldType
862 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
863 layout.getFieldOffset(fieldno), VUnit, RecordTy);
864
865 elements.push_back(fieldType);
866 }
867 }
868}
869
870/// CollectRecordStaticField - Helper for CollectRecordFields.
871void CGDebugInfo::
872CollectRecordStaticField(const VarDecl *Var,
873 SmallVectorImpl<llvm::Value *> &elements,
874 llvm::DIType RecordTy) {
875 // Create the descriptor for the static variable, with or without
876 // constant initializers.
877 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
878 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
879
880 // Do not describe enums as static members.
881 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
882 return;
883
884 unsigned LineNumber = getLineNumber(Var->getLocation());
885 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000886 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000887 if (Var->getInit()) {
888 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000889 if (Value) {
890 if (Value->isInt())
891 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
892 if (Value->isFloat())
893 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
894 }
Eric Christopher0395de32013-01-16 01:22:32 +0000895 }
896
897 unsigned Flags = 0;
898 AccessSpecifier Access = Var->getAccess();
899 if (Access == clang::AS_private)
900 Flags |= llvm::DIDescriptor::FlagPrivate;
901 else if (Access == clang::AS_protected)
902 Flags |= llvm::DIDescriptor::FlagProtected;
903
904 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000905 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000906 elements.push_back(GV);
907 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
908}
909
910/// CollectRecordNormalField - Helper for CollectRecordFields.
911void CGDebugInfo::
912CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
913 llvm::DIFile tunit,
914 SmallVectorImpl<llvm::Value *> &elements,
915 llvm::DIType RecordTy) {
916 StringRef name = field->getName();
917 QualType type = field->getType();
918
919 // Ignore unnamed fields unless they're anonymous structs/unions.
920 if (name.empty() && !type->isRecordType())
921 return;
922
923 uint64_t SizeInBitsOverride = 0;
924 if (field->isBitField()) {
925 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
926 assert(SizeInBitsOverride && "found named 0-width bitfield");
927 }
928
929 llvm::DIType fieldType
930 = createFieldType(name, type, SizeInBitsOverride,
931 field->getLocation(), field->getAccess(),
932 OffsetInBits, tunit, RecordTy);
933
934 elements.push_back(fieldType);
935}
936
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937/// CollectRecordFields - A helper function to collect debug info for
938/// record fields. This is used while creating debug info entry for a Record.
939void CGDebugInfo::
940CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
941 SmallVectorImpl<llvm::Value *> &elements,
942 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000943 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
944
Eric Christopher0395de32013-01-16 01:22:32 +0000945 if (CXXDecl && CXXDecl->isLambda())
946 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
947 else {
948 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949
Eric Christopher0395de32013-01-16 01:22:32 +0000950 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000951 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000952
Eric Christopher0395de32013-01-16 01:22:32 +0000953 // Static and non-static members should appear in the same order as
954 // the corresponding declarations in the source program.
955 for (RecordDecl::decl_iterator I = record->decls_begin(),
956 E = record->decls_end(); I != E; ++I)
957 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
958 CollectRecordStaticField(V, elements, RecordTy);
959 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000960 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
961 tunit, elements, RecordTy);
962
963 // Bump field number for next field.
964 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000965 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000966 }
967}
968
969/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
970/// function type is not updated to include implicit "this" pointer. Use this
971/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000972llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000973CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
974 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000975 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000976 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000977 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000978 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
979 Func, Unit);
980}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000981
David Blaikie9a845292013-05-22 23:22:42 +0000982llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000983 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000984 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000985 llvm::DIArray Args = llvm::DICompositeType(
986 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000987 assert (Args.getNumElements() && "Invalid number of arguments!");
988
989 SmallVector<llvm::Value *, 16> Elts;
990
991 // First element is always return type. For 'void' functions it is NULL.
992 Elts.push_back(Args.getElement(0));
993
David Blaikie67f8b5e2013-01-07 22:24:59 +0000994 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000995 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000996 if (isa<ClassTemplateSpecializationDecl>(RD)) {
997 // Create pointer type directly in this case.
998 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
999 QualType PointeeTy = ThisPtrTy->getPointeeType();
1000 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001001 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001002 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1003 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001004 llvm::DIType ThisPtrType =
1005 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1007 // TODO: This and the artificial type below are misleading, the
1008 // types aren't artificial the argument is, but the current
1009 // metadata doesn't represent that.
1010 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1011 Elts.push_back(ThisPtrType);
1012 } else {
1013 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1014 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1015 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1016 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001017 }
1018
1019 // Copy rest of the arguments.
1020 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1021 Elts.push_back(Args.getElement(i));
1022
1023 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1024
1025 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1026}
1027
Eric Christopher6537f082013-05-16 00:45:12 +00001028/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001029/// inside a function.
1030static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1031 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1032 return isFunctionLocalClass(NRD);
1033 if (isa<FunctionDecl>(RD->getDeclContext()))
1034 return true;
1035 return false;
1036}
1037
1038/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1039/// a single member function GlobalDecl.
1040llvm::DISubprogram
1041CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1042 llvm::DIFile Unit,
1043 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001044 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001045 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001047 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001048 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001049
1050 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1051 // make sense to give a single ctor/dtor a linkage name.
1052 StringRef MethodLinkageName;
1053 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1054 MethodLinkageName = CGM.getMangledName(Method);
1055
1056 // Get the location for the method.
1057 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1058 unsigned MethodLine = getLineNumber(Method->getLocation());
1059
1060 // Collect virtual method info.
1061 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001062 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001063 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001065 if (Method->isVirtual()) {
1066 if (Method->isPure())
1067 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1068 else
1069 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001070
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001071 // It doesn't make sense to give a virtual destructor a vtable index,
1072 // since a single destructor has two entries in the vtable.
1073 if (!isa<CXXDestructorDecl>(Method))
1074 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1075 ContainingType = RecordTy;
1076 }
1077
1078 unsigned Flags = 0;
1079 if (Method->isImplicit())
1080 Flags |= llvm::DIDescriptor::FlagArtificial;
1081 AccessSpecifier Access = Method->getAccess();
1082 if (Access == clang::AS_private)
1083 Flags |= llvm::DIDescriptor::FlagPrivate;
1084 else if (Access == clang::AS_protected)
1085 Flags |= llvm::DIDescriptor::FlagProtected;
1086 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1087 if (CXXC->isExplicit())
1088 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001089 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001090 dyn_cast<CXXConversionDecl>(Method)) {
1091 if (CXXC->isExplicit())
1092 Flags |= llvm::DIDescriptor::FlagExplicit;
1093 }
1094 if (Method->hasPrototype())
1095 Flags |= llvm::DIDescriptor::FlagPrototyped;
1096
1097 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1098 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001099 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001100 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001101 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001102 /* isDefinition=*/ false,
1103 Virtuality, VIndex, ContainingType,
1104 Flags, CGM.getLangOpts().Optimize, NULL,
1105 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001106
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001107 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1108
1109 return SP;
1110}
1111
1112/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001113/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001114/// a Record.
1115void CGDebugInfo::
1116CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1117 SmallVectorImpl<llvm::Value *> &EltTys,
1118 llvm::DIType RecordTy) {
1119
1120 // Since we want more than just the individual member decls if we
1121 // have templated functions iterate over every declaration to gather
1122 // the functions.
1123 for(DeclContext::decl_iterator I = RD->decls_begin(),
1124 E = RD->decls_end(); I != E; ++I) {
1125 Decl *D = *I;
1126 if (D->isImplicit() && !D->isUsed())
1127 continue;
1128
1129 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1130 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1131 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1132 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1133 SE = FTD->spec_end(); SI != SE; ++SI)
1134 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1135 RecordTy));
1136 }
Eric Christopher6537f082013-05-16 00:45:12 +00001137}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001138
1139/// CollectCXXFriends - A helper function to collect debug info for
1140/// C++ base classes. This is used while creating debug info entry for
1141/// a Record.
1142void CGDebugInfo::
1143CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1144 SmallVectorImpl<llvm::Value *> &EltTys,
1145 llvm::DIType RecordTy) {
1146 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1147 BE = RD->friend_end(); BI != BE; ++BI) {
1148 if ((*BI)->isUnsupportedFriend())
1149 continue;
1150 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001151 EltTys.push_back(DBuilder.createFriend(RecordTy,
1152 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001153 Unit)));
1154 }
1155}
1156
1157/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001158/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001159/// a Record.
1160void CGDebugInfo::
1161CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1162 SmallVectorImpl<llvm::Value *> &EltTys,
1163 llvm::DIType RecordTy) {
1164
1165 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1166 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1167 BE = RD->bases_end(); BI != BE; ++BI) {
1168 unsigned BFlags = 0;
1169 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001170
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001171 const CXXRecordDecl *Base =
1172 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001173
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001174 if (BI->isVirtual()) {
1175 // virtual base offset offset is -ve. The code generator emits dwarf
1176 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001177 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001178 0 - CGM.getVTableContext()
1179 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1180 BFlags = llvm::DIDescriptor::FlagVirtual;
1181 } else
1182 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1183 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1184 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001185
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001186 AccessSpecifier Access = BI->getAccessSpecifier();
1187 if (Access == clang::AS_private)
1188 BFlags |= llvm::DIDescriptor::FlagPrivate;
1189 else if (Access == clang::AS_protected)
1190 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001191
1192 llvm::DIType DTy =
1193 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001194 getOrCreateType(BI->getType(), Unit),
1195 BaseOffset, BFlags);
1196 EltTys.push_back(DTy);
1197 }
1198}
1199
1200/// CollectTemplateParams - A helper function to collect template parameters.
1201llvm::DIArray CGDebugInfo::
1202CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001203 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001204 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001205 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001206 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1207 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001208 StringRef Name;
1209 if (TPList)
1210 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001211 switch (TA.getKind()) {
1212 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001213 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1214 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001215 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001216 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001217 } break;
1218 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001219 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1220 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001221 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001222 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001223 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1224 TemplateParams.push_back(TVP);
1225 } break;
1226 case TemplateArgument::Declaration: {
1227 const ValueDecl *D = TA.getAsDecl();
1228 bool InstanceMember = D->isCXXInstanceMember();
1229 QualType T = InstanceMember
1230 ? CGM.getContext().getMemberPointerType(
1231 D->getType(), cast<RecordDecl>(D->getDeclContext())
1232 ->getTypeForDecl())
1233 : CGM.getContext().getPointerType(D->getType());
1234 llvm::DIType TTy = getOrCreateType(T, Unit);
1235 llvm::Value *V = 0;
1236 // Variable pointer template parameters have a value that is the address
1237 // of the variable.
1238 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1239 V = CGM.GetAddrOfGlobalVar(VD);
1240 // Member function pointers have special support for building them, though
1241 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001242 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001243 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1244 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001245 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1246 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001247 // Member data pointers have special handling too to compute the fixed
1248 // offset within the object.
1249 if (isa<FieldDecl>(D)) {
1250 // These five lines (& possibly the above member function pointer
1251 // handling) might be able to be refactored to use similar code in
1252 // CodeGenModule::getMemberPointerConstant
1253 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1254 CharUnits chars =
1255 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1256 V = CGM.getCXXABI().EmitMemberDataPointer(
1257 cast<MemberPointerType>(T.getTypePtr()), chars);
1258 }
1259 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001260 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001261 TemplateParams.push_back(TVP);
1262 } break;
1263 case TemplateArgument::NullPtr: {
1264 QualType T = TA.getNullPtrType();
1265 llvm::DIType TTy = getOrCreateType(T, Unit);
1266 llvm::Value *V = 0;
1267 // Special case member data pointer null values since they're actually -1
1268 // instead of zero.
1269 if (const MemberPointerType *MPT =
1270 dyn_cast<MemberPointerType>(T.getTypePtr()))
1271 // But treat member function pointers as simple zero integers because
1272 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1273 // CodeGen grows handling for values of non-null member function
1274 // pointers then perhaps we could remove this special case and rely on
1275 // EmitNullMemberPointer for member function pointers.
1276 if (MPT->isMemberDataPointer())
1277 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1278 if (!V)
1279 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1280 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001281 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001282 TemplateParams.push_back(TVP);
1283 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001284 case TemplateArgument::Template: {
1285 llvm::DITemplateValueParameter TVP =
1286 DBuilder.createTemplateTemplateParameter(
1287 TheCU, Name, llvm::DIType(),
1288 TA.getAsTemplate().getAsTemplateDecl()
1289 ->getQualifiedNameAsString());
1290 TemplateParams.push_back(TVP);
1291 } break;
1292 case TemplateArgument::Pack: {
1293 llvm::DITemplateValueParameter TVP =
1294 DBuilder.createTemplateParameterPack(
1295 TheCU, Name, llvm::DIType(),
1296 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1297 TemplateParams.push_back(TVP);
1298 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001299 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001300 case TemplateArgument::Expression:
1301 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001302 case TemplateArgument::Null:
1303 llvm_unreachable(
1304 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001305 }
1306 }
1307 return DBuilder.getOrCreateArray(TemplateParams);
1308}
1309
1310/// CollectFunctionTemplateParams - A helper function to collect debug
1311/// info for function template parameters.
1312llvm::DIArray CGDebugInfo::
1313CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1314 if (FD->getTemplatedKind() ==
1315 FunctionDecl::TK_FunctionTemplateSpecialization) {
1316 const TemplateParameterList *TList =
1317 FD->getTemplateSpecializationInfo()->getTemplate()
1318 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001319 return CollectTemplateParams(
1320 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001321 }
1322 return llvm::DIArray();
1323}
1324
1325/// CollectCXXTemplateParams - A helper function to collect debug info for
1326/// template parameters.
1327llvm::DIArray CGDebugInfo::
1328CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1329 llvm::DIFile Unit) {
1330 llvm::PointerUnion<ClassTemplateDecl *,
1331 ClassTemplatePartialSpecializationDecl *>
1332 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001333
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001334 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1335 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1336 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1337 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001338 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001339}
1340
1341/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1342llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1343 if (VTablePtrType.isValid())
1344 return VTablePtrType;
1345
1346 ASTContext &Context = CGM.getContext();
1347
1348 /* Function type */
1349 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1350 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1351 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1352 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1353 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1354 "__vtbl_ptr_type");
1355 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1356 return VTablePtrType;
1357}
1358
1359/// getVTableName - Get vtable name for the given Class.
1360StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1361 // Construct gdb compatible name name.
1362 std::string Name = "_vptr$" + RD->getNameAsString();
1363
1364 // Copy this name on the side and use its reference.
1365 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1366 memcpy(StrPtr, Name.data(), Name.length());
1367 return StringRef(StrPtr, Name.length());
1368}
1369
1370
1371/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1372/// debug info entry in EltTys vector.
1373void CGDebugInfo::
1374CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1375 SmallVectorImpl<llvm::Value *> &EltTys) {
1376 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1377
1378 // If there is a primary base then it will hold vtable info.
1379 if (RL.getPrimaryBase())
1380 return;
1381
1382 // If this class is not dynamic then there is not any vtable info to collect.
1383 if (!RD->isDynamicClass())
1384 return;
1385
1386 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1387 llvm::DIType VPTR
1388 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001389 0, Size, 0, 0,
1390 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001391 getOrCreateVTablePtrType(Unit));
1392 EltTys.push_back(VPTR);
1393}
1394
Eric Christopher6537f082013-05-16 00:45:12 +00001395/// getOrCreateRecordType - Emit record type's standalone debug info.
1396llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001397 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001398 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001399 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1400 return T;
1401}
1402
1403/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1404/// debug info.
1405llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001406 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001407 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001408 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001409 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001410 return T;
1411}
1412
1413/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001414llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001415 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001416 // Limited debug info should only remove struct definitions that can
1417 // safely be replaced by a forward declaration in the source code.
David Blaikie658cd2c2013-07-13 21:08:14 +00001418 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
1419 !RD->isCompleteDefinitionRequired()) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001420 // FIXME: This implementation is problematic; there are some test
1421 // cases where we violate the above principle, such as
1422 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001423 llvm::DIDescriptor FDContext =
1424 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1425 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1426 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1427 return RetTy;
1428 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001429
1430 // Get overall information about the record type for the debug info.
1431 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1432
1433 // Records and classes and unions can all be recursive. To handle them, we
1434 // first generate a debug descriptor for the struct as a forward declaration.
1435 // Then (if it is a definition) we go through and get debug info for all of
1436 // its members. Finally, we create a descriptor for the complete type (which
1437 // may refer to the forward decl if the struct is recursive) and replace all
1438 // uses of the forward declaration with the final definition.
1439
Eric Christopherf068c922013-04-02 22:59:11 +00001440 llvm::DICompositeType FwdDecl(
1441 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001442 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001443 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001444
1445 if (FwdDecl.isForwardDecl())
1446 return FwdDecl;
1447
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001448 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001449 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001450 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1451
Adrian Prantl4919de62013-03-06 22:03:30 +00001452 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001453 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1454
1455 // Convert all the elements.
1456 SmallVector<llvm::Value *, 16> EltTys;
1457
1458 // Note: The split of CXXDecl information here is intentional, the
1459 // gdb tests will depend on a certain ordering at printout. The debug
1460 // information offsets are still correct if we merge them all together
1461 // though.
1462 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1463 if (CXXDecl) {
1464 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1465 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1466 }
1467
Eric Christopher0395de32013-01-16 01:22:32 +00001468 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001469 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1470 llvm::DIArray TParamsArray;
1471 if (CXXDecl) {
1472 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1473 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1474 if (const ClassTemplateSpecializationDecl *TSpecial
1475 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1476 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1477 }
1478
1479 LexicalBlockStack.pop_back();
1480 RegionMap.erase(Ty->getDecl());
1481
1482 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001483 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001484
Eric Christopherf068c922013-04-02 22:59:11 +00001485 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1486 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001487}
1488
1489/// CreateType - get objective-c object type.
1490llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1491 llvm::DIFile Unit) {
1492 // Ignore protocols.
1493 return getOrCreateType(Ty->getBaseType(), Unit);
1494}
1495
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001496
1497/// \return true if Getter has the default name for the property PD.
1498static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1499 const ObjCMethodDecl *Getter) {
1500 assert(PD);
1501 if (!Getter)
1502 return true;
1503
1504 assert(Getter->getDeclName().isObjCZeroArgSelector());
1505 return PD->getName() ==
1506 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1507}
1508
1509/// \return true if Setter has the default name for the property PD.
1510static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1511 const ObjCMethodDecl *Setter) {
1512 assert(PD);
1513 if (!Setter)
1514 return true;
1515
1516 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001517 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001518 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1519}
1520
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001521/// CreateType - get objective-c interface type.
1522llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1523 llvm::DIFile Unit) {
1524 ObjCInterfaceDecl *ID = Ty->getDecl();
1525 if (!ID)
1526 return llvm::DIType();
1527
1528 // Get overall information about the record type for the debug info.
1529 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1530 unsigned Line = getLineNumber(ID->getLocation());
1531 unsigned RuntimeLang = TheCU.getLanguage();
1532
1533 // If this is just a forward declaration return a special forward-declaration
1534 // debug type since we won't be able to lay out the entire type.
1535 ObjCInterfaceDecl *Def = ID->getDefinition();
1536 if (!Def) {
1537 llvm::DIType FwdDecl =
1538 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001539 ID->getName(), TheCU, DefUnit, Line,
1540 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001541 return FwdDecl;
1542 }
1543
1544 ID = Def;
1545
1546 // Bit size, align and offset of the type.
1547 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1548 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1549
1550 unsigned Flags = 0;
1551 if (ID->getImplementation())
1552 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1553
Eric Christopherf068c922013-04-02 22:59:11 +00001554 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001555 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1556 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001557 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001558
1559 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1560 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001561 QualType QualTy = QualType(Ty, 0);
1562 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001563
Eric Christopherd3003dc2013-07-14 21:00:07 +00001564 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001565 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001566 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1567
1568 // Convert all the elements.
1569 SmallVector<llvm::Value *, 16> EltTys;
1570
1571 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1572 if (SClass) {
1573 llvm::DIType SClassTy =
1574 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1575 if (!SClassTy.isValid())
1576 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001577
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001578 llvm::DIType InhTag =
1579 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1580 EltTys.push_back(InhTag);
1581 }
1582
Eric Christopherd3003dc2013-07-14 21:00:07 +00001583 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001584 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1585 E = ID->prop_end(); I != E; ++I) {
1586 const ObjCPropertyDecl *PD = *I;
1587 SourceLocation Loc = PD->getLocation();
1588 llvm::DIFile PUnit = getOrCreateFile(Loc);
1589 unsigned PLine = getLineNumber(Loc);
1590 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1591 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1592 llvm::MDNode *PropertyNode =
1593 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001594 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001595 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001596 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001597 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001598 getSelectorName(PD->getSetterName()),
1599 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001600 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001601 EltTys.push_back(PropertyNode);
1602 }
1603
1604 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1605 unsigned FieldNo = 0;
1606 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1607 Field = Field->getNextIvar(), ++FieldNo) {
1608 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1609 if (!FieldTy.isValid())
1610 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001611
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001612 StringRef FieldName = Field->getName();
1613
1614 // Ignore unnamed fields.
1615 if (FieldName.empty())
1616 continue;
1617
1618 // Get the location for the field.
1619 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1620 unsigned FieldLine = getLineNumber(Field->getLocation());
1621 QualType FType = Field->getType();
1622 uint64_t FieldSize = 0;
1623 unsigned FieldAlign = 0;
1624
1625 if (!FType->isIncompleteArrayType()) {
1626
1627 // Bit size, align and offset of the type.
1628 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001629 ? Field->getBitWidthValue(CGM.getContext())
1630 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001631 FieldAlign = CGM.getContext().getTypeAlign(FType);
1632 }
1633
1634 uint64_t FieldOffset;
1635 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1636 // We don't know the runtime offset of an ivar if we're using the
1637 // non-fragile ABI. For bitfields, use the bit offset into the first
1638 // byte of storage of the bitfield. For other fields, use zero.
1639 if (Field->isBitField()) {
1640 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1641 CGM, ID, Field);
1642 FieldOffset %= CGM.getContext().getCharWidth();
1643 } else {
1644 FieldOffset = 0;
1645 }
1646 } else {
1647 FieldOffset = RL.getFieldOffset(FieldNo);
1648 }
1649
1650 unsigned Flags = 0;
1651 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1652 Flags = llvm::DIDescriptor::FlagProtected;
1653 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1654 Flags = llvm::DIDescriptor::FlagPrivate;
1655
1656 llvm::MDNode *PropertyNode = NULL;
1657 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001658 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001659 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1660 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001661 SourceLocation Loc = PD->getLocation();
1662 llvm::DIFile PUnit = getOrCreateFile(Loc);
1663 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001664 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1665 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1666 PropertyNode =
1667 DBuilder.createObjCProperty(PD->getName(),
1668 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001669 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001670 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001671 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001672 getSelectorName(PD->getSetterName()),
1673 PD->getPropertyAttributes(),
1674 getOrCreateType(PD->getType(), PUnit));
1675 }
1676 }
1677 }
1678 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1679 FieldLine, FieldSize, FieldAlign,
1680 FieldOffset, Flags, FieldTy,
1681 PropertyNode);
1682 EltTys.push_back(FieldTy);
1683 }
1684
1685 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001686 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001687
1688 // If the implementation is not yet set, we do not want to mark it
1689 // as complete. An implementation may declare additional
1690 // private ivars that we would miss otherwise.
1691 if (ID->getImplementation() == 0)
1692 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001693
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001694 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001695 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001696}
1697
1698llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1699 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1700 int64_t Count = Ty->getNumElements();
1701 if (Count == 0)
1702 // If number of elements are not known then this is an unbounded array.
1703 // Use Count == -1 to express such arrays.
1704 Count = -1;
1705
1706 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1707 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1708
1709 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1710 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1711
1712 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1713}
1714
1715llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1716 llvm::DIFile Unit) {
1717 uint64_t Size;
1718 uint64_t Align;
1719
1720 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1721 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1722 Size = 0;
1723 Align =
1724 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1725 } else if (Ty->isIncompleteArrayType()) {
1726 Size = 0;
1727 if (Ty->getElementType()->isIncompleteType())
1728 Align = 0;
1729 else
1730 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001731 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001732 Size = 0;
1733 Align = 0;
1734 } else {
1735 // Size and align of the whole array, not the element type.
1736 Size = CGM.getContext().getTypeSize(Ty);
1737 Align = CGM.getContext().getTypeAlign(Ty);
1738 }
1739
1740 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1741 // interior arrays, do we care? Why aren't nested arrays represented the
1742 // obvious/recursive way?
1743 SmallVector<llvm::Value *, 8> Subscripts;
1744 QualType EltTy(Ty, 0);
1745 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1746 // If the number of elements is known, then count is that number. Otherwise,
1747 // it's -1. This allows us to represent a subrange with an array of 0
1748 // elements, like this:
1749 //
1750 // struct foo {
1751 // int x[0];
1752 // };
1753 int64_t Count = -1; // Count == -1 is an unbounded array.
1754 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1755 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001756
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001757 // FIXME: Verify this is right for VLAs.
1758 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1759 EltTy = Ty->getElementType();
1760 }
1761
1762 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1763
Eric Christopher6537f082013-05-16 00:45:12 +00001764 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001765 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1766 SubscriptArray);
1767 return DbgTy;
1768}
1769
Eric Christopher6537f082013-05-16 00:45:12 +00001770llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001771 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001772 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001773 Ty, Ty->getPointeeType(), Unit);
1774}
1775
Eric Christopher6537f082013-05-16 00:45:12 +00001776llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001777 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001778 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001779 Ty, Ty->getPointeeType(), Unit);
1780}
1781
Eric Christopher6537f082013-05-16 00:45:12 +00001782llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001783 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001784 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1785 if (!Ty->getPointeeType()->isFunctionType())
1786 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001787 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001788 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1789 CGM.getContext().getPointerType(
1790 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1791 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1792 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001793}
1794
Eric Christopher6537f082013-05-16 00:45:12 +00001795llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001796 llvm::DIFile U) {
1797 // Ignore the atomic wrapping
1798 // FIXME: What is the correct representation?
1799 return getOrCreateType(Ty->getValueType(), U);
1800}
1801
1802/// CreateEnumType - get enumeration type.
1803llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1804 uint64_t Size = 0;
1805 uint64_t Align = 0;
1806 if (!ED->getTypeForDecl()->isIncompleteType()) {
1807 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1808 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1809 }
1810
1811 // If this is just a forward declaration, construct an appropriately
1812 // marked node and just return it.
1813 if (!ED->getDefinition()) {
1814 llvm::DIDescriptor EDContext;
1815 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1816 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1817 unsigned Line = getLineNumber(ED->getLocation());
1818 StringRef EDName = ED->getName();
1819 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1820 EDName, EDContext, DefUnit, Line, 0,
1821 Size, Align);
1822 }
1823
1824 // Create DIEnumerator elements for each enumerator.
1825 SmallVector<llvm::Value *, 16> Enumerators;
1826 ED = ED->getDefinition();
1827 for (EnumDecl::enumerator_iterator
1828 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1829 Enum != EnumEnd; ++Enum) {
1830 Enumerators.push_back(
1831 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001832 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001833 }
1834
1835 // Return a CompositeType for the enum itself.
1836 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1837
1838 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1839 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001840 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001842 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001843 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001844 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001845 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1846 Size, Align, EltArray,
1847 ClassTy);
1848 return DbgTy;
1849}
1850
David Blaikie4b12be62013-01-21 04:37:12 +00001851static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1852 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001853 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001854 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001855 QualType LastT = T;
1856 switch (T->getTypeClass()) {
1857 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001858 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001859 case Type::TemplateSpecialization:
1860 T = cast<TemplateSpecializationType>(T)->desugar();
1861 break;
1862 case Type::TypeOfExpr:
1863 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1864 break;
1865 case Type::TypeOf:
1866 T = cast<TypeOfType>(T)->getUnderlyingType();
1867 break;
1868 case Type::Decltype:
1869 T = cast<DecltypeType>(T)->getUnderlyingType();
1870 break;
1871 case Type::UnaryTransform:
1872 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1873 break;
1874 case Type::Attributed:
1875 T = cast<AttributedType>(T)->getEquivalentType();
1876 break;
1877 case Type::Elaborated:
1878 T = cast<ElaboratedType>(T)->getNamedType();
1879 break;
1880 case Type::Paren:
1881 T = cast<ParenType>(T)->getInnerType();
1882 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001883 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001884 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001885 break;
1886 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001887 QualType DT = cast<AutoType>(T)->getDeducedType();
1888 if (DT.isNull())
1889 return T;
1890 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001891 break;
1892 }
Eric Christopher6537f082013-05-16 00:45:12 +00001893
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001894 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001895 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001896 } while (true);
1897}
1898
Eric Christopherf0890c42013-05-16 00:52:20 +00001899/// getType - Get the type from the cache or return null type if it doesn't
1900/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001901llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1902
1903 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001904 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001905
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001906 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001907 if (Ty->getTypeClass() == Type::ObjCInterface) {
1908 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1909 if (V)
1910 return llvm::DIType(cast<llvm::MDNode>(V));
1911 else return llvm::DIType();
1912 }
1913
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001914 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1915 TypeCache.find(Ty.getAsOpaquePtr());
1916 if (it != TypeCache.end()) {
1917 // Verify that the debug info still exists.
1918 if (llvm::Value *V = it->second)
1919 return llvm::DIType(cast<llvm::MDNode>(V));
1920 }
1921
1922 return llvm::DIType();
1923}
1924
1925/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1926/// doesn't exist.
1927llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1928
1929 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001930 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001931
1932 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001933 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001934 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1935 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001936 if (it != CompletedTypeCache.end())
1937 V = it->second;
1938 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001939 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001940 }
1941
Adrian Prantl4919de62013-03-06 22:03:30 +00001942 // Verify that any cached debug info still exists.
David Blaikieeab6a362013-06-21 00:40:50 +00001943 if (V != 0)
1944 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantl4919de62013-03-06 22:03:30 +00001945
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001946 return llvm::DIType();
1947}
1948
David Blaikieeab6a362013-06-21 00:40:50 +00001949void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1950 // In limited debug info we only want to do this if the complete type was
1951 // required.
1952 if (DebugKind <= CodeGenOptions::LimitedDebugInfo)
1953 return;
1954
David Blaikie076f51f2013-06-21 00:59:44 +00001955 QualType QTy = CGM.getContext().getRecordType(&RD);
1956 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieeab6a362013-06-21 00:40:50 +00001957
Eric Christopherb2d13922013-07-18 00:52:50 +00001958 if (T && T.isForwardDecl())
David Blaikie076f51f2013-06-21 00:59:44 +00001959 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieeab6a362013-06-21 00:40:50 +00001960}
1961
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001962/// getCachedInterfaceTypeOrNull - Get the type from the interface
1963/// cache, unless it needs to regenerated. Otherwise return null.
1964llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1965 // Is there a cached interface that hasn't changed?
1966 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1967 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1968
1969 if (it1 != ObjCInterfaceCache.end())
1970 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1971 if (Checksum(Decl) == it1->second.second)
1972 // Return cached forward declaration.
1973 return it1->second.first;
1974
1975 return 0;
1976}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001977
1978/// getOrCreateType - Get the type from the cache or create a new
1979/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001980llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1981 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001982 if (Ty.isNull())
1983 return llvm::DIType();
1984
1985 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001986 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001987
1988 llvm::DIType T = getCompletedTypeOrNull(Ty);
1989
Eric Christopherb2d13922013-07-18 00:52:50 +00001990 if (T) {
David Blaikief0c31d92013-06-21 21:03:11 +00001991 // If we're looking for a definition, make sure we have definitions of any
1992 // underlying types.
1993 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1994 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1995 if (Ty.hasLocalQualifiers())
1996 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001997 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00001998 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001999
2000 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00002001 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002002 void* TyPtr = Ty.getAsOpaquePtr();
2003
2004 // And update the type cache.
2005 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002006
2007 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002008 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002009 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2010 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2011 // Interface types may have elements added to them by a
2012 // subsequent implementation or extension, so we keep them in
2013 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002014 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002015 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002016 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2017 if (V.first)
2018 return llvm::DIType(cast<llvm::MDNode>(V.first));
2019 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2020 Decl->getName(), TheCU, Unit,
2021 getLineNumber(Decl->getLocation()),
2022 TheCU.getLanguage());
2023 // Store the forward declaration in the cache.
2024 V.first = TC;
2025 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002026
David Blaikiee2eb89a2013-05-21 18:29:40 +00002027 // Register the type for replacement in finalize().
2028 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2029
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002030 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002031 }
2032
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002033 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002034 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002035
2036 return Res;
2037}
2038
Adrian Prantlb5a50072013-06-07 01:10:41 +00002039/// Currently the checksum of an interface includes the number of
2040/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002041unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002042 // The assumption is that the number of ivars can only increase
2043 // monotonically, so it is safe to just use their current number as
2044 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002045 unsigned Sum = 0;
2046 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2047 Ivar != 0; Ivar = Ivar->getNextIvar())
2048 ++Sum;
2049
2050 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002051}
2052
2053ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2054 switch (Ty->getTypeClass()) {
2055 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002056 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2057 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002058 case Type::ObjCInterface:
2059 return cast<ObjCInterfaceType>(Ty)->getDecl();
2060 default:
2061 return 0;
2062 }
2063}
2064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002065/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002066llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2067 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068 // Handle qualifiers, which recursively handles what they refer to.
2069 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002070 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002071
2072 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002073
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002074 // Work out details of type.
2075 switch (Ty->getTypeClass()) {
2076#define TYPE(Class, Base)
2077#define ABSTRACT_TYPE(Class, Base)
2078#define NON_CANONICAL_TYPE(Class, Base)
2079#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2080#include "clang/AST/TypeNodes.def"
2081 llvm_unreachable("Dependent types cannot show up in debug information");
2082
2083 case Type::ExtVector:
2084 case Type::Vector:
2085 return CreateType(cast<VectorType>(Ty), Unit);
2086 case Type::ObjCObjectPointer:
2087 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2088 case Type::ObjCObject:
2089 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2090 case Type::ObjCInterface:
2091 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2092 case Type::Builtin:
2093 return CreateType(cast<BuiltinType>(Ty));
2094 case Type::Complex:
2095 return CreateType(cast<ComplexType>(Ty));
2096 case Type::Pointer:
2097 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002098 case Type::Decayed:
2099 // Decayed types are just pointers in LLVM and DWARF.
2100 return CreateType(
2101 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002102 case Type::BlockPointer:
2103 return CreateType(cast<BlockPointerType>(Ty), Unit);
2104 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002105 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002106 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002107 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002108 case Type::Enum:
2109 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2110 case Type::FunctionProto:
2111 case Type::FunctionNoProto:
2112 return CreateType(cast<FunctionType>(Ty), Unit);
2113 case Type::ConstantArray:
2114 case Type::VariableArray:
2115 case Type::IncompleteArray:
2116 return CreateType(cast<ArrayType>(Ty), Unit);
2117
2118 case Type::LValueReference:
2119 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2120 case Type::RValueReference:
2121 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2122
2123 case Type::MemberPointer:
2124 return CreateType(cast<MemberPointerType>(Ty), Unit);
2125
2126 case Type::Atomic:
2127 return CreateType(cast<AtomicType>(Ty), Unit);
2128
2129 case Type::Attributed:
2130 case Type::TemplateSpecialization:
2131 case Type::Elaborated:
2132 case Type::Paren:
2133 case Type::SubstTemplateTypeParm:
2134 case Type::TypeOfExpr:
2135 case Type::TypeOf:
2136 case Type::Decltype:
2137 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002138 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002139 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002140 case Type::Auto:
2141 Diag = "auto";
2142 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002143 }
Eric Christopher6537f082013-05-16 00:45:12 +00002144
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002145 assert(Diag && "Fall through without a diagnostic?");
2146 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2147 "debug information for %0 is not yet supported");
2148 CGM.getDiags().Report(DiagID)
2149 << Diag;
2150 return llvm::DIType();
2151}
2152
2153/// getOrCreateLimitedType - Get the type from the cache or create a new
2154/// limited type if necessary.
2155llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002156 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002157 if (Ty.isNull())
2158 return llvm::DIType();
2159
2160 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002161 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002162
2163 llvm::DIType T = getTypeOrNull(Ty);
2164
2165 // We may have cached a forward decl when we could have created
2166 // a non-forward decl. Go ahead and create a non-forward decl
2167 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002168 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002169
2170 // Otherwise create the type.
2171 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2172
Eric Christopherb2d13922013-07-18 00:52:50 +00002173 if (T && T.isForwardDecl())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002174 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2175 static_cast<llvm::Value*>(T)));
2176
2177 // And update the type cache.
2178 TypeCache[Ty.getAsOpaquePtr()] = Res;
2179 return Res;
2180}
2181
2182// TODO: Currently used for context chains when limiting debug info.
2183llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2184 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002185
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002186 // Get overall information about the record type for the debug info.
2187 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2188 unsigned Line = getLineNumber(RD->getLocation());
2189 StringRef RDName = getClassName(RD);
2190
2191 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002192 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002193 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2194 else
2195 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2196
2197 // If this is just a forward declaration, construct an appropriately
2198 // marked node and just return it.
2199 if (!RD->getDefinition())
2200 return createRecordFwdDecl(RD, RDContext);
2201
2202 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2203 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2204 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002205 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002206
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002207 if (RD->isUnion())
2208 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002209 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002210 else if (RD->isClass()) {
2211 // FIXME: This could be a struct type giving a default visibility different
2212 // than C++ class type, but needs llvm metadata changes first.
2213 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002214 Size, Align, 0, 0, llvm::DIType(),
2215 llvm::DIArray(), llvm::DIType(),
2216 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002217 } else
2218 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002219 Size, Align, 0, llvm::DIType(),
2220 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002221
2222 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002223 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002224
2225 if (CXXDecl) {
2226 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002227 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002228 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2229 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2230 // Seek non virtual primary base root.
2231 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002232 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2233 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2234 if (PBT && !BRL.isPrimaryBaseVirtual())
2235 PBase = PBT;
2236 else
2237 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002238 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002239 ContainingType = llvm::DICompositeType(
2240 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2241 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002242 ContainingType = RealDecl;
2243
David Blaikie2fcadbe2013-03-26 23:47:35 +00002244 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002245 }
2246 return llvm::DIType(RealDecl);
2247}
2248
2249/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2250/// declare composite types that haven't been processed yet.
2251llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2252
2253 // Work out details of type.
2254 switch (Ty->getTypeClass()) {
2255#define TYPE(Class, Base)
2256#define ABSTRACT_TYPE(Class, Base)
2257#define NON_CANONICAL_TYPE(Class, Base)
2258#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2259 #include "clang/AST/TypeNodes.def"
2260 llvm_unreachable("Dependent types cannot show up in debug information");
2261
2262 case Type::Record:
2263 return CreateLimitedType(cast<RecordType>(Ty));
2264 default:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002265 return CreateTypeNode(Ty, Unit, false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002266 }
2267}
2268
2269/// CreateMemberType - Create new member and increase Offset by FType's size.
2270llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2271 StringRef Name,
2272 uint64_t *Offset) {
2273 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2274 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2275 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2276 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2277 FieldSize, FieldAlign,
2278 *Offset, 0, FieldTy);
2279 *Offset += FieldSize;
2280 return Ty;
2281}
2282
David Blaikie9faebd22013-05-20 04:58:53 +00002283llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2284 // We only need a declaration (not a definition) of the type - so use whatever
2285 // we would otherwise do to get a type for a pointee. (forward declarations in
2286 // limited debug info, full definitions (if the type definition is available)
2287 // in unlimited debug info)
2288 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2289 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002290 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2291 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002292 }
2293 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2294 // This doesn't handle providing declarations (for functions or variables) for
2295 // entities without definitions in this TU, nor when the definition proceeds
2296 // the call to this function.
2297 // FIXME: This should be split out into more specific maps with support for
2298 // emitting forward declarations and merging definitions with declarations,
2299 // the same way as we do for types.
2300 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2301 DeclCache.find(D->getCanonicalDecl());
2302 if (I == DeclCache.end())
2303 return llvm::DIDescriptor();
2304 llvm::Value *V = I->second;
2305 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2306}
2307
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002308/// getFunctionDeclaration - Return debug info descriptor to describe method
2309/// declaration for the given method definition.
2310llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002311 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2312 return llvm::DISubprogram();
2313
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002314 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2315 if (!FD) return llvm::DISubprogram();
2316
2317 // Setup context.
2318 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2319
2320 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2321 MI = SPCache.find(FD->getCanonicalDecl());
2322 if (MI != SPCache.end()) {
2323 llvm::Value *V = MI->second;
2324 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002325 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002326 return SP;
2327 }
2328
2329 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2330 E = FD->redecls_end(); I != E; ++I) {
2331 const FunctionDecl *NextFD = *I;
2332 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2333 MI = SPCache.find(NextFD->getCanonicalDecl());
2334 if (MI != SPCache.end()) {
2335 llvm::Value *V = MI->second;
2336 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002337 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002338 return SP;
2339 }
2340 }
2341 return llvm::DISubprogram();
2342}
2343
2344// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2345// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002346llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2347 QualType FnType,
2348 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002349 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2350 // Create fake but valid subroutine type. Otherwise
2351 // llvm::DISubprogram::Verify() would return false, and
2352 // subprogram DIE will miss DW_AT_decl_file and
2353 // DW_AT_decl_line fields.
2354 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002355
2356 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2357 return getOrCreateMethodType(Method, F);
2358 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2359 // Add "self" and "_cmd"
2360 SmallVector<llvm::Value *, 16> Elts;
2361
2362 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002363 QualType ResultTy = OMethod->getResultType();
2364
2365 // Replace the instancetype keyword with the actual type.
2366 if (ResultTy == CGM.getContext().getObjCInstanceType())
2367 ResultTy = CGM.getContext().getPointerType(
2368 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2369
Adrian Prantl566a9c32013-05-10 21:08:31 +00002370 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002371 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002372 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2373 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2374 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002375 // "_cmd" pointer is always second argument.
2376 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2377 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2378 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002379 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002380 PE = OMethod->param_end(); PI != PE; ++PI)
2381 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2382
2383 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2384 return DBuilder.createSubroutineType(F, EltTypeArray);
2385 }
David Blaikie9a845292013-05-22 23:22:42 +00002386 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002387}
2388
2389/// EmitFunctionStart - Constructs the debug code for entering a function.
2390void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2391 llvm::Function *Fn,
2392 CGBuilderTy &Builder) {
2393
2394 StringRef Name;
2395 StringRef LinkageName;
2396
2397 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2398
2399 const Decl *D = GD.getDecl();
2400 // Function may lack declaration in source code if it is created by Clang
2401 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2402 bool HasDecl = (D != 0);
2403 // Use the location of the declaration.
2404 SourceLocation Loc;
2405 if (HasDecl)
2406 Loc = D->getLocation();
2407
2408 unsigned Flags = 0;
2409 llvm::DIFile Unit = getOrCreateFile(Loc);
2410 llvm::DIDescriptor FDContext(Unit);
2411 llvm::DIArray TParamsArray;
2412 if (!HasDecl) {
2413 // Use llvm function name.
2414 Name = Fn->getName();
2415 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2416 // If there is a DISubprogram for this function available then use it.
2417 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2418 FI = SPCache.find(FD->getCanonicalDecl());
2419 if (FI != SPCache.end()) {
2420 llvm::Value *V = FI->second;
2421 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2422 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2423 llvm::MDNode *SPN = SP;
2424 LexicalBlockStack.push_back(SPN);
2425 RegionMap[D] = llvm::WeakVH(SP);
2426 return;
2427 }
2428 }
2429 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002430 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002431 if (FD->hasPrototype()) {
2432 LinkageName = CGM.getMangledName(GD);
2433 Flags |= llvm::DIDescriptor::FlagPrototyped;
2434 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002435 // No need to replicate the linkage name if it isn't different from the
2436 // subprogram name, no need to have it at all unless coverage is enabled or
2437 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002438 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002439 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2440 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002441 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002442 LinkageName = StringRef();
2443
Eric Christopher13c97672013-05-16 00:45:23 +00002444 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002445 if (const NamespaceDecl *NSDecl =
2446 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2447 FDContext = getOrCreateNameSpace(NSDecl);
2448 else if (const RecordDecl *RDecl =
2449 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2450 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2451
2452 // Collect template parameters.
2453 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2454 }
2455 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2456 Name = getObjCMethodName(OMD);
2457 Flags |= llvm::DIDescriptor::FlagPrototyped;
2458 } else {
2459 // Use llvm function name.
2460 Name = Fn->getName();
2461 Flags |= llvm::DIDescriptor::FlagPrototyped;
2462 }
2463 if (!Name.empty() && Name[0] == '\01')
2464 Name = Name.substr(1);
2465
2466 unsigned LineNo = getLineNumber(Loc);
2467 if (!HasDecl || D->isImplicit())
2468 Flags |= llvm::DIDescriptor::FlagArtificial;
2469
David Blaikie23e66db2013-06-22 00:09:36 +00002470 llvm::DISubprogram SP = DBuilder.createFunction(
2471 FDContext, Name, LinkageName, Unit, LineNo,
2472 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2473 true /*definition*/, getLineNumber(CurLoc), Flags,
2474 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002475 if (HasDecl)
2476 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002477
2478 // Push function on region stack.
2479 llvm::MDNode *SPN = SP;
2480 LexicalBlockStack.push_back(SPN);
2481 if (HasDecl)
2482 RegionMap[D] = llvm::WeakVH(SP);
2483}
2484
2485/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002486/// information in the source file. If the location is invalid, the
2487/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002488void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2489 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002490 // Update our current location
2491 setLocation(Loc);
2492
2493 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2494
2495 // Don't bother if things are the same as last time.
2496 SourceManager &SM = CGM.getContext().getSourceManager();
2497 if (CurLoc == PrevLoc ||
2498 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2499 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002500 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2501 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2502 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002503 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002504
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002505 // Update last state.
2506 PrevLoc = CurLoc;
2507
2508 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002509 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2510 (getLineNumber(CurLoc),
2511 getColumnNumber(CurLoc, ForceColumnInfo),
2512 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002513}
2514
2515/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2516/// the stack.
2517void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2518 llvm::DIDescriptor D =
2519 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2520 llvm::DIDescriptor() :
2521 llvm::DIDescriptor(LexicalBlockStack.back()),
2522 getOrCreateFile(CurLoc),
2523 getLineNumber(CurLoc),
2524 getColumnNumber(CurLoc));
2525 llvm::MDNode *DN = D;
2526 LexicalBlockStack.push_back(DN);
2527}
2528
2529/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2530/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002531void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2532 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002533 // Set our current location.
2534 setLocation(Loc);
2535
2536 // Create a new lexical block and push it on the stack.
2537 CreateLexicalBlock(Loc);
2538
2539 // Emit a line table change for the current location inside the new scope.
2540 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2541 getColumnNumber(Loc),
2542 LexicalBlockStack.back()));
2543}
2544
2545/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2546/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002547void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2548 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002549 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2550
2551 // Provide an entry in the line table for the end of the block.
2552 EmitLocation(Builder, Loc);
2553
2554 LexicalBlockStack.pop_back();
2555}
2556
2557/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2558void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2559 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2560 unsigned RCount = FnBeginRegionCount.back();
2561 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2562
2563 // Pop all regions for this function.
2564 while (LexicalBlockStack.size() != RCount)
2565 EmitLexicalBlockEnd(Builder, CurLoc);
2566 FnBeginRegionCount.pop_back();
2567}
2568
Eric Christopher6537f082013-05-16 00:45:12 +00002569// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002570// See BuildByRefType.
2571llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2572 uint64_t *XOffset) {
2573
2574 SmallVector<llvm::Value *, 5> EltTys;
2575 QualType FType;
2576 uint64_t FieldSize, FieldOffset;
2577 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002578
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002579 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002580 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002581
2582 FieldOffset = 0;
2583 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2584 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2585 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2586 FType = CGM.getContext().IntTy;
2587 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2588 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2589
2590 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2591 if (HasCopyAndDispose) {
2592 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2593 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2594 &FieldOffset));
2595 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2596 &FieldOffset));
2597 }
2598 bool HasByrefExtendedLayout;
2599 Qualifiers::ObjCLifetime Lifetime;
2600 if (CGM.getContext().getByrefLifetime(Type,
2601 Lifetime, HasByrefExtendedLayout)
2602 && HasByrefExtendedLayout)
2603 EltTys.push_back(CreateMemberType(Unit, FType,
2604 "__byref_variable_layout",
2605 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002606
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002607 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2608 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002609 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002610 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002611 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2612 CharUnits AlignedOffsetInBytes
2613 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2614 CharUnits NumPaddingBytes
2615 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002616
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 if (NumPaddingBytes.isPositive()) {
2618 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2619 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2620 pad, ArrayType::Normal, 0);
2621 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2622 }
2623 }
Eric Christopher6537f082013-05-16 00:45:12 +00002624
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002625 FType = Type;
2626 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2627 FieldSize = CGM.getContext().getTypeSize(FType);
2628 FieldAlign = CGM.getContext().toBits(Align);
2629
Eric Christopher6537f082013-05-16 00:45:12 +00002630 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002631 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2632 0, FieldSize, FieldAlign,
2633 FieldOffset, 0, FieldTy);
2634 EltTys.push_back(FieldTy);
2635 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002636
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002637 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002638
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002639 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002640
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002641 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002642 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002643}
2644
2645/// EmitDeclare - Emit local variable declaration debug info.
2646void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002647 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002648 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002649 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002650 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2651
2652 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2653 llvm::DIType Ty;
2654 uint64_t XOffset = 0;
2655 if (VD->hasAttr<BlocksAttr>())
2656 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002657 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002658 Ty = getOrCreateType(VD->getType(), Unit);
2659
2660 // If there is no debug info for this type then do not emit debug info
2661 // for this variable.
2662 if (!Ty)
2663 return;
2664
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 // Get location information.
2666 unsigned Line = getLineNumber(VD->getLocation());
2667 unsigned Column = getColumnNumber(VD->getLocation());
2668 unsigned Flags = 0;
2669 if (VD->isImplicit())
2670 Flags |= llvm::DIDescriptor::FlagArtificial;
2671 // If this is the first argument and it is implicit then
2672 // give it an object pointer flag.
2673 // FIXME: There has to be a better way to do this, but for static
2674 // functions there won't be an implicit param at arg1 and
2675 // otherwise it is 'self' or 'this'.
2676 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2677 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002678 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002679 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2680 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002681 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002682
2683 llvm::MDNode *Scope = LexicalBlockStack.back();
2684
2685 StringRef Name = VD->getName();
2686 if (!Name.empty()) {
2687 if (VD->hasAttr<BlocksAttr>()) {
2688 CharUnits offset = CharUnits::fromQuantity(32);
2689 SmallVector<llvm::Value *, 9> addr;
2690 llvm::Type *Int64Ty = CGM.Int64Ty;
2691 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2692 // offset of __forwarding field
2693 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002694 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002695 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2696 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2697 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2698 // offset of x field
2699 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2700 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2701
2702 // Create the descriptor for the variable.
2703 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002704 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002705 llvm::DIDescriptor(Scope),
2706 VD->getName(), Unit, Line, Ty,
2707 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002708
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002709 // Insert an llvm.dbg.declare into the current block.
2710 llvm::Instruction *Call =
2711 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2712 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2713 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002714 }
David Blaikie436653b2013-01-05 05:58:35 +00002715 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2716 // If VD is an anonymous union then Storage represents value for
2717 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002718 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002719 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002720 for (RecordDecl::field_iterator I = RD->field_begin(),
2721 E = RD->field_end();
2722 I != E; ++I) {
2723 FieldDecl *Field = *I;
2724 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2725 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002726
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002727 // Ignore unnamed fields. Do not ignore unnamed records.
2728 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2729 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002730
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002731 // Use VarDecl's Tag, Scope and Line number.
2732 llvm::DIVariable D =
2733 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002734 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002735 CGM.getLangOpts().Optimize, Flags,
2736 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002737
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002738 // Insert an llvm.dbg.declare into the current block.
2739 llvm::Instruction *Call =
2740 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2741 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2742 }
David Blaikied8180cf2013-01-05 20:03:07 +00002743 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002744 }
2745 }
David Blaikie436653b2013-01-05 05:58:35 +00002746
2747 // Create the descriptor for the variable.
2748 llvm::DIVariable D =
2749 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2750 Name, Unit, Line, Ty,
2751 CGM.getLangOpts().Optimize, Flags, ArgNo);
2752
2753 // Insert an llvm.dbg.declare into the current block.
2754 llvm::Instruction *Call =
2755 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2756 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002757}
2758
2759void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2760 llvm::Value *Storage,
2761 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002762 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002763 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2764}
2765
Adrian Prantle86fcc42013-03-29 19:20:29 +00002766/// Look up the completed type for a self pointer in the TypeCache and
2767/// create a copy of it with the ObjectPointer and Artificial flags
2768/// set. If the type is not cached, a new one is created. This should
2769/// never happen though, since creating a type for the implicit self
2770/// argument implies that we already parsed the interface definition
2771/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002772llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2773 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002774 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002775 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002776 else DEBUG(llvm::dbgs() << "No cached type for self.");
2777 return DBuilder.createObjectPointerType(Ty);
2778}
2779
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002780void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2781 llvm::Value *Storage,
2782 CGBuilderTy &Builder,
2783 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002784 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002786
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002787 if (Builder.GetInsertBlock() == 0)
2788 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002789
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002790 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002791
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002792 uint64_t XOffset = 0;
2793 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2794 llvm::DIType Ty;
2795 if (isByRef)
2796 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002797 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002798 Ty = getOrCreateType(VD->getType(), Unit);
2799
2800 // Self is passed along as an implicit non-arg variable in a
2801 // block. Mark it as the object pointer.
2802 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002803 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002804
2805 // Get location information.
2806 unsigned Line = getLineNumber(VD->getLocation());
2807 unsigned Column = getColumnNumber(VD->getLocation());
2808
2809 const llvm::DataLayout &target = CGM.getDataLayout();
2810
2811 CharUnits offset = CharUnits::fromQuantity(
2812 target.getStructLayout(blockInfo.StructureType)
2813 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2814
2815 SmallVector<llvm::Value *, 9> addr;
2816 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002817 if (isa<llvm::AllocaInst>(Storage))
2818 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002819 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2820 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2821 if (isByRef) {
2822 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2823 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2824 // offset of __forwarding field
2825 offset = CGM.getContext()
2826 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2827 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2828 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2829 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2830 // offset of x field
2831 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2832 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2833 }
2834
2835 // Create the descriptor for the variable.
2836 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002837 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002838 llvm::DIDescriptor(LexicalBlockStack.back()),
2839 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002840
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002841 // Insert an llvm.dbg.declare into the current block.
2842 llvm::Instruction *Call =
2843 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2844 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2845 LexicalBlockStack.back()));
2846}
2847
2848/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2849/// variable declaration.
2850void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2851 unsigned ArgNo,
2852 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002853 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002854 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2855}
2856
2857namespace {
2858 struct BlockLayoutChunk {
2859 uint64_t OffsetInBits;
2860 const BlockDecl::Capture *Capture;
2861 };
2862 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2863 return l.OffsetInBits < r.OffsetInBits;
2864 }
2865}
2866
2867void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002868 llvm::Value *Arg,
2869 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002870 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002871 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002872 ASTContext &C = CGM.getContext();
2873 const BlockDecl *blockDecl = block.getBlockDecl();
2874
2875 // Collect some general information about the block's location.
2876 SourceLocation loc = blockDecl->getCaretLocation();
2877 llvm::DIFile tunit = getOrCreateFile(loc);
2878 unsigned line = getLineNumber(loc);
2879 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002880
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002881 // Build the debug-info type for the block literal.
2882 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2883
2884 const llvm::StructLayout *blockLayout =
2885 CGM.getDataLayout().getStructLayout(block.StructureType);
2886
2887 SmallVector<llvm::Value*, 16> fields;
2888 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2889 blockLayout->getElementOffsetInBits(0),
2890 tunit, tunit));
2891 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2892 blockLayout->getElementOffsetInBits(1),
2893 tunit, tunit));
2894 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2895 blockLayout->getElementOffsetInBits(2),
2896 tunit, tunit));
2897 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2898 blockLayout->getElementOffsetInBits(3),
2899 tunit, tunit));
2900 fields.push_back(createFieldType("__descriptor",
2901 C.getPointerType(block.NeedsCopyDispose ?
2902 C.getBlockDescriptorExtendedType() :
2903 C.getBlockDescriptorType()),
2904 0, loc, AS_public,
2905 blockLayout->getElementOffsetInBits(4),
2906 tunit, tunit));
2907
2908 // We want to sort the captures by offset, not because DWARF
2909 // requires this, but because we're paranoid about debuggers.
2910 SmallVector<BlockLayoutChunk, 8> chunks;
2911
2912 // 'this' capture.
2913 if (blockDecl->capturesCXXThis()) {
2914 BlockLayoutChunk chunk;
2915 chunk.OffsetInBits =
2916 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2917 chunk.Capture = 0;
2918 chunks.push_back(chunk);
2919 }
2920
2921 // Variable captures.
2922 for (BlockDecl::capture_const_iterator
2923 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2924 i != e; ++i) {
2925 const BlockDecl::Capture &capture = *i;
2926 const VarDecl *variable = capture.getVariable();
2927 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2928
2929 // Ignore constant captures.
2930 if (captureInfo.isConstant())
2931 continue;
2932
2933 BlockLayoutChunk chunk;
2934 chunk.OffsetInBits =
2935 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2936 chunk.Capture = &capture;
2937 chunks.push_back(chunk);
2938 }
2939
2940 // Sort by offset.
2941 llvm::array_pod_sort(chunks.begin(), chunks.end());
2942
2943 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2944 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2945 uint64_t offsetInBits = i->OffsetInBits;
2946 const BlockDecl::Capture *capture = i->Capture;
2947
2948 // If we have a null capture, this must be the C++ 'this' capture.
2949 if (!capture) {
2950 const CXXMethodDecl *method =
2951 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2952 QualType type = method->getThisType(C);
2953
2954 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2955 offsetInBits, tunit, tunit));
2956 continue;
2957 }
2958
2959 const VarDecl *variable = capture->getVariable();
2960 StringRef name = variable->getName();
2961
2962 llvm::DIType fieldType;
2963 if (capture->isByRef()) {
2964 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2965
2966 // FIXME: this creates a second copy of this type!
2967 uint64_t xoffset;
2968 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2969 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2970 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2971 ptrInfo.first, ptrInfo.second,
2972 offsetInBits, 0, fieldType);
2973 } else {
2974 fieldType = createFieldType(name, variable->getType(), 0,
2975 loc, AS_public, offsetInBits, tunit, tunit);
2976 }
2977 fields.push_back(fieldType);
2978 }
2979
2980 SmallString<36> typeName;
2981 llvm::raw_svector_ostream(typeName)
2982 << "__block_literal_" << CGM.getUniqueBlockCount();
2983
2984 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2985
2986 llvm::DIType type =
2987 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2988 CGM.getContext().toBits(block.BlockSize),
2989 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002990 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002991 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2992
2993 // Get overall information about the block.
2994 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2995 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002996
2997 // Create the descriptor for the parameter.
2998 llvm::DIVariable debugVar =
2999 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003000 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003001 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003002 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003003 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3004
Adrian Prantlbea407c2013-03-14 21:52:59 +00003005 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003006 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003007 llvm::Instruction *DbgVal =
3008 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003009 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003010 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3011 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003012
Adrian Prantlbea407c2013-03-14 21:52:59 +00003013 // Insert an llvm.dbg.declare into the current block.
3014 llvm::Instruction *DbgDecl =
3015 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3016 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003017}
3018
Eric Christopher0395de32013-01-16 01:22:32 +00003019/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
3020/// a static data member of a class, find its corresponding in-class
3021/// declaration.
3022llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
3023 if (cast<VarDecl>(D)->isStaticDataMember()) {
3024 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
3025 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3026 if (MI != StaticDataMemberCache.end())
3027 // Verify the info still exists.
3028 if (llvm::Value *V = MI->second)
3029 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
3030 }
3031 return llvm::DIDerivedType();
3032}
3033
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003034/// EmitGlobalVariable - Emit information about a global variable.
3035void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3036 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003037 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003038 // Create global variable debug descriptor.
3039 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3040 unsigned LineNo = getLineNumber(D->getLocation());
3041
3042 setLocation(D->getLocation());
3043
3044 QualType T = D->getType();
3045 if (T->isIncompleteArrayType()) {
3046
3047 // CodeGen turns int[] into int[1] so we'll do the same here.
3048 llvm::APInt ConstVal(32, 1);
3049 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3050
3051 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3052 ArrayType::Normal, 0);
3053 }
3054 StringRef DeclName = D->getName();
3055 StringRef LinkageName;
3056 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3057 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3058 LinkageName = Var->getName();
3059 if (LinkageName == DeclName)
3060 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003061 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003062 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003063 llvm::DIGlobalVariable GV =
3064 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3065 LineNo, getOrCreateType(T, Unit),
3066 Var->hasInternalLinkage(), Var,
3067 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003068 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003069}
3070
3071/// EmitGlobalVariable - Emit information about an objective-c interface.
3072void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3073 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003074 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003075 // Create global variable debug descriptor.
3076 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3077 unsigned LineNo = getLineNumber(ID->getLocation());
3078
3079 StringRef Name = ID->getName();
3080
3081 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3082 if (T->isIncompleteArrayType()) {
3083
3084 // CodeGen turns int[] into int[1] so we'll do the same here.
3085 llvm::APInt ConstVal(32, 1);
3086 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3087
3088 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3089 ArrayType::Normal, 0);
3090 }
3091
3092 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3093 getOrCreateType(T, Unit),
3094 Var->hasInternalLinkage(), Var);
3095}
3096
3097/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003098void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003099 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003100 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003101 // Create the descriptor for the variable.
3102 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3103 StringRef Name = VD->getName();
3104 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3105 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3106 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3107 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3108 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3109 }
3110 // Do not use DIGlobalVariable for enums.
3111 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3112 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003113 llvm::DIGlobalVariable GV =
3114 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3115 getLineNumber(VD->getLocation()), Ty, true,
3116 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003117 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3118}
3119
3120llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3121 if (!LexicalBlockStack.empty())
3122 return llvm::DIScope(LexicalBlockStack.back());
3123 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003124}
3125
David Blaikie957dac52013-04-22 06:13:21 +00003126void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003127 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3128 return;
David Blaikie957dac52013-04-22 06:13:21 +00003129 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003130 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3131 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003132 getLineNumber(UD.getLocation()));
3133}
3134
David Blaikie9faebd22013-05-20 04:58:53 +00003135void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3136 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3137 return;
3138 assert(UD.shadow_size() &&
3139 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3140 // Emitting one decl is sufficient - debuggers can detect that this is an
3141 // overloaded name & provide lookup for all the overloads.
3142 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003143 if (llvm::DIDescriptor Target =
3144 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003145 DBuilder.createImportedDeclaration(
3146 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3147 getLineNumber(USD.getLocation()));
3148}
3149
David Blaikiefc46ebc2013-05-20 22:50:41 +00003150llvm::DIImportedEntity
3151CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3152 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3153 return llvm::DIImportedEntity(0);
3154 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3155 if (VH)
3156 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3157 llvm::DIImportedEntity R(0);
3158 if (const NamespaceAliasDecl *Underlying =
3159 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3160 // This could cache & dedup here rather than relying on metadata deduping.
3161 R = DBuilder.createImportedModule(
3162 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3163 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3164 NA.getName());
3165 else
3166 R = DBuilder.createImportedModule(
3167 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3168 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3169 getLineNumber(NA.getLocation()), NA.getName());
3170 VH = R;
3171 return R;
3172}
3173
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003174/// getOrCreateNamesSpace - Return namespace descriptor for the given
3175/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003176llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003177CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003178 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003179 NameSpaceCache.find(NSDecl);
3180 if (I != NameSpaceCache.end())
3181 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003182
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003183 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3184 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003185 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003186 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3187 llvm::DINameSpace NS =
3188 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3189 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3190 return NS;
3191}
3192
3193void CGDebugInfo::finalize() {
3194 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3195 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3196 llvm::DIType Ty, RepTy;
3197 // Verify that the debug info still exists.
3198 if (llvm::Value *V = VI->second)
3199 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003200
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003201 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3202 TypeCache.find(VI->first);
3203 if (it != TypeCache.end()) {
3204 // Verify that the debug info still exists.
3205 if (llvm::Value *V = it->second)
3206 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3207 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003208
Eric Christopherb2d13922013-07-18 00:52:50 +00003209 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003210 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003211 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003212
3213 // We keep our own list of retained types, because we need to look
3214 // up the final type in the type cache.
3215 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3216 RE = RetainedTypes.end(); RI != RE; ++RI)
3217 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3218
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003219 DBuilder.finalize();
3220}