blob: 1d3bad9f6dd128d2d092c808313121e848fabdce [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();
Adrian Prantlb6cdc962013-07-24 20:34:39 +000075 DI->CurLoc = SourceLocation();
76 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
77 }
78}
79
80void ArtificialLocation::Emit() {
81 if (DI) {
Adrian Prantled6bbe42013-07-18 00:28:02 +000082 // Sync the Builder.
83 DI->EmitLocation(Builder, SavedLoc);
84 DI->CurLoc = SourceLocation();
85 // Construct a location that has a valid scope, but no line info.
Adrian Prantlb6cdc962013-07-24 20:34:39 +000086 assert(!DI->LexicalBlockStack.empty());
87 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000088 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
89 }
90}
91
Adrian Prantlb061ce22013-07-18 01:36:04 +000092ArtificialLocation::~ArtificialLocation() {
Adrian Prantled6bbe42013-07-18 00:28:02 +000093 if (DI) {
94 assert(Builder.getCurrentDebugLocation().getLine() == 0);
95 DI->CurLoc = SavedLoc;
96 }
97}
98
Guy Benyei7f92f2d2012-12-18 14:30:41 +000099void CGDebugInfo::setLocation(SourceLocation Loc) {
100 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +0000101 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000102
103 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
104
105 // If we've changed files in the middle of a lexical scope go ahead
106 // and create a new lexical scope with file node if it's different
107 // from the one in the scope.
108 if (LexicalBlockStack.empty()) return;
109
110 SourceManager &SM = CGM.getContext().getSourceManager();
111 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
112 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
113
114 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
115 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
116 return;
117
118 llvm::MDNode *LB = LexicalBlockStack.back();
119 llvm::DIScope Scope = llvm::DIScope(LB);
120 if (Scope.isLexicalBlockFile()) {
121 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
122 llvm::DIDescriptor D
123 = DBuilder.createLexicalBlockFile(LBF.getScope(),
124 getOrCreateFile(CurLoc));
125 llvm::MDNode *N = D;
126 LexicalBlockStack.pop_back();
127 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000128 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000129 llvm::DIDescriptor D
130 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
131 llvm::MDNode *N = D;
132 LexicalBlockStack.pop_back();
133 LexicalBlockStack.push_back(N);
134 }
135}
136
137/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000138llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000139 if (!Context)
140 return TheCU;
141
142 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
143 I = RegionMap.find(Context);
144 if (I != RegionMap.end()) {
145 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000146 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000147 }
148
149 // Check namespace.
150 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000151 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000152
David Blaikiebb000792013-04-19 06:56:38 +0000153 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
154 if (!RDecl->isDependentType())
155 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000156 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000157 return TheCU;
158}
159
160/// getFunctionName - Get function name for the given FunctionDecl. If the
161/// name is constructred on demand (e.g. C++ destructor) then the name
162/// is stored on the side.
163StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
164 assert (FD && "Invalid FunctionDecl!");
165 IdentifierInfo *FII = FD->getIdentifier();
166 FunctionTemplateSpecializationInfo *Info
167 = FD->getTemplateSpecializationInfo();
168 if (!Info && FII)
169 return FII->getName();
170
171 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000172 SmallString<128> NS;
173 llvm::raw_svector_ostream OS(NS);
174 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000175
176 // Add any template specialization args.
177 if (Info) {
178 const TemplateArgumentList *TArgs = Info->TemplateArguments;
179 const TemplateArgument *Args = TArgs->data();
180 unsigned NumArgs = TArgs->size();
181 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000182 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
183 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000184 }
185
186 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000187 OS.flush();
188 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
189 memcpy(StrPtr, NS.data(), NS.size());
190 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000191}
192
193StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
194 SmallString<256> MethodName;
195 llvm::raw_svector_ostream OS(MethodName);
196 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
197 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000198 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCImplementationDecl>(DC)) {
200 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000201 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000202 dyn_cast<const ObjCInterfaceDecl>(DC)) {
203 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000204 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000205 dyn_cast<const ObjCCategoryImplDecl>(DC)){
206 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
207 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000208 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000209 // We can extract the type of the class from the self pointer.
210 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
211 QualType ClassTy =
212 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
213 ClassTy.print(OS, PrintingPolicy(LangOptions()));
214 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000215 }
216 OS << ' ' << OMD->getSelector().getAsString() << ']';
217
218 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
219 memcpy(StrPtr, MethodName.begin(), OS.tell());
220 return StringRef(StrPtr, OS.tell());
221}
222
223/// getSelectorName - Return selector name. This is used for debugging
224/// info.
225StringRef CGDebugInfo::getSelectorName(Selector S) {
226 const std::string &SName = S.getAsString();
227 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
228 memcpy(StrPtr, SName.data(), SName.size());
229 return StringRef(StrPtr, SName.size());
230}
231
232/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000233StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000234CGDebugInfo::getClassName(const RecordDecl *RD) {
235 const ClassTemplateSpecializationDecl *Spec
236 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
237 if (!Spec)
238 return RD->getName();
239
240 const TemplateArgument *Args;
241 unsigned NumArgs;
242 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
243 const TemplateSpecializationType *TST =
244 cast<TemplateSpecializationType>(TAW->getType());
245 Args = TST->getArgs();
246 NumArgs = TST->getNumArgs();
247 } else {
248 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
249 Args = TemplateArgs.data();
250 NumArgs = TemplateArgs.size();
251 }
252 StringRef Name = RD->getIdentifier()->getName();
253 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000254 SmallString<128> TemplateArgList;
255 {
256 llvm::raw_svector_ostream OS(TemplateArgList);
257 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
258 Policy);
259 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000260
261 // Copy this name on the side and use its reference.
262 size_t Length = Name.size() + TemplateArgList.size();
263 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
264 memcpy(StrPtr, Name.data(), Name.size());
265 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
266 return StringRef(StrPtr, Length);
267}
268
269/// getOrCreateFile - Get the file debug info descriptor for the input location.
270llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
271 if (!Loc.isValid())
272 // If Location is not valid then use main input file.
273 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
274
275 SourceManager &SM = CGM.getContext().getSourceManager();
276 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
277
278 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
279 // If the location is not valid then use main input file.
280 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
281
282 // Cache the results.
283 const char *fname = PLoc.getFilename();
284 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
285 DIFileCache.find(fname);
286
287 if (it != DIFileCache.end()) {
288 // Verify that the information still exists.
289 if (llvm::Value *V = it->second)
290 return llvm::DIFile(cast<llvm::MDNode>(V));
291 }
292
293 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
294
295 DIFileCache[fname] = F;
296 return F;
297}
298
299/// getOrCreateMainFile - Get the file info for main compile unit.
300llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
301 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
302}
303
304/// getLineNumber - Get line number for the location. If location is invalid
305/// then use current location.
306unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
307 if (Loc.isInvalid() && CurLoc.isInvalid())
308 return 0;
309 SourceManager &SM = CGM.getContext().getSourceManager();
310 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
311 return PLoc.isValid()? PLoc.getLine() : 0;
312}
313
314/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000315unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000316 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000317 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000318 return 0;
319
320 // If the location is invalid then use the current column.
321 if (Loc.isInvalid() && CurLoc.isInvalid())
322 return 0;
323 SourceManager &SM = CGM.getContext().getSourceManager();
324 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
325 return PLoc.isValid()? PLoc.getColumn() : 0;
326}
327
328StringRef CGDebugInfo::getCurrentDirname() {
329 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
330 return CGM.getCodeGenOpts().DebugCompilationDir;
331
332 if (!CWDName.empty())
333 return CWDName;
334 SmallString<256> CWD;
335 llvm::sys::fs::current_path(CWD);
336 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
337 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
338 return CWDName = StringRef(CompDirnamePtr, CWD.size());
339}
340
341/// CreateCompileUnit - Create new compile unit.
342void CGDebugInfo::CreateCompileUnit() {
343
344 // Get absolute path name.
345 SourceManager &SM = CGM.getContext().getSourceManager();
346 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
347 if (MainFileName.empty())
348 MainFileName = "<unknown>";
349
350 // The main file name provided via the "-main-file-name" option contains just
351 // the file name itself with no path information. This file name may have had
352 // a relative path, so we look into the actual file entry for the main
353 // file to determine the real absolute path for the file.
354 std::string MainFileDir;
355 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
356 MainFileDir = MainFile->getDir()->getName();
357 if (MainFileDir != ".")
358 MainFileName = MainFileDir + "/" + MainFileName;
359 }
360
361 // Save filename string.
362 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
363 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
364 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000365
366 // Save split dwarf file string.
367 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
368 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
369 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
370 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000371
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000372 unsigned LangTag;
373 const LangOptions &LO = CGM.getLangOpts();
374 if (LO.CPlusPlus) {
375 if (LO.ObjC1)
376 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
377 else
378 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
379 } else if (LO.ObjC1) {
380 LangTag = llvm::dwarf::DW_LANG_ObjC;
381 } else if (LO.C99) {
382 LangTag = llvm::dwarf::DW_LANG_C99;
383 } else {
384 LangTag = llvm::dwarf::DW_LANG_C89;
385 }
386
387 std::string Producer = getClangFullVersion();
388
389 // Figure out which version of the ObjC runtime we have.
390 unsigned RuntimeVers = 0;
391 if (LO.ObjC1)
392 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
393
394 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000395 // FIXME - Eliminate TheCU.
Eric Christopher8fed3f42013-07-19 00:51:58 +0000396 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
397 Producer, LO.Optimize,
398 CGM.getCodeGenOpts().DwarfDebugFlags,
399 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000400}
401
402/// CreateType - Get the Basic type from the cache or create a new
403/// one if necessary.
404llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
405 unsigned Encoding = 0;
406 StringRef BTName;
407 switch (BT->getKind()) {
408#define BUILTIN_TYPE(Id, SingletonId)
409#define PLACEHOLDER_TYPE(Id, SingletonId) \
410 case BuiltinType::Id:
411#include "clang/AST/BuiltinTypes.def"
412 case BuiltinType::Dependent:
413 llvm_unreachable("Unexpected builtin type");
414 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000415 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000416 case BuiltinType::Void:
417 return llvm::DIType();
418 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000419 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000420 return ClassTy;
421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
422 "objc_class", TheCU,
423 getOrCreateMainFile(), 0);
424 return ClassTy;
425 case BuiltinType::ObjCId: {
426 // typedef struct objc_class *Class;
427 // typedef struct objc_object {
428 // Class isa;
429 // } *id;
430
Eric Christopherb2d13922013-07-18 00:52:50 +0000431 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000432 return ObjTy;
433
Eric Christopherb2d13922013-07-18 00:52:50 +0000434 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000435 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
436 "objc_class", TheCU,
437 getOrCreateMainFile(), 0);
438
439 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000440
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000441 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
442
Eric Christopherf068c922013-04-02 22:59:11 +0000443 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000444 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
445 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000446
Eric Christopherf068c922013-04-02 22:59:11 +0000447 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
448 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000449 return ObjTy;
450 }
451 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000452 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000453 return SelTy;
454 SelTy =
455 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
456 "objc_selector", TheCU, getOrCreateMainFile(),
457 0);
458 return SelTy;
459 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000460
461 case BuiltinType::OCLImage1d:
462 return getOrCreateStructPtrType("opencl_image1d_t",
463 OCLImage1dDITy);
464 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000465 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000466 OCLImage1dArrayDITy);
467 case BuiltinType::OCLImage1dBuffer:
468 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
469 OCLImage1dBufferDITy);
470 case BuiltinType::OCLImage2d:
471 return getOrCreateStructPtrType("opencl_image2d_t",
472 OCLImage2dDITy);
473 case BuiltinType::OCLImage2dArray:
474 return getOrCreateStructPtrType("opencl_image2d_array_t",
475 OCLImage2dArrayDITy);
476 case BuiltinType::OCLImage3d:
477 return getOrCreateStructPtrType("opencl_image3d_t",
478 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000479 case BuiltinType::OCLSampler:
480 return DBuilder.createBasicType("opencl_sampler_t",
481 CGM.getContext().getTypeSize(BT),
482 CGM.getContext().getTypeAlign(BT),
483 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000484 case BuiltinType::OCLEvent:
485 return getOrCreateStructPtrType("opencl_event_t",
486 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000487
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000488 case BuiltinType::UChar:
489 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
490 case BuiltinType::Char_S:
491 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
492 case BuiltinType::Char16:
493 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
494 case BuiltinType::UShort:
495 case BuiltinType::UInt:
496 case BuiltinType::UInt128:
497 case BuiltinType::ULong:
498 case BuiltinType::WChar_U:
499 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
500 case BuiltinType::Short:
501 case BuiltinType::Int:
502 case BuiltinType::Int128:
503 case BuiltinType::Long:
504 case BuiltinType::WChar_S:
505 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
506 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
507 case BuiltinType::Half:
508 case BuiltinType::Float:
509 case BuiltinType::LongDouble:
510 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
511 }
512
513 switch (BT->getKind()) {
514 case BuiltinType::Long: BTName = "long int"; break;
515 case BuiltinType::LongLong: BTName = "long long int"; break;
516 case BuiltinType::ULong: BTName = "long unsigned int"; break;
517 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
518 default:
519 BTName = BT->getName(CGM.getLangOpts());
520 break;
521 }
522 // Bit size, align and offset of the type.
523 uint64_t Size = CGM.getContext().getTypeSize(BT);
524 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000525 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000526 DBuilder.createBasicType(BTName, Size, Align, Encoding);
527 return DbgTy;
528}
529
530llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
531 // Bit size, align and offset of the type.
532 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
533 if (Ty->isComplexIntegerType())
534 Encoding = llvm::dwarf::DW_ATE_lo_user;
535
536 uint64_t Size = CGM.getContext().getTypeSize(Ty);
537 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000538 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000539 DBuilder.createBasicType("complex", Size, Align, Encoding);
540
541 return DbgTy;
542}
543
544/// CreateCVRType - Get the qualified type from the cache or create
545/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
547 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000548 QualifierCollector Qc;
549 const Type *T = Qc.strip(Ty);
550
551 // Ignore these qualifiers for now.
552 Qc.removeObjCGCAttr();
553 Qc.removeAddressSpace();
554 Qc.removeObjCLifetime();
555
556 // We will create one Derived type for one qualifier and recurse to handle any
557 // additional ones.
558 unsigned Tag;
559 if (Qc.hasConst()) {
560 Tag = llvm::dwarf::DW_TAG_const_type;
561 Qc.removeConst();
562 } else if (Qc.hasVolatile()) {
563 Tag = llvm::dwarf::DW_TAG_volatile_type;
564 Qc.removeVolatile();
565 } else if (Qc.hasRestrict()) {
566 Tag = llvm::dwarf::DW_TAG_restrict_type;
567 Qc.removeRestrict();
568 } else {
569 assert(Qc.empty() && "Unknown type qualifier for debug info");
570 return getOrCreateType(QualType(T, 0), Unit);
571 }
572
Eric Christopher56b108a2013-06-07 22:54:39 +0000573 llvm::DIType FromTy =
574 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000575
576 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
577 // CVR derived types.
578 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000579
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000580 return DbgTy;
581}
582
583llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
584 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000585
586 // The frontend treats 'id' as a typedef to an ObjCObjectType,
587 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
588 // debug info, we want to emit 'id' in both cases.
589 if (Ty->isObjCQualifiedIdType())
590 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
591
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000592 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000593 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000594 Ty->getPointeeType(), Unit);
595 return DbgTy;
596}
597
598llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
599 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000600 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000601 Ty->getPointeeType(), Unit);
602}
603
604// Creates a forward declaration for a RecordDecl in the given context.
605llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
606 llvm::DIDescriptor Ctx) {
607 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
608 unsigned Line = getLineNumber(RD->getLocation());
609 StringRef RDName = getClassName(RD);
610
611 unsigned Tag = 0;
612 if (RD->isStruct() || RD->isInterface())
613 Tag = llvm::dwarf::DW_TAG_structure_type;
614 else if (RD->isUnion())
615 Tag = llvm::dwarf::DW_TAG_union_type;
616 else {
617 assert(RD->isClass());
618 Tag = llvm::dwarf::DW_TAG_class_type;
619 }
620
621 // Create the type.
622 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
623}
624
625// Walk up the context chain and create forward decls for record decls,
626// and normal descriptors for namespaces.
627llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
628 if (!Context)
629 return TheCU;
630
631 // See if we already have the parent.
632 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
633 I = RegionMap.find(Context);
634 if (I != RegionMap.end()) {
635 llvm::Value *V = I->second;
636 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
637 }
Eric Christopher6537f082013-05-16 00:45:12 +0000638
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000639 // Check namespace.
640 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
641 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
642
643 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
644 if (!RD->isDependentType()) {
David Blaikie4a077162013-08-12 22:24:20 +0000645 llvm::DIType Ty = getOrCreateLimitedType(
646 CGM.getContext().getRecordType(RD)->castAs<RecordType>(), getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000647 return llvm::DIDescriptor(Ty);
648 }
649 }
650 return TheCU;
651}
652
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000654 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000655 QualType PointeeTy,
656 llvm::DIFile Unit) {
657 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
658 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000659 return DBuilder.createReferenceType(
David Blaikieb3c23772013-08-12 23:14:36 +0000660 Tag, getOrCreateType(PointeeTy, Unit, true));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000661
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000662 // Bit size, align and offset of the type.
663 // Size is always the size of a pointer. We can't use getTypeSize here
664 // because that does not return the correct value for references.
665 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000666 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000667 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
668
David Blaikieb3c23772013-08-12 23:14:36 +0000669 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit, true),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000670 Size, Align);
671}
672
Eric Christopherf0890c42013-05-16 00:52:20 +0000673llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
674 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000675 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000676 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000677 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
678 TheCU, getOrCreateMainFile(), 0);
679 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
680 Cache = DBuilder.createPointerType(Cache, Size);
681 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000682}
683
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000684llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
685 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000686 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000687 return BlockLiteralGeneric;
688
689 SmallVector<llvm::Value *, 8> EltTys;
690 llvm::DIType FieldTy;
691 QualType FType;
692 uint64_t FieldSize, FieldOffset;
693 unsigned FieldAlign;
694 llvm::DIArray Elements;
695 llvm::DIType EltTy, DescTy;
696
697 FieldOffset = 0;
698 FType = CGM.getContext().UnsignedLongTy;
699 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
700 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
701
702 Elements = DBuilder.getOrCreateArray(EltTys);
703 EltTys.clear();
704
705 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
706 unsigned LineNo = getLineNumber(CurLoc);
707
708 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
709 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000710 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000711
712 // Bit size, align and offset of the type.
713 uint64_t Size = CGM.getContext().getTypeSize(Ty);
714
715 DescTy = DBuilder.createPointerType(EltTy, Size);
716
717 FieldOffset = 0;
718 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
719 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
720 FType = CGM.getContext().IntTy;
721 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
722 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
723 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
724 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
725
726 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
727 FieldTy = DescTy;
728 FieldSize = CGM.getContext().getTypeSize(Ty);
729 FieldAlign = CGM.getContext().getTypeAlign(Ty);
730 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
731 LineNo, FieldSize, FieldAlign,
732 FieldOffset, 0, FieldTy);
733 EltTys.push_back(FieldTy);
734
735 FieldOffset += FieldSize;
736 Elements = DBuilder.getOrCreateArray(EltTys);
737
738 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
739 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000740 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000741
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000742 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
743 return BlockLiteralGeneric;
744}
745
David Blaikie5f6e2f42013-06-05 05:32:23 +0000746llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
747 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000748 // Typedefs are derived from some other type. If we have a typedef of a
749 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000750 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000751 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherb2d13922013-07-18 00:52:50 +0000752 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000753 return llvm::DIType();
754 // We don't set size information, but do specify where the typedef was
755 // declared.
756 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
757 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000758
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000759 llvm::DIDescriptor TypedefContext =
760 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000761
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000762 return
763 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
764}
765
766llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
767 llvm::DIFile Unit) {
768 SmallVector<llvm::Value *, 16> EltTys;
769
770 // Add the result type at least.
771 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
772
773 // Set up remainder of arguments if there is a prototype.
774 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
775 if (isa<FunctionNoProtoType>(Ty))
776 EltTys.push_back(DBuilder.createUnspecifiedParameter());
777 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
778 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
779 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
780 }
781
782 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
783 return DBuilder.createSubroutineType(Unit, EltTypeArray);
784}
785
786
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000787llvm::DIType CGDebugInfo::createFieldType(StringRef name,
788 QualType type,
789 uint64_t sizeInBitsOverride,
790 SourceLocation loc,
791 AccessSpecifier AS,
792 uint64_t offsetInBits,
793 llvm::DIFile tunit,
794 llvm::DIDescriptor scope) {
795 llvm::DIType debugType = getOrCreateType(type, tunit);
796
797 // Get the location for the field.
798 llvm::DIFile file = getOrCreateFile(loc);
799 unsigned line = getLineNumber(loc);
800
801 uint64_t sizeInBits = 0;
802 unsigned alignInBits = 0;
803 if (!type->isIncompleteArrayType()) {
804 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
805
806 if (sizeInBitsOverride)
807 sizeInBits = sizeInBitsOverride;
808 }
809
810 unsigned flags = 0;
811 if (AS == clang::AS_private)
812 flags |= llvm::DIDescriptor::FlagPrivate;
813 else if (AS == clang::AS_protected)
814 flags |= llvm::DIDescriptor::FlagProtected;
815
816 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
817 alignInBits, offsetInBits, flags, debugType);
818}
819
Eric Christopher0395de32013-01-16 01:22:32 +0000820/// CollectRecordLambdaFields - Helper for CollectRecordFields.
821void CGDebugInfo::
822CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
823 SmallVectorImpl<llvm::Value *> &elements,
824 llvm::DIType RecordTy) {
825 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
826 // has the name and the location of the variable so we should iterate over
827 // both concurrently.
828 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
829 RecordDecl::field_iterator Field = CXXDecl->field_begin();
830 unsigned fieldno = 0;
831 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
832 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
833 const LambdaExpr::Capture C = *I;
834 if (C.capturesVariable()) {
835 VarDecl *V = C.getCapturedVar();
836 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
837 StringRef VName = V->getName();
838 uint64_t SizeInBitsOverride = 0;
839 if (Field->isBitField()) {
840 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
841 assert(SizeInBitsOverride && "found named 0-width bitfield");
842 }
843 llvm::DIType fieldType
844 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
845 C.getLocation(), Field->getAccess(),
846 layout.getFieldOffset(fieldno), VUnit, RecordTy);
847 elements.push_back(fieldType);
848 } else {
849 // TODO: Need to handle 'this' in some way by probably renaming the
850 // this of the lambda class and having a field member of 'this' or
851 // by using AT_object_pointer for the function and having that be
852 // used as 'this' for semantic references.
853 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
854 FieldDecl *f = *Field;
855 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
856 QualType type = f->getType();
857 llvm::DIType fieldType
858 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
859 layout.getFieldOffset(fieldno), VUnit, RecordTy);
860
861 elements.push_back(fieldType);
862 }
863 }
864}
865
866/// CollectRecordStaticField - Helper for CollectRecordFields.
867void CGDebugInfo::
868CollectRecordStaticField(const VarDecl *Var,
869 SmallVectorImpl<llvm::Value *> &elements,
870 llvm::DIType RecordTy) {
871 // Create the descriptor for the static variable, with or without
872 // constant initializers.
873 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
874 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
875
876 // Do not describe enums as static members.
877 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
878 return;
879
880 unsigned LineNumber = getLineNumber(Var->getLocation());
881 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000882 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000883 if (Var->getInit()) {
884 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000885 if (Value) {
886 if (Value->isInt())
887 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
888 if (Value->isFloat())
889 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
890 }
Eric Christopher0395de32013-01-16 01:22:32 +0000891 }
892
893 unsigned Flags = 0;
894 AccessSpecifier Access = Var->getAccess();
895 if (Access == clang::AS_private)
896 Flags |= llvm::DIDescriptor::FlagPrivate;
897 else if (Access == clang::AS_protected)
898 Flags |= llvm::DIDescriptor::FlagProtected;
899
900 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000901 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000902 elements.push_back(GV);
903 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
904}
905
906/// CollectRecordNormalField - Helper for CollectRecordFields.
907void CGDebugInfo::
908CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
909 llvm::DIFile tunit,
910 SmallVectorImpl<llvm::Value *> &elements,
911 llvm::DIType RecordTy) {
912 StringRef name = field->getName();
913 QualType type = field->getType();
914
915 // Ignore unnamed fields unless they're anonymous structs/unions.
916 if (name.empty() && !type->isRecordType())
917 return;
918
919 uint64_t SizeInBitsOverride = 0;
920 if (field->isBitField()) {
921 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
922 assert(SizeInBitsOverride && "found named 0-width bitfield");
923 }
924
925 llvm::DIType fieldType
926 = createFieldType(name, type, SizeInBitsOverride,
927 field->getLocation(), field->getAccess(),
928 OffsetInBits, tunit, RecordTy);
929
930 elements.push_back(fieldType);
931}
932
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000933/// CollectRecordFields - A helper function to collect debug info for
934/// record fields. This is used while creating debug info entry for a Record.
935void CGDebugInfo::
936CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
937 SmallVectorImpl<llvm::Value *> &elements,
938 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000939 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
940
Eric Christopher0395de32013-01-16 01:22:32 +0000941 if (CXXDecl && CXXDecl->isLambda())
942 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
943 else {
944 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000945
Eric Christopher0395de32013-01-16 01:22:32 +0000946 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000947 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000948
Eric Christopher0395de32013-01-16 01:22:32 +0000949 // Static and non-static members should appear in the same order as
950 // the corresponding declarations in the source program.
951 for (RecordDecl::decl_iterator I = record->decls_begin(),
952 E = record->decls_end(); I != E; ++I)
953 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
954 CollectRecordStaticField(V, elements, RecordTy);
955 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000956 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
957 tunit, elements, RecordTy);
958
959 // Bump field number for next field.
960 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000961 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000962 }
963}
964
965/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
966/// function type is not updated to include implicit "this" pointer. Use this
967/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000968llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000969CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
970 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000971 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000972 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000973 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000974 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
975 Func, Unit);
976}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000977
David Blaikie9a845292013-05-22 23:22:42 +0000978llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000980 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000981 llvm::DIArray Args = llvm::DICompositeType(
982 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000983 assert (Args.getNumElements() && "Invalid number of arguments!");
984
985 SmallVector<llvm::Value *, 16> Elts;
986
987 // First element is always return type. For 'void' functions it is NULL.
988 Elts.push_back(Args.getElement(0));
989
David Blaikie67f8b5e2013-01-07 22:24:59 +0000990 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000991 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000992 if (isa<ClassTemplateSpecializationDecl>(RD)) {
993 // Create pointer type directly in this case.
994 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
995 QualType PointeeTy = ThisPtrTy->getPointeeType();
996 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000997 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000998 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
999 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001000 llvm::DIType ThisPtrType =
1001 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001002 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1003 // TODO: This and the artificial type below are misleading, the
1004 // types aren't artificial the argument is, but the current
1005 // metadata doesn't represent that.
1006 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1007 Elts.push_back(ThisPtrType);
1008 } else {
1009 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1010 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1011 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1012 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001013 }
1014
1015 // Copy rest of the arguments.
1016 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1017 Elts.push_back(Args.getElement(i));
1018
1019 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1020
1021 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1022}
1023
Eric Christopher6537f082013-05-16 00:45:12 +00001024/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001025/// inside a function.
1026static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1027 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1028 return isFunctionLocalClass(NRD);
1029 if (isa<FunctionDecl>(RD->getDeclContext()))
1030 return true;
1031 return false;
1032}
1033
1034/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1035/// a single member function GlobalDecl.
1036llvm::DISubprogram
1037CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1038 llvm::DIFile Unit,
1039 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001040 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001042
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001043 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001044 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001045
1046 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1047 // make sense to give a single ctor/dtor a linkage name.
1048 StringRef MethodLinkageName;
1049 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1050 MethodLinkageName = CGM.getMangledName(Method);
1051
1052 // Get the location for the method.
1053 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1054 unsigned MethodLine = getLineNumber(Method->getLocation());
1055
1056 // Collect virtual method info.
1057 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001058 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001059 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001060
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001061 if (Method->isVirtual()) {
1062 if (Method->isPure())
1063 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1064 else
1065 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001066
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001067 // It doesn't make sense to give a virtual destructor a vtable index,
1068 // since a single destructor has two entries in the vtable.
1069 if (!isa<CXXDestructorDecl>(Method))
1070 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1071 ContainingType = RecordTy;
1072 }
1073
1074 unsigned Flags = 0;
1075 if (Method->isImplicit())
1076 Flags |= llvm::DIDescriptor::FlagArtificial;
1077 AccessSpecifier Access = Method->getAccess();
1078 if (Access == clang::AS_private)
1079 Flags |= llvm::DIDescriptor::FlagPrivate;
1080 else if (Access == clang::AS_protected)
1081 Flags |= llvm::DIDescriptor::FlagProtected;
1082 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1083 if (CXXC->isExplicit())
1084 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001085 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001086 dyn_cast<CXXConversionDecl>(Method)) {
1087 if (CXXC->isExplicit())
1088 Flags |= llvm::DIDescriptor::FlagExplicit;
1089 }
1090 if (Method->hasPrototype())
1091 Flags |= llvm::DIDescriptor::FlagPrototyped;
1092
1093 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1094 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001095 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001096 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001097 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001098 /* isDefinition=*/ false,
1099 Virtuality, VIndex, ContainingType,
1100 Flags, CGM.getLangOpts().Optimize, NULL,
1101 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001102
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001103 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1104
1105 return SP;
1106}
1107
1108/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001109/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001110/// a Record.
1111void CGDebugInfo::
1112CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1113 SmallVectorImpl<llvm::Value *> &EltTys,
1114 llvm::DIType RecordTy) {
1115
1116 // Since we want more than just the individual member decls if we
1117 // have templated functions iterate over every declaration to gather
1118 // the functions.
1119 for(DeclContext::decl_iterator I = RD->decls_begin(),
1120 E = RD->decls_end(); I != E; ++I) {
1121 Decl *D = *I;
David Blaikied6d5d692013-08-09 17:20:05 +00001122 if (D->isImplicit())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001123 continue;
1124
1125 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1126 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001127 }
Eric Christopher6537f082013-05-16 00:45:12 +00001128}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001129
1130/// CollectCXXFriends - A helper function to collect debug info for
1131/// C++ base classes. This is used while creating debug info entry for
1132/// a Record.
1133void CGDebugInfo::
1134CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1135 SmallVectorImpl<llvm::Value *> &EltTys,
1136 llvm::DIType RecordTy) {
1137 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1138 BE = RD->friend_end(); BI != BE; ++BI) {
1139 if ((*BI)->isUnsupportedFriend())
1140 continue;
1141 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001142 EltTys.push_back(DBuilder.createFriend(RecordTy,
1143 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001144 Unit)));
1145 }
1146}
1147
1148/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001149/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001150/// a Record.
1151void CGDebugInfo::
1152CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1153 SmallVectorImpl<llvm::Value *> &EltTys,
1154 llvm::DIType RecordTy) {
1155
1156 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1157 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1158 BE = RD->bases_end(); BI != BE; ++BI) {
1159 unsigned BFlags = 0;
1160 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001161
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001162 const CXXRecordDecl *Base =
1163 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001164
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001165 if (BI->isVirtual()) {
1166 // virtual base offset offset is -ve. The code generator emits dwarf
1167 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001168 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001169 0 - CGM.getVTableContext()
1170 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1171 BFlags = llvm::DIDescriptor::FlagVirtual;
1172 } else
1173 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1174 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1175 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001176
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001177 AccessSpecifier Access = BI->getAccessSpecifier();
1178 if (Access == clang::AS_private)
1179 BFlags |= llvm::DIDescriptor::FlagPrivate;
1180 else if (Access == clang::AS_protected)
1181 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001182
1183 llvm::DIType DTy =
1184 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001185 getOrCreateType(BI->getType(), Unit),
1186 BaseOffset, BFlags);
1187 EltTys.push_back(DTy);
1188 }
1189}
1190
1191/// CollectTemplateParams - A helper function to collect template parameters.
1192llvm::DIArray CGDebugInfo::
1193CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001194 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001195 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001196 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001197 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1198 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001199 StringRef Name;
1200 if (TPList)
1201 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001202 switch (TA.getKind()) {
1203 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001204 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1205 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001206 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001207 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001208 } break;
1209 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001210 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1211 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001212 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001213 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001214 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1215 TemplateParams.push_back(TVP);
1216 } break;
1217 case TemplateArgument::Declaration: {
1218 const ValueDecl *D = TA.getAsDecl();
1219 bool InstanceMember = D->isCXXInstanceMember();
1220 QualType T = InstanceMember
1221 ? CGM.getContext().getMemberPointerType(
1222 D->getType(), cast<RecordDecl>(D->getDeclContext())
1223 ->getTypeForDecl())
1224 : CGM.getContext().getPointerType(D->getType());
1225 llvm::DIType TTy = getOrCreateType(T, Unit);
1226 llvm::Value *V = 0;
1227 // Variable pointer template parameters have a value that is the address
1228 // of the variable.
1229 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1230 V = CGM.GetAddrOfGlobalVar(VD);
1231 // Member function pointers have special support for building them, though
1232 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001233 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001234 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1235 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001236 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1237 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001238 // Member data pointers have special handling too to compute the fixed
1239 // offset within the object.
1240 if (isa<FieldDecl>(D)) {
1241 // These five lines (& possibly the above member function pointer
1242 // handling) might be able to be refactored to use similar code in
1243 // CodeGenModule::getMemberPointerConstant
1244 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1245 CharUnits chars =
1246 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1247 V = CGM.getCXXABI().EmitMemberDataPointer(
1248 cast<MemberPointerType>(T.getTypePtr()), chars);
1249 }
1250 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001251 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001252 TemplateParams.push_back(TVP);
1253 } break;
1254 case TemplateArgument::NullPtr: {
1255 QualType T = TA.getNullPtrType();
1256 llvm::DIType TTy = getOrCreateType(T, Unit);
1257 llvm::Value *V = 0;
1258 // Special case member data pointer null values since they're actually -1
1259 // instead of zero.
1260 if (const MemberPointerType *MPT =
1261 dyn_cast<MemberPointerType>(T.getTypePtr()))
1262 // But treat member function pointers as simple zero integers because
1263 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1264 // CodeGen grows handling for values of non-null member function
1265 // pointers then perhaps we could remove this special case and rely on
1266 // EmitNullMemberPointer for member function pointers.
1267 if (MPT->isMemberDataPointer())
1268 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1269 if (!V)
1270 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1271 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001272 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001273 TemplateParams.push_back(TVP);
1274 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001275 case TemplateArgument::Template: {
1276 llvm::DITemplateValueParameter TVP =
1277 DBuilder.createTemplateTemplateParameter(
1278 TheCU, Name, llvm::DIType(),
1279 TA.getAsTemplate().getAsTemplateDecl()
1280 ->getQualifiedNameAsString());
1281 TemplateParams.push_back(TVP);
1282 } break;
1283 case TemplateArgument::Pack: {
1284 llvm::DITemplateValueParameter TVP =
1285 DBuilder.createTemplateParameterPack(
1286 TheCU, Name, llvm::DIType(),
1287 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1288 TemplateParams.push_back(TVP);
1289 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001290 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001291 case TemplateArgument::Expression:
1292 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001293 case TemplateArgument::Null:
1294 llvm_unreachable(
1295 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001296 }
1297 }
1298 return DBuilder.getOrCreateArray(TemplateParams);
1299}
1300
1301/// CollectFunctionTemplateParams - A helper function to collect debug
1302/// info for function template parameters.
1303llvm::DIArray CGDebugInfo::
1304CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1305 if (FD->getTemplatedKind() ==
1306 FunctionDecl::TK_FunctionTemplateSpecialization) {
1307 const TemplateParameterList *TList =
1308 FD->getTemplateSpecializationInfo()->getTemplate()
1309 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001310 return CollectTemplateParams(
1311 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001312 }
1313 return llvm::DIArray();
1314}
1315
1316/// CollectCXXTemplateParams - A helper function to collect debug info for
1317/// template parameters.
1318llvm::DIArray CGDebugInfo::
1319CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1320 llvm::DIFile Unit) {
1321 llvm::PointerUnion<ClassTemplateDecl *,
1322 ClassTemplatePartialSpecializationDecl *>
1323 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001324
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001325 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1326 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1327 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1328 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001329 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001330}
1331
1332/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1333llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1334 if (VTablePtrType.isValid())
1335 return VTablePtrType;
1336
1337 ASTContext &Context = CGM.getContext();
1338
1339 /* Function type */
1340 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1341 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1342 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1343 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1344 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1345 "__vtbl_ptr_type");
1346 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1347 return VTablePtrType;
1348}
1349
1350/// getVTableName - Get vtable name for the given Class.
1351StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1352 // Construct gdb compatible name name.
1353 std::string Name = "_vptr$" + RD->getNameAsString();
1354
1355 // Copy this name on the side and use its reference.
1356 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1357 memcpy(StrPtr, Name.data(), Name.length());
1358 return StringRef(StrPtr, Name.length());
1359}
1360
1361
1362/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1363/// debug info entry in EltTys vector.
1364void CGDebugInfo::
1365CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1366 SmallVectorImpl<llvm::Value *> &EltTys) {
1367 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1368
1369 // If there is a primary base then it will hold vtable info.
1370 if (RL.getPrimaryBase())
1371 return;
1372
1373 // If this class is not dynamic then there is not any vtable info to collect.
1374 if (!RD->isDynamicClass())
1375 return;
1376
1377 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1378 llvm::DIType VPTR
1379 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001380 0, Size, 0, 0,
1381 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001382 getOrCreateVTablePtrType(Unit));
1383 EltTys.push_back(VPTR);
1384}
1385
Eric Christopher6537f082013-05-16 00:45:12 +00001386/// getOrCreateRecordType - Emit record type's standalone debug info.
1387llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001388 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001389 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001390 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1391 return T;
1392}
1393
1394/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1395/// debug info.
1396llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +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(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001400 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001401 return T;
1402}
1403
1404/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001405llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001406 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001407 // Limited debug info should only remove struct definitions that can
1408 // safely be replaced by a forward declaration in the source code.
David Blaikie658cd2c2013-07-13 21:08:14 +00001409 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
David Blaikieac00b792013-08-01 20:57:40 +00001410 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001411 // FIXME: This implementation is problematic; there are some test
1412 // cases where we violate the above principle, such as
1413 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001414 llvm::DIDescriptor FDContext =
1415 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1416 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1417 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1418 return RetTy;
1419 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001420
1421 // Get overall information about the record type for the debug info.
1422 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1423
1424 // Records and classes and unions can all be recursive. To handle them, we
1425 // first generate a debug descriptor for the struct as a forward declaration.
1426 // Then (if it is a definition) we go through and get debug info for all of
1427 // its members. Finally, we create a descriptor for the complete type (which
1428 // may refer to the forward decl if the struct is recursive) and replace all
1429 // uses of the forward declaration with the final definition.
1430
David Blaikie4a077162013-08-12 22:24:20 +00001431 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001432 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001433 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001434
1435 if (FwdDecl.isForwardDecl())
1436 return FwdDecl;
1437
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001438 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001439 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001440 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1441
Adrian Prantl4919de62013-03-06 22:03:30 +00001442 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001443 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1444
1445 // Convert all the elements.
1446 SmallVector<llvm::Value *, 16> EltTys;
1447
1448 // Note: The split of CXXDecl information here is intentional, the
1449 // gdb tests will depend on a certain ordering at printout. The debug
1450 // information offsets are still correct if we merge them all together
1451 // though.
1452 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1453 if (CXXDecl) {
1454 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1455 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1456 }
1457
Eric Christopher0395de32013-01-16 01:22:32 +00001458 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001459 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001460 if (CXXDecl) {
1461 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1462 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001463 }
1464
1465 LexicalBlockStack.pop_back();
1466 RegionMap.erase(Ty->getDecl());
1467
1468 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001469 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001470
Eric Christopherf068c922013-04-02 22:59:11 +00001471 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1472 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001473}
1474
1475/// CreateType - get objective-c object type.
1476llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1477 llvm::DIFile Unit) {
1478 // Ignore protocols.
1479 return getOrCreateType(Ty->getBaseType(), Unit);
1480}
1481
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001482
1483/// \return true if Getter has the default name for the property PD.
1484static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1485 const ObjCMethodDecl *Getter) {
1486 assert(PD);
1487 if (!Getter)
1488 return true;
1489
1490 assert(Getter->getDeclName().isObjCZeroArgSelector());
1491 return PD->getName() ==
1492 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1493}
1494
1495/// \return true if Setter has the default name for the property PD.
1496static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1497 const ObjCMethodDecl *Setter) {
1498 assert(PD);
1499 if (!Setter)
1500 return true;
1501
1502 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001503 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001504 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1505}
1506
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001507/// CreateType - get objective-c interface type.
1508llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1509 llvm::DIFile Unit) {
1510 ObjCInterfaceDecl *ID = Ty->getDecl();
1511 if (!ID)
1512 return llvm::DIType();
1513
1514 // Get overall information about the record type for the debug info.
1515 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1516 unsigned Line = getLineNumber(ID->getLocation());
1517 unsigned RuntimeLang = TheCU.getLanguage();
1518
1519 // If this is just a forward declaration return a special forward-declaration
1520 // debug type since we won't be able to lay out the entire type.
1521 ObjCInterfaceDecl *Def = ID->getDefinition();
1522 if (!Def) {
1523 llvm::DIType FwdDecl =
1524 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001525 ID->getName(), TheCU, DefUnit, Line,
1526 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001527 return FwdDecl;
1528 }
1529
1530 ID = Def;
1531
1532 // Bit size, align and offset of the type.
1533 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1534 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1535
1536 unsigned Flags = 0;
1537 if (ID->getImplementation())
1538 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1539
Eric Christopherf068c922013-04-02 22:59:11 +00001540 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001541 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1542 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001543 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001544
1545 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1546 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001547 QualType QualTy = QualType(Ty, 0);
1548 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001549
Eric Christopherd3003dc2013-07-14 21:00:07 +00001550 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001551 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001552 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1553
1554 // Convert all the elements.
1555 SmallVector<llvm::Value *, 16> EltTys;
1556
1557 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1558 if (SClass) {
1559 llvm::DIType SClassTy =
1560 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1561 if (!SClassTy.isValid())
1562 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001563
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001564 llvm::DIType InhTag =
1565 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1566 EltTys.push_back(InhTag);
1567 }
1568
Eric Christopherd3003dc2013-07-14 21:00:07 +00001569 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001570 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1571 E = ID->prop_end(); I != E; ++I) {
1572 const ObjCPropertyDecl *PD = *I;
1573 SourceLocation Loc = PD->getLocation();
1574 llvm::DIFile PUnit = getOrCreateFile(Loc);
1575 unsigned PLine = getLineNumber(Loc);
1576 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1577 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1578 llvm::MDNode *PropertyNode =
1579 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001580 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001581 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001582 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001583 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001584 getSelectorName(PD->getSetterName()),
1585 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001586 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001587 EltTys.push_back(PropertyNode);
1588 }
1589
1590 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1591 unsigned FieldNo = 0;
1592 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1593 Field = Field->getNextIvar(), ++FieldNo) {
1594 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1595 if (!FieldTy.isValid())
1596 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001597
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001598 StringRef FieldName = Field->getName();
1599
1600 // Ignore unnamed fields.
1601 if (FieldName.empty())
1602 continue;
1603
1604 // Get the location for the field.
1605 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1606 unsigned FieldLine = getLineNumber(Field->getLocation());
1607 QualType FType = Field->getType();
1608 uint64_t FieldSize = 0;
1609 unsigned FieldAlign = 0;
1610
1611 if (!FType->isIncompleteArrayType()) {
1612
1613 // Bit size, align and offset of the type.
1614 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001615 ? Field->getBitWidthValue(CGM.getContext())
1616 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001617 FieldAlign = CGM.getContext().getTypeAlign(FType);
1618 }
1619
1620 uint64_t FieldOffset;
1621 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1622 // We don't know the runtime offset of an ivar if we're using the
1623 // non-fragile ABI. For bitfields, use the bit offset into the first
1624 // byte of storage of the bitfield. For other fields, use zero.
1625 if (Field->isBitField()) {
1626 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1627 CGM, ID, Field);
1628 FieldOffset %= CGM.getContext().getCharWidth();
1629 } else {
1630 FieldOffset = 0;
1631 }
1632 } else {
1633 FieldOffset = RL.getFieldOffset(FieldNo);
1634 }
1635
1636 unsigned Flags = 0;
1637 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1638 Flags = llvm::DIDescriptor::FlagProtected;
1639 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1640 Flags = llvm::DIDescriptor::FlagPrivate;
1641
1642 llvm::MDNode *PropertyNode = NULL;
1643 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001644 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001645 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1646 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001647 SourceLocation Loc = PD->getLocation();
1648 llvm::DIFile PUnit = getOrCreateFile(Loc);
1649 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001650 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1651 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1652 PropertyNode =
1653 DBuilder.createObjCProperty(PD->getName(),
1654 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001655 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001656 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001657 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001658 getSelectorName(PD->getSetterName()),
1659 PD->getPropertyAttributes(),
1660 getOrCreateType(PD->getType(), PUnit));
1661 }
1662 }
1663 }
1664 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1665 FieldLine, FieldSize, FieldAlign,
1666 FieldOffset, Flags, FieldTy,
1667 PropertyNode);
1668 EltTys.push_back(FieldTy);
1669 }
1670
1671 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001672 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001673
1674 // If the implementation is not yet set, we do not want to mark it
1675 // as complete. An implementation may declare additional
1676 // private ivars that we would miss otherwise.
1677 if (ID->getImplementation() == 0)
1678 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001679
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001680 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001681 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001682}
1683
1684llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1685 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1686 int64_t Count = Ty->getNumElements();
1687 if (Count == 0)
1688 // If number of elements are not known then this is an unbounded array.
1689 // Use Count == -1 to express such arrays.
1690 Count = -1;
1691
1692 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1693 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1694
1695 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1696 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1697
1698 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1699}
1700
1701llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1702 llvm::DIFile Unit) {
1703 uint64_t Size;
1704 uint64_t Align;
1705
1706 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1707 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1708 Size = 0;
1709 Align =
1710 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1711 } else if (Ty->isIncompleteArrayType()) {
1712 Size = 0;
1713 if (Ty->getElementType()->isIncompleteType())
1714 Align = 0;
1715 else
1716 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001717 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001718 Size = 0;
1719 Align = 0;
1720 } else {
1721 // Size and align of the whole array, not the element type.
1722 Size = CGM.getContext().getTypeSize(Ty);
1723 Align = CGM.getContext().getTypeAlign(Ty);
1724 }
1725
1726 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1727 // interior arrays, do we care? Why aren't nested arrays represented the
1728 // obvious/recursive way?
1729 SmallVector<llvm::Value *, 8> Subscripts;
1730 QualType EltTy(Ty, 0);
1731 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1732 // If the number of elements is known, then count is that number. Otherwise,
1733 // it's -1. This allows us to represent a subrange with an array of 0
1734 // elements, like this:
1735 //
1736 // struct foo {
1737 // int x[0];
1738 // };
1739 int64_t Count = -1; // Count == -1 is an unbounded array.
1740 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1741 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001742
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001743 // FIXME: Verify this is right for VLAs.
1744 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1745 EltTy = Ty->getElementType();
1746 }
1747
1748 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1749
Eric Christopher6537f082013-05-16 00:45:12 +00001750 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001751 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1752 SubscriptArray);
1753 return DbgTy;
1754}
1755
Eric Christopher6537f082013-05-16 00:45:12 +00001756llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001757 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001758 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001759 Ty, Ty->getPointeeType(), Unit);
1760}
1761
Eric Christopher6537f082013-05-16 00:45:12 +00001762llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001763 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001764 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001765 Ty, Ty->getPointeeType(), Unit);
1766}
1767
Eric Christopher6537f082013-05-16 00:45:12 +00001768llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001769 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001770 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1771 if (!Ty->getPointeeType()->isFunctionType())
1772 return DBuilder.createMemberPointerType(
David Blaikieb3c23772013-08-12 23:14:36 +00001773 getOrCreateType(Ty->getPointeeType(), U, true), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001774 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1775 CGM.getContext().getPointerType(
1776 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1777 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1778 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001779}
1780
Eric Christopher6537f082013-05-16 00:45:12 +00001781llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001782 llvm::DIFile U) {
1783 // Ignore the atomic wrapping
1784 // FIXME: What is the correct representation?
1785 return getOrCreateType(Ty->getValueType(), U);
1786}
1787
1788/// CreateEnumType - get enumeration type.
1789llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1790 uint64_t Size = 0;
1791 uint64_t Align = 0;
1792 if (!ED->getTypeForDecl()->isIncompleteType()) {
1793 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1794 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1795 }
1796
1797 // If this is just a forward declaration, construct an appropriately
1798 // marked node and just return it.
1799 if (!ED->getDefinition()) {
1800 llvm::DIDescriptor EDContext;
1801 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1802 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1803 unsigned Line = getLineNumber(ED->getLocation());
1804 StringRef EDName = ED->getName();
1805 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1806 EDName, EDContext, DefUnit, Line, 0,
1807 Size, Align);
1808 }
1809
1810 // Create DIEnumerator elements for each enumerator.
1811 SmallVector<llvm::Value *, 16> Enumerators;
1812 ED = ED->getDefinition();
1813 for (EnumDecl::enumerator_iterator
1814 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1815 Enum != EnumEnd; ++Enum) {
1816 Enumerators.push_back(
1817 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001818 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001819 }
1820
1821 // Return a CompositeType for the enum itself.
1822 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1823
1824 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1825 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001826 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001827 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001828 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001830 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001831 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1832 Size, Align, EltArray,
1833 ClassTy);
1834 return DbgTy;
1835}
1836
David Blaikie4b12be62013-01-21 04:37:12 +00001837static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1838 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001840 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841 QualType LastT = T;
1842 switch (T->getTypeClass()) {
1843 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001844 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001845 case Type::TemplateSpecialization:
1846 T = cast<TemplateSpecializationType>(T)->desugar();
1847 break;
1848 case Type::TypeOfExpr:
1849 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1850 break;
1851 case Type::TypeOf:
1852 T = cast<TypeOfType>(T)->getUnderlyingType();
1853 break;
1854 case Type::Decltype:
1855 T = cast<DecltypeType>(T)->getUnderlyingType();
1856 break;
1857 case Type::UnaryTransform:
1858 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1859 break;
1860 case Type::Attributed:
1861 T = cast<AttributedType>(T)->getEquivalentType();
1862 break;
1863 case Type::Elaborated:
1864 T = cast<ElaboratedType>(T)->getNamedType();
1865 break;
1866 case Type::Paren:
1867 T = cast<ParenType>(T)->getInnerType();
1868 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001869 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001870 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871 break;
1872 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001873 QualType DT = cast<AutoType>(T)->getDeducedType();
1874 if (DT.isNull())
1875 return T;
1876 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001877 break;
1878 }
Eric Christopher6537f082013-05-16 00:45:12 +00001879
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001881 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001882 } while (true);
1883}
1884
Eric Christopherf0890c42013-05-16 00:52:20 +00001885/// getType - Get the type from the cache or return null type if it doesn't
1886/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001887llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1888
1889 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001890 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001891
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001893 if (Ty->getTypeClass() == Type::ObjCInterface) {
1894 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1895 if (V)
1896 return llvm::DIType(cast<llvm::MDNode>(V));
1897 else return llvm::DIType();
1898 }
1899
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001900 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1901 TypeCache.find(Ty.getAsOpaquePtr());
1902 if (it != TypeCache.end()) {
1903 // Verify that the debug info still exists.
1904 if (llvm::Value *V = it->second)
1905 return llvm::DIType(cast<llvm::MDNode>(V));
1906 }
1907
1908 return llvm::DIType();
1909}
1910
1911/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1912/// doesn't exist.
1913llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1914
1915 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001916 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001917
1918 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001919 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001920 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1921 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001922 if (it != CompletedTypeCache.end())
1923 V = it->second;
1924 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001925 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001926 }
1927
Adrian Prantl4919de62013-03-06 22:03:30 +00001928 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00001929 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001930}
1931
David Blaikieeab6a362013-06-21 00:40:50 +00001932void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1933 // In limited debug info we only want to do this if the complete type was
1934 // required.
David Blaikieac00b792013-08-01 20:57:40 +00001935 if (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1936 CGM.getLangOpts().CPlusPlus)
David Blaikieeab6a362013-06-21 00:40:50 +00001937 return;
1938
David Blaikie076f51f2013-06-21 00:59:44 +00001939 QualType QTy = CGM.getContext().getRecordType(&RD);
1940 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieeab6a362013-06-21 00:40:50 +00001941
Eric Christopherb2d13922013-07-18 00:52:50 +00001942 if (T && T.isForwardDecl())
David Blaikie076f51f2013-06-21 00:59:44 +00001943 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieeab6a362013-06-21 00:40:50 +00001944}
1945
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001946/// getCachedInterfaceTypeOrNull - Get the type from the interface
1947/// cache, unless it needs to regenerated. Otherwise return null.
1948llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1949 // Is there a cached interface that hasn't changed?
1950 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1951 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1952
1953 if (it1 != ObjCInterfaceCache.end())
1954 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1955 if (Checksum(Decl) == it1->second.second)
1956 // Return cached forward declaration.
1957 return it1->second.first;
1958
1959 return 0;
1960}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961
1962/// getOrCreateType - Get the type from the cache or create a new
1963/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001964llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1965 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001966 if (Ty.isNull())
1967 return llvm::DIType();
1968
1969 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001970 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001971
David Blaikie00383082013-08-13 04:21:38 +00001972 if (llvm::DIType T = getCompletedTypeOrNull(Ty)) {
David Blaikief0c31d92013-06-21 21:03:11 +00001973 // If we're looking for a definition, make sure we have definitions of any
1974 // underlying types.
1975 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1976 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1977 if (Ty.hasLocalQualifiers())
1978 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001979 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00001980 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001981
1982 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001983 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001984 void* TyPtr = Ty.getAsOpaquePtr();
1985
1986 // And update the type cache.
1987 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001988
1989 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00001990 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001991 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1992 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1993 // Interface types may have elements added to them by a
1994 // subsequent implementation or extension, so we keep them in
1995 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001996 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001997 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001998 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1999 if (V.first)
2000 return llvm::DIType(cast<llvm::MDNode>(V.first));
2001 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2002 Decl->getName(), TheCU, Unit,
2003 getLineNumber(Decl->getLocation()),
2004 TheCU.getLanguage());
2005 // Store the forward declaration in the cache.
2006 V.first = TC;
2007 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002008
David Blaikiee2eb89a2013-05-21 18:29:40 +00002009 // Register the type for replacement in finalize().
2010 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2011
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002012 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002013 }
2014
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002015 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002016 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002017
2018 return Res;
2019}
2020
Adrian Prantlb5a50072013-06-07 01:10:41 +00002021/// Currently the checksum of an interface includes the number of
2022/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002023unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002024 // The assumption is that the number of ivars can only increase
2025 // monotonically, so it is safe to just use their current number as
2026 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002027 unsigned Sum = 0;
2028 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2029 Ivar != 0; Ivar = Ivar->getNextIvar())
2030 ++Sum;
2031
2032 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002033}
2034
2035ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2036 switch (Ty->getTypeClass()) {
2037 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002038 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2039 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002040 case Type::ObjCInterface:
2041 return cast<ObjCInterfaceType>(Ty)->getDecl();
2042 default:
2043 return 0;
2044 }
2045}
2046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002048llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2049 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002050 // Handle qualifiers, which recursively handles what they refer to.
2051 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002052 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002053
2054 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002055
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002056 // Work out details of type.
2057 switch (Ty->getTypeClass()) {
2058#define TYPE(Class, Base)
2059#define ABSTRACT_TYPE(Class, Base)
2060#define NON_CANONICAL_TYPE(Class, Base)
2061#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2062#include "clang/AST/TypeNodes.def"
2063 llvm_unreachable("Dependent types cannot show up in debug information");
2064
2065 case Type::ExtVector:
2066 case Type::Vector:
2067 return CreateType(cast<VectorType>(Ty), Unit);
2068 case Type::ObjCObjectPointer:
2069 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2070 case Type::ObjCObject:
2071 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2072 case Type::ObjCInterface:
2073 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2074 case Type::Builtin:
2075 return CreateType(cast<BuiltinType>(Ty));
2076 case Type::Complex:
2077 return CreateType(cast<ComplexType>(Ty));
2078 case Type::Pointer:
2079 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002080 case Type::Decayed:
2081 // Decayed types are just pointers in LLVM and DWARF.
2082 return CreateType(
2083 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002084 case Type::BlockPointer:
2085 return CreateType(cast<BlockPointerType>(Ty), Unit);
2086 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002087 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002088 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002089 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002090 case Type::Enum:
2091 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2092 case Type::FunctionProto:
2093 case Type::FunctionNoProto:
2094 return CreateType(cast<FunctionType>(Ty), Unit);
2095 case Type::ConstantArray:
2096 case Type::VariableArray:
2097 case Type::IncompleteArray:
2098 return CreateType(cast<ArrayType>(Ty), Unit);
2099
2100 case Type::LValueReference:
2101 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2102 case Type::RValueReference:
2103 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2104
2105 case Type::MemberPointer:
2106 return CreateType(cast<MemberPointerType>(Ty), Unit);
2107
2108 case Type::Atomic:
2109 return CreateType(cast<AtomicType>(Ty), Unit);
2110
2111 case Type::Attributed:
2112 case Type::TemplateSpecialization:
2113 case Type::Elaborated:
2114 case Type::Paren:
2115 case Type::SubstTemplateTypeParm:
2116 case Type::TypeOfExpr:
2117 case Type::TypeOf:
2118 case Type::Decltype:
2119 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002120 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002121 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002122 case Type::Auto:
2123 Diag = "auto";
2124 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002125 }
Eric Christopher6537f082013-05-16 00:45:12 +00002126
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002127 assert(Diag && "Fall through without a diagnostic?");
2128 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2129 "debug information for %0 is not yet supported");
2130 CGM.getDiags().Report(DiagID)
2131 << Diag;
2132 return llvm::DIType();
2133}
2134
2135/// getOrCreateLimitedType - Get the type from the cache or create a new
2136/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002137llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002138 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002139 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002140
David Blaikie4a077162013-08-12 22:24:20 +00002141 llvm::DIType T = getTypeOrNull(QTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002142
2143 // We may have cached a forward decl when we could have created
2144 // a non-forward decl. Go ahead and create a non-forward decl
2145 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002146 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002147
2148 // Otherwise create the type.
David Blaikie4a077162013-08-12 22:24:20 +00002149 llvm::DIType Res = CreateLimitedType(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002150
Eric Christopherb2d13922013-07-18 00:52:50 +00002151 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002152 ReplaceMap.push_back(
2153 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002154
2155 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002156 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002157 return Res;
2158}
2159
2160// TODO: Currently used for context chains when limiting debug info.
2161llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2162 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002163
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002164 // Get overall information about the record type for the debug info.
2165 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2166 unsigned Line = getLineNumber(RD->getLocation());
2167 StringRef RDName = getClassName(RD);
2168
2169 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002170 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002171 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2172 else
2173 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2174
2175 // If this is just a forward declaration, construct an appropriately
2176 // marked node and just return it.
2177 if (!RD->getDefinition())
2178 return createRecordFwdDecl(RD, RDContext);
2179
2180 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2181 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002182 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002183
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002184 if (RD->isUnion())
2185 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002186 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002187 else if (RD->isClass()) {
2188 // FIXME: This could be a struct type giving a default visibility different
2189 // than C++ class type, but needs llvm metadata changes first.
2190 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002191 Size, Align, 0, 0, llvm::DIType(),
2192 llvm::DIArray(), llvm::DIType(),
2193 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002194 } else
2195 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002196 Size, Align, 0, llvm::DIType(),
2197 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002198
2199 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002200 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002201
David Blaikie841b37c2013-08-01 18:23:24 +00002202 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002203 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002204 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002205 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2206 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2207 // Seek non virtual primary base root.
2208 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002209 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2210 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2211 if (PBT && !BRL.isPrimaryBaseVirtual())
2212 PBase = PBT;
2213 else
2214 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002215 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002216 ContainingType = llvm::DICompositeType(
2217 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2218 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002219 ContainingType = RealDecl;
2220
David Blaikie2fcadbe2013-03-26 23:47:35 +00002221 RealDecl.setContainingType(ContainingType);
David Blaikie80588332013-08-01 20:31:40 +00002222 if (const ClassTemplateSpecializationDecl *TSpecial =
2223 dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2224 RealDecl.setTypeArray(llvm::DIArray(),
2225 CollectCXXTemplateParams(TSpecial, DefUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002226 }
2227 return llvm::DIType(RealDecl);
2228}
2229
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002230/// CreateMemberType - Create new member and increase Offset by FType's size.
2231llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2232 StringRef Name,
2233 uint64_t *Offset) {
2234 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2235 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2236 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2237 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2238 FieldSize, FieldAlign,
2239 *Offset, 0, FieldTy);
2240 *Offset += FieldSize;
2241 return Ty;
2242}
2243
David Blaikie9faebd22013-05-20 04:58:53 +00002244llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2245 // We only need a declaration (not a definition) of the type - so use whatever
2246 // we would otherwise do to get a type for a pointee. (forward declarations in
2247 // limited debug info, full definitions (if the type definition is available)
2248 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002249 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2250 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2251 getOrCreateFile(TD->getLocation()), true);
David Blaikie9faebd22013-05-20 04:58:53 +00002252 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2253 // This doesn't handle providing declarations (for functions or variables) for
2254 // entities without definitions in this TU, nor when the definition proceeds
2255 // the call to this function.
2256 // FIXME: This should be split out into more specific maps with support for
2257 // emitting forward declarations and merging definitions with declarations,
2258 // the same way as we do for types.
2259 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2260 DeclCache.find(D->getCanonicalDecl());
2261 if (I == DeclCache.end())
2262 return llvm::DIDescriptor();
2263 llvm::Value *V = I->second;
2264 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2265}
2266
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002267/// getFunctionDeclaration - Return debug info descriptor to describe method
2268/// declaration for the given method definition.
2269llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002270 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2271 return llvm::DISubprogram();
2272
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002273 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2274 if (!FD) return llvm::DISubprogram();
2275
2276 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002277 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002278
2279 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2280 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002281 if (MI == SPCache.end()) {
2282 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2283 llvm::DICompositeType T(S);
2284 llvm::DISubprogram SP = CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2285 T.addMember(SP);
2286 return SP;
2287 }
2288 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002289 if (MI != SPCache.end()) {
2290 llvm::Value *V = MI->second;
2291 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002292 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002293 return SP;
2294 }
2295
2296 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2297 E = FD->redecls_end(); I != E; ++I) {
2298 const FunctionDecl *NextFD = *I;
2299 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2300 MI = SPCache.find(NextFD->getCanonicalDecl());
2301 if (MI != SPCache.end()) {
2302 llvm::Value *V = MI->second;
2303 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002304 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002305 return SP;
2306 }
2307 }
2308 return llvm::DISubprogram();
2309}
2310
2311// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2312// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002313llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2314 QualType FnType,
2315 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002316 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2317 // Create fake but valid subroutine type. Otherwise
2318 // llvm::DISubprogram::Verify() would return false, and
2319 // subprogram DIE will miss DW_AT_decl_file and
2320 // DW_AT_decl_line fields.
2321 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002322
2323 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2324 return getOrCreateMethodType(Method, F);
2325 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2326 // Add "self" and "_cmd"
2327 SmallVector<llvm::Value *, 16> Elts;
2328
2329 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002330 QualType ResultTy = OMethod->getResultType();
2331
2332 // Replace the instancetype keyword with the actual type.
2333 if (ResultTy == CGM.getContext().getObjCInstanceType())
2334 ResultTy = CGM.getContext().getPointerType(
2335 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2336
Adrian Prantl566a9c32013-05-10 21:08:31 +00002337 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002338 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002339 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2340 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2341 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002342 // "_cmd" pointer is always second argument.
2343 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2344 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2345 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002346 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002347 PE = OMethod->param_end(); PI != PE; ++PI)
2348 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2349
2350 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2351 return DBuilder.createSubroutineType(F, EltTypeArray);
2352 }
David Blaikie9a845292013-05-22 23:22:42 +00002353 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002354}
2355
2356/// EmitFunctionStart - Constructs the debug code for entering a function.
2357void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2358 llvm::Function *Fn,
2359 CGBuilderTy &Builder) {
2360
2361 StringRef Name;
2362 StringRef LinkageName;
2363
2364 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2365
2366 const Decl *D = GD.getDecl();
2367 // Function may lack declaration in source code if it is created by Clang
2368 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2369 bool HasDecl = (D != 0);
2370 // Use the location of the declaration.
2371 SourceLocation Loc;
2372 if (HasDecl)
2373 Loc = D->getLocation();
2374
2375 unsigned Flags = 0;
2376 llvm::DIFile Unit = getOrCreateFile(Loc);
2377 llvm::DIDescriptor FDContext(Unit);
2378 llvm::DIArray TParamsArray;
2379 if (!HasDecl) {
2380 // Use llvm function name.
2381 Name = Fn->getName();
2382 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2383 // If there is a DISubprogram for this function available then use it.
2384 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2385 FI = SPCache.find(FD->getCanonicalDecl());
2386 if (FI != SPCache.end()) {
2387 llvm::Value *V = FI->second;
2388 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2389 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2390 llvm::MDNode *SPN = SP;
2391 LexicalBlockStack.push_back(SPN);
2392 RegionMap[D] = llvm::WeakVH(SP);
2393 return;
2394 }
2395 }
2396 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002397 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002398 if (FD->hasPrototype()) {
2399 LinkageName = CGM.getMangledName(GD);
2400 Flags |= llvm::DIDescriptor::FlagPrototyped;
2401 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002402 // No need to replicate the linkage name if it isn't different from the
2403 // subprogram name, no need to have it at all unless coverage is enabled or
2404 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002405 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002406 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2407 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002408 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002409 LinkageName = StringRef();
2410
Eric Christopher13c97672013-05-16 00:45:23 +00002411 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002412 if (const NamespaceDecl *NSDecl =
2413 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2414 FDContext = getOrCreateNameSpace(NSDecl);
2415 else if (const RecordDecl *RDecl =
2416 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2417 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2418
2419 // Collect template parameters.
2420 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2421 }
2422 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2423 Name = getObjCMethodName(OMD);
2424 Flags |= llvm::DIDescriptor::FlagPrototyped;
2425 } else {
2426 // Use llvm function name.
2427 Name = Fn->getName();
2428 Flags |= llvm::DIDescriptor::FlagPrototyped;
2429 }
2430 if (!Name.empty() && Name[0] == '\01')
2431 Name = Name.substr(1);
2432
2433 unsigned LineNo = getLineNumber(Loc);
2434 if (!HasDecl || D->isImplicit())
2435 Flags |= llvm::DIDescriptor::FlagArtificial;
2436
David Blaikie23e66db2013-06-22 00:09:36 +00002437 llvm::DISubprogram SP = DBuilder.createFunction(
2438 FDContext, Name, LinkageName, Unit, LineNo,
2439 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2440 true /*definition*/, getLineNumber(CurLoc), Flags,
2441 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002442 if (HasDecl)
2443 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002444
2445 // Push function on region stack.
2446 llvm::MDNode *SPN = SP;
2447 LexicalBlockStack.push_back(SPN);
2448 if (HasDecl)
2449 RegionMap[D] = llvm::WeakVH(SP);
2450}
2451
2452/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002453/// information in the source file. If the location is invalid, the
2454/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002455void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2456 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002457 // Update our current location
2458 setLocation(Loc);
2459
2460 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2461
2462 // Don't bother if things are the same as last time.
2463 SourceManager &SM = CGM.getContext().getSourceManager();
2464 if (CurLoc == PrevLoc ||
2465 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2466 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002467 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2468 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2469 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002470 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002471
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002472 // Update last state.
2473 PrevLoc = CurLoc;
2474
2475 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002476 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2477 (getLineNumber(CurLoc),
2478 getColumnNumber(CurLoc, ForceColumnInfo),
2479 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002480}
2481
2482/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2483/// the stack.
2484void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2485 llvm::DIDescriptor D =
2486 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2487 llvm::DIDescriptor() :
2488 llvm::DIDescriptor(LexicalBlockStack.back()),
2489 getOrCreateFile(CurLoc),
2490 getLineNumber(CurLoc),
2491 getColumnNumber(CurLoc));
2492 llvm::MDNode *DN = D;
2493 LexicalBlockStack.push_back(DN);
2494}
2495
2496/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2497/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002498void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2499 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002500 // Set our current location.
2501 setLocation(Loc);
2502
2503 // Create a new lexical block and push it on the stack.
2504 CreateLexicalBlock(Loc);
2505
2506 // Emit a line table change for the current location inside the new scope.
2507 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2508 getColumnNumber(Loc),
2509 LexicalBlockStack.back()));
2510}
2511
2512/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2513/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002514void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2515 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002516 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2517
2518 // Provide an entry in the line table for the end of the block.
2519 EmitLocation(Builder, Loc);
2520
2521 LexicalBlockStack.pop_back();
2522}
2523
2524/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2525void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2526 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2527 unsigned RCount = FnBeginRegionCount.back();
2528 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2529
2530 // Pop all regions for this function.
2531 while (LexicalBlockStack.size() != RCount)
2532 EmitLexicalBlockEnd(Builder, CurLoc);
2533 FnBeginRegionCount.pop_back();
2534}
2535
Eric Christopher6537f082013-05-16 00:45:12 +00002536// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002537// See BuildByRefType.
2538llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2539 uint64_t *XOffset) {
2540
2541 SmallVector<llvm::Value *, 5> EltTys;
2542 QualType FType;
2543 uint64_t FieldSize, FieldOffset;
2544 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002545
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002546 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002547 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548
2549 FieldOffset = 0;
2550 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2551 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2552 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2553 FType = CGM.getContext().IntTy;
2554 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2555 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2556
2557 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2558 if (HasCopyAndDispose) {
2559 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2560 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2561 &FieldOffset));
2562 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2563 &FieldOffset));
2564 }
2565 bool HasByrefExtendedLayout;
2566 Qualifiers::ObjCLifetime Lifetime;
2567 if (CGM.getContext().getByrefLifetime(Type,
2568 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002569 && HasByrefExtendedLayout) {
2570 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002571 EltTys.push_back(CreateMemberType(Unit, FType,
2572 "__byref_variable_layout",
2573 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002574 }
Eric Christopher6537f082013-05-16 00:45:12 +00002575
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002576 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2577 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002578 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002579 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002580 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2581 CharUnits AlignedOffsetInBytes
2582 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2583 CharUnits NumPaddingBytes
2584 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002585
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002586 if (NumPaddingBytes.isPositive()) {
2587 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2588 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2589 pad, ArrayType::Normal, 0);
2590 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2591 }
2592 }
Eric Christopher6537f082013-05-16 00:45:12 +00002593
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002594 FType = Type;
2595 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2596 FieldSize = CGM.getContext().getTypeSize(FType);
2597 FieldAlign = CGM.getContext().toBits(Align);
2598
Eric Christopher6537f082013-05-16 00:45:12 +00002599 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002600 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2601 0, FieldSize, FieldAlign,
2602 FieldOffset, 0, FieldTy);
2603 EltTys.push_back(FieldTy);
2604 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002605
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002606 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002607
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002608 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002609
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002610 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002611 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002612}
2613
2614/// EmitDeclare - Emit local variable declaration debug info.
2615void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002616 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002618 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2620
2621 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2622 llvm::DIType Ty;
2623 uint64_t XOffset = 0;
2624 if (VD->hasAttr<BlocksAttr>())
2625 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002626 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002627 Ty = getOrCreateType(VD->getType(), Unit);
2628
2629 // If there is no debug info for this type then do not emit debug info
2630 // for this variable.
2631 if (!Ty)
2632 return;
2633
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002634 // Get location information.
2635 unsigned Line = getLineNumber(VD->getLocation());
2636 unsigned Column = getColumnNumber(VD->getLocation());
2637 unsigned Flags = 0;
2638 if (VD->isImplicit())
2639 Flags |= llvm::DIDescriptor::FlagArtificial;
2640 // If this is the first argument and it is implicit then
2641 // give it an object pointer flag.
2642 // FIXME: There has to be a better way to do this, but for static
2643 // functions there won't be an implicit param at arg1 and
2644 // otherwise it is 'self' or 'this'.
2645 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2646 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002647 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002648 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2649 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002650 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002651
2652 llvm::MDNode *Scope = LexicalBlockStack.back();
2653
2654 StringRef Name = VD->getName();
2655 if (!Name.empty()) {
2656 if (VD->hasAttr<BlocksAttr>()) {
2657 CharUnits offset = CharUnits::fromQuantity(32);
2658 SmallVector<llvm::Value *, 9> addr;
2659 llvm::Type *Int64Ty = CGM.Int64Ty;
2660 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2661 // offset of __forwarding field
2662 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002663 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002664 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2665 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2666 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2667 // offset of x field
2668 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2669 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2670
2671 // Create the descriptor for the variable.
2672 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002673 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002674 llvm::DIDescriptor(Scope),
2675 VD->getName(), Unit, Line, Ty,
2676 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002677
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002678 // Insert an llvm.dbg.declare into the current block.
2679 llvm::Instruction *Call =
2680 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2681 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2682 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683 }
David Blaikie436653b2013-01-05 05:58:35 +00002684 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2685 // If VD is an anonymous union then Storage represents value for
2686 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002687 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002688 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002689 for (RecordDecl::field_iterator I = RD->field_begin(),
2690 E = RD->field_end();
2691 I != E; ++I) {
2692 FieldDecl *Field = *I;
2693 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2694 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002695
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696 // Ignore unnamed fields. Do not ignore unnamed records.
2697 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2698 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002699
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002700 // Use VarDecl's Tag, Scope and Line number.
2701 llvm::DIVariable D =
2702 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002703 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 CGM.getLangOpts().Optimize, Flags,
2705 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002706
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002707 // Insert an llvm.dbg.declare into the current block.
2708 llvm::Instruction *Call =
2709 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2710 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2711 }
David Blaikied8180cf2013-01-05 20:03:07 +00002712 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002713 }
2714 }
David Blaikie436653b2013-01-05 05:58:35 +00002715
2716 // Create the descriptor for the variable.
2717 llvm::DIVariable D =
2718 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2719 Name, Unit, Line, Ty,
2720 CGM.getLangOpts().Optimize, Flags, ArgNo);
2721
2722 // Insert an llvm.dbg.declare into the current block.
2723 llvm::Instruction *Call =
2724 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2725 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002726}
2727
2728void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2729 llvm::Value *Storage,
2730 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002731 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002732 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2733}
2734
Adrian Prantle86fcc42013-03-29 19:20:29 +00002735/// Look up the completed type for a self pointer in the TypeCache and
2736/// create a copy of it with the ObjectPointer and Artificial flags
2737/// set. If the type is not cached, a new one is created. This should
2738/// never happen though, since creating a type for the implicit self
2739/// argument implies that we already parsed the interface definition
2740/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002741llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2742 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002743 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002744 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002745 else DEBUG(llvm::dbgs() << "No cached type for self.");
2746 return DBuilder.createObjectPointerType(Ty);
2747}
2748
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002749void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2750 llvm::Value *Storage,
2751 CGBuilderTy &Builder,
2752 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002753 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002754 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002755
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002756 if (Builder.GetInsertBlock() == 0)
2757 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002758
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002759 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002760
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002761 uint64_t XOffset = 0;
2762 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2763 llvm::DIType Ty;
2764 if (isByRef)
2765 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002766 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002767 Ty = getOrCreateType(VD->getType(), Unit);
2768
2769 // Self is passed along as an implicit non-arg variable in a
2770 // block. Mark it as the object pointer.
2771 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002772 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002773
2774 // Get location information.
2775 unsigned Line = getLineNumber(VD->getLocation());
2776 unsigned Column = getColumnNumber(VD->getLocation());
2777
2778 const llvm::DataLayout &target = CGM.getDataLayout();
2779
2780 CharUnits offset = CharUnits::fromQuantity(
2781 target.getStructLayout(blockInfo.StructureType)
2782 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2783
2784 SmallVector<llvm::Value *, 9> addr;
2785 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002786 if (isa<llvm::AllocaInst>(Storage))
2787 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002788 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2789 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2790 if (isByRef) {
2791 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2792 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2793 // offset of __forwarding field
2794 offset = CGM.getContext()
2795 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2796 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2797 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2798 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2799 // offset of x field
2800 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2801 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2802 }
2803
2804 // Create the descriptor for the variable.
2805 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002806 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002807 llvm::DIDescriptor(LexicalBlockStack.back()),
2808 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002809
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002810 // Insert an llvm.dbg.declare into the current block.
2811 llvm::Instruction *Call =
2812 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2813 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2814 LexicalBlockStack.back()));
2815}
2816
2817/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2818/// variable declaration.
2819void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2820 unsigned ArgNo,
2821 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002822 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002823 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2824}
2825
2826namespace {
2827 struct BlockLayoutChunk {
2828 uint64_t OffsetInBits;
2829 const BlockDecl::Capture *Capture;
2830 };
2831 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2832 return l.OffsetInBits < r.OffsetInBits;
2833 }
2834}
2835
2836void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002837 llvm::Value *Arg,
2838 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002839 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002840 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002841 ASTContext &C = CGM.getContext();
2842 const BlockDecl *blockDecl = block.getBlockDecl();
2843
2844 // Collect some general information about the block's location.
2845 SourceLocation loc = blockDecl->getCaretLocation();
2846 llvm::DIFile tunit = getOrCreateFile(loc);
2847 unsigned line = getLineNumber(loc);
2848 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002849
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002850 // Build the debug-info type for the block literal.
2851 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2852
2853 const llvm::StructLayout *blockLayout =
2854 CGM.getDataLayout().getStructLayout(block.StructureType);
2855
2856 SmallVector<llvm::Value*, 16> fields;
2857 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2858 blockLayout->getElementOffsetInBits(0),
2859 tunit, tunit));
2860 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2861 blockLayout->getElementOffsetInBits(1),
2862 tunit, tunit));
2863 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2864 blockLayout->getElementOffsetInBits(2),
2865 tunit, tunit));
2866 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2867 blockLayout->getElementOffsetInBits(3),
2868 tunit, tunit));
2869 fields.push_back(createFieldType("__descriptor",
2870 C.getPointerType(block.NeedsCopyDispose ?
2871 C.getBlockDescriptorExtendedType() :
2872 C.getBlockDescriptorType()),
2873 0, loc, AS_public,
2874 blockLayout->getElementOffsetInBits(4),
2875 tunit, tunit));
2876
2877 // We want to sort the captures by offset, not because DWARF
2878 // requires this, but because we're paranoid about debuggers.
2879 SmallVector<BlockLayoutChunk, 8> chunks;
2880
2881 // 'this' capture.
2882 if (blockDecl->capturesCXXThis()) {
2883 BlockLayoutChunk chunk;
2884 chunk.OffsetInBits =
2885 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2886 chunk.Capture = 0;
2887 chunks.push_back(chunk);
2888 }
2889
2890 // Variable captures.
2891 for (BlockDecl::capture_const_iterator
2892 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2893 i != e; ++i) {
2894 const BlockDecl::Capture &capture = *i;
2895 const VarDecl *variable = capture.getVariable();
2896 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2897
2898 // Ignore constant captures.
2899 if (captureInfo.isConstant())
2900 continue;
2901
2902 BlockLayoutChunk chunk;
2903 chunk.OffsetInBits =
2904 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2905 chunk.Capture = &capture;
2906 chunks.push_back(chunk);
2907 }
2908
2909 // Sort by offset.
2910 llvm::array_pod_sort(chunks.begin(), chunks.end());
2911
2912 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2913 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2914 uint64_t offsetInBits = i->OffsetInBits;
2915 const BlockDecl::Capture *capture = i->Capture;
2916
2917 // If we have a null capture, this must be the C++ 'this' capture.
2918 if (!capture) {
2919 const CXXMethodDecl *method =
2920 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2921 QualType type = method->getThisType(C);
2922
2923 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2924 offsetInBits, tunit, tunit));
2925 continue;
2926 }
2927
2928 const VarDecl *variable = capture->getVariable();
2929 StringRef name = variable->getName();
2930
2931 llvm::DIType fieldType;
2932 if (capture->isByRef()) {
2933 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2934
2935 // FIXME: this creates a second copy of this type!
2936 uint64_t xoffset;
2937 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2938 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2939 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2940 ptrInfo.first, ptrInfo.second,
2941 offsetInBits, 0, fieldType);
2942 } else {
2943 fieldType = createFieldType(name, variable->getType(), 0,
2944 loc, AS_public, offsetInBits, tunit, tunit);
2945 }
2946 fields.push_back(fieldType);
2947 }
2948
2949 SmallString<36> typeName;
2950 llvm::raw_svector_ostream(typeName)
2951 << "__block_literal_" << CGM.getUniqueBlockCount();
2952
2953 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2954
2955 llvm::DIType type =
2956 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2957 CGM.getContext().toBits(block.BlockSize),
2958 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002959 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002960 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2961
2962 // Get overall information about the block.
2963 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2964 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002965
2966 // Create the descriptor for the parameter.
2967 llvm::DIVariable debugVar =
2968 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002969 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002970 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002971 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002972 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2973
Adrian Prantlbea407c2013-03-14 21:52:59 +00002974 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002975 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002976 llvm::Instruction *DbgVal =
2977 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002978 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002979 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2980 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002981
Adrian Prantlbea407c2013-03-14 21:52:59 +00002982 // Insert an llvm.dbg.declare into the current block.
2983 llvm::Instruction *DbgDecl =
2984 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2985 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002986}
2987
Eric Christopher0395de32013-01-16 01:22:32 +00002988/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2989/// a static data member of a class, find its corresponding in-class
2990/// declaration.
2991llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2992 if (cast<VarDecl>(D)->isStaticDataMember()) {
2993 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2994 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2995 if (MI != StaticDataMemberCache.end())
2996 // Verify the info still exists.
2997 if (llvm::Value *V = MI->second)
2998 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2999 }
3000 return llvm::DIDerivedType();
3001}
3002
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003003/// EmitGlobalVariable - Emit information about a global variable.
3004void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3005 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003006 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003007 // Create global variable debug descriptor.
3008 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3009 unsigned LineNo = getLineNumber(D->getLocation());
3010
3011 setLocation(D->getLocation());
3012
3013 QualType T = D->getType();
3014 if (T->isIncompleteArrayType()) {
3015
3016 // CodeGen turns int[] into int[1] so we'll do the same here.
3017 llvm::APInt ConstVal(32, 1);
3018 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3019
3020 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3021 ArrayType::Normal, 0);
3022 }
3023 StringRef DeclName = D->getName();
3024 StringRef LinkageName;
3025 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3026 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3027 LinkageName = Var->getName();
3028 if (LinkageName == DeclName)
3029 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003030 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003031 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003032 llvm::DIGlobalVariable GV =
3033 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3034 LineNo, getOrCreateType(T, Unit),
3035 Var->hasInternalLinkage(), Var,
3036 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003037 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003038}
3039
3040/// EmitGlobalVariable - Emit information about an objective-c interface.
3041void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3042 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003043 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003044 // Create global variable debug descriptor.
3045 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3046 unsigned LineNo = getLineNumber(ID->getLocation());
3047
3048 StringRef Name = ID->getName();
3049
3050 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3051 if (T->isIncompleteArrayType()) {
3052
3053 // CodeGen turns int[] into int[1] so we'll do the same here.
3054 llvm::APInt ConstVal(32, 1);
3055 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3056
3057 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3058 ArrayType::Normal, 0);
3059 }
3060
3061 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3062 getOrCreateType(T, Unit),
3063 Var->hasInternalLinkage(), Var);
3064}
3065
3066/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003067void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003068 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003069 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003070 // Create the descriptor for the variable.
3071 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3072 StringRef Name = VD->getName();
3073 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3074 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3075 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3076 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3077 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3078 }
3079 // Do not use DIGlobalVariable for enums.
3080 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3081 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003082 llvm::DIGlobalVariable GV =
3083 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3084 getLineNumber(VD->getLocation()), Ty, true,
3085 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003086 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3087}
3088
3089llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3090 if (!LexicalBlockStack.empty())
3091 return llvm::DIScope(LexicalBlockStack.back());
3092 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003093}
3094
David Blaikie957dac52013-04-22 06:13:21 +00003095void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003096 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3097 return;
David Blaikie957dac52013-04-22 06:13:21 +00003098 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003099 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3100 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003101 getLineNumber(UD.getLocation()));
3102}
3103
David Blaikie9faebd22013-05-20 04:58:53 +00003104void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3105 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3106 return;
3107 assert(UD.shadow_size() &&
3108 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3109 // Emitting one decl is sufficient - debuggers can detect that this is an
3110 // overloaded name & provide lookup for all the overloads.
3111 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003112 if (llvm::DIDescriptor Target =
3113 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003114 DBuilder.createImportedDeclaration(
3115 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3116 getLineNumber(USD.getLocation()));
3117}
3118
David Blaikiefc46ebc2013-05-20 22:50:41 +00003119llvm::DIImportedEntity
3120CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3121 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3122 return llvm::DIImportedEntity(0);
3123 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3124 if (VH)
3125 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3126 llvm::DIImportedEntity R(0);
3127 if (const NamespaceAliasDecl *Underlying =
3128 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3129 // This could cache & dedup here rather than relying on metadata deduping.
3130 R = DBuilder.createImportedModule(
3131 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3132 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3133 NA.getName());
3134 else
3135 R = DBuilder.createImportedModule(
3136 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3137 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3138 getLineNumber(NA.getLocation()), NA.getName());
3139 VH = R;
3140 return R;
3141}
3142
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003143/// getOrCreateNamesSpace - Return namespace descriptor for the given
3144/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003145llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003146CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003147 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003148 NameSpaceCache.find(NSDecl);
3149 if (I != NameSpaceCache.end())
3150 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003151
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003152 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3153 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003154 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003155 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3156 llvm::DINameSpace NS =
3157 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3158 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3159 return NS;
3160}
3161
3162void CGDebugInfo::finalize() {
3163 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3164 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3165 llvm::DIType Ty, RepTy;
3166 // Verify that the debug info still exists.
3167 if (llvm::Value *V = VI->second)
3168 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003169
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003170 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3171 TypeCache.find(VI->first);
3172 if (it != TypeCache.end()) {
3173 // Verify that the debug info still exists.
3174 if (llvm::Value *V = it->second)
3175 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3176 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003177
Eric Christopherb2d13922013-07-18 00:52:50 +00003178 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003179 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003180 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003181
3182 // We keep our own list of retained types, because we need to look
3183 // up the final type in the type cache.
3184 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3185 RE = RetainedTypes.end(); RI != RE; ++RI)
3186 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3187
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003188 DBuilder.finalize();
3189}