blob: bd197373529f7279ee3dcae0d96ea4d1ac259650 [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.
David Blaikie47251962013-08-22 13:36:01 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000547 QualifierCollector Qc;
548 const Type *T = Qc.strip(Ty);
549
550 // Ignore these qualifiers for now.
551 Qc.removeObjCGCAttr();
552 Qc.removeAddressSpace();
553 Qc.removeObjCLifetime();
554
555 // We will create one Derived type for one qualifier and recurse to handle any
556 // additional ones.
557 unsigned Tag;
558 if (Qc.hasConst()) {
559 Tag = llvm::dwarf::DW_TAG_const_type;
560 Qc.removeConst();
561 } else if (Qc.hasVolatile()) {
562 Tag = llvm::dwarf::DW_TAG_volatile_type;
563 Qc.removeVolatile();
564 } else if (Qc.hasRestrict()) {
565 Tag = llvm::dwarf::DW_TAG_restrict_type;
566 Qc.removeRestrict();
567 } else {
568 assert(Qc.empty() && "Unknown type qualifier for debug info");
569 return getOrCreateType(QualType(T, 0), Unit);
570 }
571
David Blaikie47251962013-08-22 13:36:01 +0000572 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000573
574 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
575 // CVR derived types.
576 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000577
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000578 return DbgTy;
579}
580
581llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
582 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000583
584 // The frontend treats 'id' as a typedef to an ObjCObjectType,
585 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
586 // debug info, we want to emit 'id' in both cases.
587 if (Ty->isObjCQualifiedIdType())
588 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
589
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000590 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000591 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000592 Ty->getPointeeType(), Unit);
593 return DbgTy;
594}
595
596llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
597 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000598 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000599 Ty->getPointeeType(), Unit);
600}
601
Manman Renf1acc312013-08-29 18:51:51 +0000602/// In C++ mode, types have linkage, so we can rely on the ODR and
603/// on their mangled names, if they're external. Otherwise, we append
604/// the CU's directory and file name.
605static void getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
606 llvm::DICompileUnit TheCU,
607 SmallString<256> &FullName) {
608 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
609 // For now, only apply ODR with C++.
610 const TagDecl *TD = Ty->getDecl();
611 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
612 !TD->isExternallyVisible())
613 return;
614 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
615 if (CGM.getTarget().getCXXABI().isMicrosoft())
616 return;
617
618 // TODO: This is using the RTTI name. Is there a better way to get
619 // a unique string for a type?
620 llvm::raw_svector_ostream Out(FullName);
621 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
622 Out.flush();
623}
624
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000625// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000626llvm::DICompositeType
Manman Renf3327332013-08-28 21:20:28 +0000627CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikieeaacc882013-08-20 21:03:29 +0000628 llvm::DIDescriptor Ctx) {
Manman Renf3327332013-08-28 21:20:28 +0000629 const RecordDecl *RD = Ty->getDecl();
David Blaikiec5cd1a72013-08-15 20:17:25 +0000630 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000631 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000632 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
633 unsigned Line = getLineNumber(RD->getLocation());
634 StringRef RDName = getClassName(RD);
635
636 unsigned Tag = 0;
637 if (RD->isStruct() || RD->isInterface())
638 Tag = llvm::dwarf::DW_TAG_structure_type;
639 else if (RD->isUnion())
640 Tag = llvm::dwarf::DW_TAG_union_type;
641 else {
642 assert(RD->isClass());
643 Tag = llvm::dwarf::DW_TAG_class_type;
644 }
645
646 // Create the type.
Manman Renf1acc312013-08-29 18:51:51 +0000647 SmallString<256> FullName;
648 getUniqueTagTypeName(Ty, CGM, TheCU, FullName);
649 if (!FullName.empty()) {
650 QualType QTy(Ty, 0);
651 RetainedTypes.push_back(QTy.getAsOpaquePtr());
652 }
653 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
654 FullName.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000655}
656
657// Walk up the context chain and create forward decls for record decls,
658// and normal descriptors for namespaces.
659llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
660 if (!Context)
661 return TheCU;
662
663 // See if we already have the parent.
664 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
665 I = RegionMap.find(Context);
666 if (I != RegionMap.end()) {
667 llvm::Value *V = I->second;
668 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
669 }
Eric Christopher6537f082013-05-16 00:45:12 +0000670
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000671 // Check namespace.
672 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
673 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
674
David Blaikieeaacc882013-08-20 21:03:29 +0000675 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context))
676 if (!RD->isDependentType())
677 return getOrCreateLimitedType(
David Blaikie5434fc22013-08-20 01:28:15 +0000678 CGM.getContext().getRecordType(RD)->castAs<RecordType>(),
David Blaikieeaacc882013-08-20 21:03:29 +0000679 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000680 return TheCU;
681}
682
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000683llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000684 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000685 QualType PointeeTy,
686 llvm::DIFile Unit) {
687 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
688 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie47251962013-08-22 13:36:01 +0000689 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000690
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000691 // Bit size, align and offset of the type.
692 // Size is always the size of a pointer. We can't use getTypeSize here
693 // because that does not return the correct value for references.
694 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000695 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000696 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
697
David Blaikie47251962013-08-22 13:36:01 +0000698 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
699 Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000700}
701
Eric Christopherf0890c42013-05-16 00:52:20 +0000702llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
703 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000704 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000705 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000706 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
707 TheCU, getOrCreateMainFile(), 0);
708 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
709 Cache = DBuilder.createPointerType(Cache, Size);
710 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000711}
712
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000713llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
714 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000715 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000716 return BlockLiteralGeneric;
717
718 SmallVector<llvm::Value *, 8> EltTys;
719 llvm::DIType FieldTy;
720 QualType FType;
721 uint64_t FieldSize, FieldOffset;
722 unsigned FieldAlign;
723 llvm::DIArray Elements;
724 llvm::DIType EltTy, DescTy;
725
726 FieldOffset = 0;
727 FType = CGM.getContext().UnsignedLongTy;
728 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
729 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
730
731 Elements = DBuilder.getOrCreateArray(EltTys);
732 EltTys.clear();
733
734 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
735 unsigned LineNo = getLineNumber(CurLoc);
736
737 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
738 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000739 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000740
741 // Bit size, align and offset of the type.
742 uint64_t Size = CGM.getContext().getTypeSize(Ty);
743
744 DescTy = DBuilder.createPointerType(EltTy, Size);
745
746 FieldOffset = 0;
747 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
748 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
749 FType = CGM.getContext().IntTy;
750 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
751 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
752 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
753 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
754
755 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
756 FieldTy = DescTy;
757 FieldSize = CGM.getContext().getTypeSize(Ty);
758 FieldAlign = CGM.getContext().getTypeAlign(Ty);
759 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
760 LineNo, FieldSize, FieldAlign,
761 FieldOffset, 0, FieldTy);
762 EltTys.push_back(FieldTy);
763
764 FieldOffset += FieldSize;
765 Elements = DBuilder.getOrCreateArray(EltTys);
766
767 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
768 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000769 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000770
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000771 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
772 return BlockLiteralGeneric;
773}
774
David Blaikie47251962013-08-22 13:36:01 +0000775llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000776 // Typedefs are derived from some other type. If we have a typedef of a
777 // typedef, make sure to emit the whole chain.
David Blaikie47251962013-08-22 13:36:01 +0000778 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherb2d13922013-07-18 00:52:50 +0000779 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000780 return llvm::DIType();
781 // We don't set size information, but do specify where the typedef was
782 // declared.
783 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
784 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000785
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000786 llvm::DIDescriptor TypedefContext =
787 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000788
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000789 return
790 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
791}
792
793llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
794 llvm::DIFile Unit) {
795 SmallVector<llvm::Value *, 16> EltTys;
796
797 // Add the result type at least.
David Blaikie47251962013-08-22 13:36:01 +0000798 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000799
800 // Set up remainder of arguments if there is a prototype.
801 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
802 if (isa<FunctionNoProtoType>(Ty))
803 EltTys.push_back(DBuilder.createUnspecifiedParameter());
804 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
805 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie47251962013-08-22 13:36:01 +0000806 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000807 }
808
809 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
810 return DBuilder.createSubroutineType(Unit, EltTypeArray);
811}
812
813
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000814llvm::DIType CGDebugInfo::createFieldType(StringRef name,
815 QualType type,
816 uint64_t sizeInBitsOverride,
817 SourceLocation loc,
818 AccessSpecifier AS,
819 uint64_t offsetInBits,
820 llvm::DIFile tunit,
821 llvm::DIDescriptor scope) {
822 llvm::DIType debugType = getOrCreateType(type, tunit);
823
824 // Get the location for the field.
825 llvm::DIFile file = getOrCreateFile(loc);
826 unsigned line = getLineNumber(loc);
827
828 uint64_t sizeInBits = 0;
829 unsigned alignInBits = 0;
830 if (!type->isIncompleteArrayType()) {
831 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
832
833 if (sizeInBitsOverride)
834 sizeInBits = sizeInBitsOverride;
835 }
836
837 unsigned flags = 0;
838 if (AS == clang::AS_private)
839 flags |= llvm::DIDescriptor::FlagPrivate;
840 else if (AS == clang::AS_protected)
841 flags |= llvm::DIDescriptor::FlagProtected;
842
843 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
844 alignInBits, offsetInBits, flags, debugType);
845}
846
Eric Christopher0395de32013-01-16 01:22:32 +0000847/// CollectRecordLambdaFields - Helper for CollectRecordFields.
848void CGDebugInfo::
849CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
850 SmallVectorImpl<llvm::Value *> &elements,
851 llvm::DIType RecordTy) {
852 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
853 // has the name and the location of the variable so we should iterate over
854 // both concurrently.
855 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
856 RecordDecl::field_iterator Field = CXXDecl->field_begin();
857 unsigned fieldno = 0;
858 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
859 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
860 const LambdaExpr::Capture C = *I;
861 if (C.capturesVariable()) {
862 VarDecl *V = C.getCapturedVar();
863 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
864 StringRef VName = V->getName();
865 uint64_t SizeInBitsOverride = 0;
866 if (Field->isBitField()) {
867 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
868 assert(SizeInBitsOverride && "found named 0-width bitfield");
869 }
870 llvm::DIType fieldType
871 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
872 C.getLocation(), Field->getAccess(),
873 layout.getFieldOffset(fieldno), VUnit, RecordTy);
874 elements.push_back(fieldType);
875 } else {
876 // TODO: Need to handle 'this' in some way by probably renaming the
877 // this of the lambda class and having a field member of 'this' or
878 // by using AT_object_pointer for the function and having that be
879 // used as 'this' for semantic references.
880 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
881 FieldDecl *f = *Field;
882 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
883 QualType type = f->getType();
884 llvm::DIType fieldType
885 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
886 layout.getFieldOffset(fieldno), VUnit, RecordTy);
887
888 elements.push_back(fieldType);
889 }
890 }
891}
892
David Blaikie5434fc22013-08-20 01:28:15 +0000893/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000894llvm::DIDerivedType
895CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
896 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000897 // Create the descriptor for the static variable, with or without
898 // constant initializers.
899 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
900 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
901
Eric Christopher0395de32013-01-16 01:22:32 +0000902 unsigned LineNumber = getLineNumber(Var->getLocation());
903 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000904 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000905 if (Var->getInit()) {
906 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000907 if (Value) {
908 if (Value->isInt())
909 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
910 if (Value->isFloat())
911 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
912 }
Eric Christopher0395de32013-01-16 01:22:32 +0000913 }
914
915 unsigned Flags = 0;
916 AccessSpecifier Access = Var->getAccess();
917 if (Access == clang::AS_private)
918 Flags |= llvm::DIDescriptor::FlagPrivate;
919 else if (Access == clang::AS_protected)
920 Flags |= llvm::DIDescriptor::FlagProtected;
921
David Blaikiecbcb0302013-08-15 22:50:29 +0000922 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
923 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000924 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000925 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000926}
927
928/// CollectRecordNormalField - Helper for CollectRecordFields.
929void CGDebugInfo::
930CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
931 llvm::DIFile tunit,
932 SmallVectorImpl<llvm::Value *> &elements,
933 llvm::DIType RecordTy) {
934 StringRef name = field->getName();
935 QualType type = field->getType();
936
937 // Ignore unnamed fields unless they're anonymous structs/unions.
938 if (name.empty() && !type->isRecordType())
939 return;
940
941 uint64_t SizeInBitsOverride = 0;
942 if (field->isBitField()) {
943 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
944 assert(SizeInBitsOverride && "found named 0-width bitfield");
945 }
946
947 llvm::DIType fieldType
948 = createFieldType(name, type, SizeInBitsOverride,
949 field->getLocation(), field->getAccess(),
950 OffsetInBits, tunit, RecordTy);
951
952 elements.push_back(fieldType);
953}
954
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000955/// CollectRecordFields - A helper function to collect debug info for
956/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000957void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
958 llvm::DIFile tunit,
959 SmallVectorImpl<llvm::Value *> &elements,
960 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000961 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
962
Eric Christopher0395de32013-01-16 01:22:32 +0000963 if (CXXDecl && CXXDecl->isLambda())
964 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
965 else {
966 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000967
Eric Christopher0395de32013-01-16 01:22:32 +0000968 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000969 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000970
Eric Christopher0395de32013-01-16 01:22:32 +0000971 // Static and non-static members should appear in the same order as
972 // the corresponding declarations in the source program.
973 for (RecordDecl::decl_iterator I = record->decls_begin(),
974 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000975 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
976 // Reuse the existing static member declaration if one exists
977 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
978 StaticDataMemberCache.find(V->getCanonicalDecl());
979 if (MI != StaticDataMemberCache.end()) {
980 assert(MI->second &&
981 "Static data member declaration should still exist");
982 elements.push_back(
983 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
984 } else
985 elements.push_back(CreateRecordStaticField(V, RecordTy));
986 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000987 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
988 tunit, elements, RecordTy);
989
990 // Bump field number for next field.
991 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000992 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000993 }
994}
995
996/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
997/// function type is not updated to include implicit "this" pointer. Use this
998/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000999llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001000CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1001 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +00001002 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +00001003 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +00001004 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +00001005 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1006 Func, Unit);
1007}
David Blaikie67f8b5e2013-01-07 22:24:59 +00001008
David Blaikie9a845292013-05-22 23:22:42 +00001009llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +00001010 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001011 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +00001012 llvm::DIArray Args = llvm::DICompositeType(
1013 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001014 assert (Args.getNumElements() && "Invalid number of arguments!");
1015
1016 SmallVector<llvm::Value *, 16> Elts;
1017
1018 // First element is always return type. For 'void' functions it is NULL.
1019 Elts.push_back(Args.getElement(0));
1020
David Blaikie67f8b5e2013-01-07 22:24:59 +00001021 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +00001022 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +00001023 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1024 // Create pointer type directly in this case.
1025 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1026 QualType PointeeTy = ThisPtrTy->getPointeeType();
1027 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001028 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001029 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1030 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001031 llvm::DIType ThisPtrType =
1032 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001033 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1034 // TODO: This and the artificial type below are misleading, the
1035 // types aren't artificial the argument is, but the current
1036 // metadata doesn't represent that.
1037 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1038 Elts.push_back(ThisPtrType);
1039 } else {
1040 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1041 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1042 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1043 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001044 }
1045
1046 // Copy rest of the arguments.
1047 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1048 Elts.push_back(Args.getElement(i));
1049
1050 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1051
1052 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1053}
1054
Eric Christopher6537f082013-05-16 00:45:12 +00001055/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001056/// inside a function.
1057static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1058 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1059 return isFunctionLocalClass(NRD);
1060 if (isa<FunctionDecl>(RD->getDeclContext()))
1061 return true;
1062 return false;
1063}
1064
1065/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1066/// a single member function GlobalDecl.
1067llvm::DISubprogram
1068CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1069 llvm::DIFile Unit,
1070 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001071 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001072 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001073
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001074 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001075 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001076
1077 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1078 // make sense to give a single ctor/dtor a linkage name.
1079 StringRef MethodLinkageName;
1080 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1081 MethodLinkageName = CGM.getMangledName(Method);
1082
1083 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001084 llvm::DIFile MethodDefUnit;
1085 unsigned MethodLine = 0;
1086 if (!Method->isImplicit()) {
1087 MethodDefUnit = getOrCreateFile(Method->getLocation());
1088 MethodLine = getLineNumber(Method->getLocation());
1089 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001090
1091 // Collect virtual method info.
1092 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001093 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001094 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001095
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001096 if (Method->isVirtual()) {
1097 if (Method->isPure())
1098 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1099 else
1100 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001101
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001102 // It doesn't make sense to give a virtual destructor a vtable index,
1103 // since a single destructor has two entries in the vtable.
1104 if (!isa<CXXDestructorDecl>(Method))
1105 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1106 ContainingType = RecordTy;
1107 }
1108
1109 unsigned Flags = 0;
1110 if (Method->isImplicit())
1111 Flags |= llvm::DIDescriptor::FlagArtificial;
1112 AccessSpecifier Access = Method->getAccess();
1113 if (Access == clang::AS_private)
1114 Flags |= llvm::DIDescriptor::FlagPrivate;
1115 else if (Access == clang::AS_protected)
1116 Flags |= llvm::DIDescriptor::FlagProtected;
1117 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1118 if (CXXC->isExplicit())
1119 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001120 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001121 dyn_cast<CXXConversionDecl>(Method)) {
1122 if (CXXC->isExplicit())
1123 Flags |= llvm::DIDescriptor::FlagExplicit;
1124 }
1125 if (Method->hasPrototype())
1126 Flags |= llvm::DIDescriptor::FlagPrototyped;
1127
1128 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1129 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001130 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001131 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001132 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001133 /* isDefinition=*/ false,
1134 Virtuality, VIndex, ContainingType,
1135 Flags, CGM.getLangOpts().Optimize, NULL,
1136 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001137
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001138 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1139
1140 return SP;
1141}
1142
1143/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001144/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145/// a Record.
1146void CGDebugInfo::
1147CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1148 SmallVectorImpl<llvm::Value *> &EltTys,
1149 llvm::DIType RecordTy) {
1150
1151 // Since we want more than just the individual member decls if we
1152 // have templated functions iterate over every declaration to gather
1153 // the functions.
1154 for(DeclContext::decl_iterator I = RD->decls_begin(),
1155 E = RD->decls_end(); I != E; ++I) {
David Blaikiec5761272013-08-28 17:27:13 +00001156 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001157 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001158 // It may be associated with the declaration of the type & should be
1159 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001160 //
1161 // This situation can arise in the vtable-based debug info reduction where
1162 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001163 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1164 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001165 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001166 // If the member is implicit, lazily create it when we see the
1167 // definition, not before. (an ODR-used implicit default ctor that's
1168 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001169 if (!Method->isImplicit())
1170 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1171 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001172 EltTys.push_back(MI->second);
Eric Christopherac7c25f2013-08-28 23:12:10 +00001173 } else if (const FunctionTemplateDecl *FTD =
1174 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikie11fa7512013-08-28 23:06:52 +00001175 // Add any template specializations that have already been seen. Like
1176 // implicit member functions, these may have been added to a declaration
1177 // in the case of vtable-based debug info reduction.
Eric Christopherac7c25f2013-08-28 23:12:10 +00001178 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1179 SE = FTD->spec_end();
1180 SI != SE; ++SI) {
David Blaikie11fa7512013-08-28 23:06:52 +00001181 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1182 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1183 if (MI != SPCache.end())
1184 EltTys.push_back(MI->second);
1185 }
David Blaikie5434fc22013-08-20 01:28:15 +00001186 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 }
Eric Christopher6537f082013-05-16 00:45:12 +00001188}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001189
1190/// CollectCXXFriends - A helper function to collect debug info for
1191/// C++ base classes. This is used while creating debug info entry for
1192/// a Record.
1193void CGDebugInfo::
1194CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1195 SmallVectorImpl<llvm::Value *> &EltTys,
1196 llvm::DIType RecordTy) {
1197 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1198 BE = RD->friend_end(); BI != BE; ++BI) {
1199 if ((*BI)->isUnsupportedFriend())
1200 continue;
1201 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001202 EltTys.push_back(DBuilder.createFriend(
David Blaikie47251962013-08-22 13:36:01 +00001203 RecordTy, getOrCreateType(TInfo->getType(), Unit)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001204 }
1205}
1206
1207/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001208/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001209/// a Record.
1210void CGDebugInfo::
1211CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1212 SmallVectorImpl<llvm::Value *> &EltTys,
1213 llvm::DIType RecordTy) {
1214
1215 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1216 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1217 BE = RD->bases_end(); BI != BE; ++BI) {
1218 unsigned BFlags = 0;
1219 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001220
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001221 const CXXRecordDecl *Base =
1222 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001223
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001224 if (BI->isVirtual()) {
1225 // virtual base offset offset is -ve. The code generator emits dwarf
1226 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001227 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001228 0 - CGM.getVTableContext()
1229 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1230 BFlags = llvm::DIDescriptor::FlagVirtual;
1231 } else
1232 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1233 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1234 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001235
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001236 AccessSpecifier Access = BI->getAccessSpecifier();
1237 if (Access == clang::AS_private)
1238 BFlags |= llvm::DIDescriptor::FlagPrivate;
1239 else if (Access == clang::AS_protected)
1240 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001241
1242 llvm::DIType DTy =
1243 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001244 getOrCreateType(BI->getType(), Unit),
1245 BaseOffset, BFlags);
1246 EltTys.push_back(DTy);
1247 }
1248}
1249
1250/// CollectTemplateParams - A helper function to collect template parameters.
1251llvm::DIArray CGDebugInfo::
1252CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001253 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001254 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001255 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001256 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1257 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001258 StringRef Name;
1259 if (TPList)
1260 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001261 switch (TA.getKind()) {
1262 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001263 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1264 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001265 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001266 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001267 } break;
1268 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001269 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1270 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001271 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001272 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001273 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1274 TemplateParams.push_back(TVP);
1275 } break;
1276 case TemplateArgument::Declaration: {
1277 const ValueDecl *D = TA.getAsDecl();
1278 bool InstanceMember = D->isCXXInstanceMember();
1279 QualType T = InstanceMember
1280 ? CGM.getContext().getMemberPointerType(
1281 D->getType(), cast<RecordDecl>(D->getDeclContext())
1282 ->getTypeForDecl())
1283 : CGM.getContext().getPointerType(D->getType());
1284 llvm::DIType TTy = getOrCreateType(T, Unit);
1285 llvm::Value *V = 0;
1286 // Variable pointer template parameters have a value that is the address
1287 // of the variable.
1288 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1289 V = CGM.GetAddrOfGlobalVar(VD);
1290 // Member function pointers have special support for building them, though
1291 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001292 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001293 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1294 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001295 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1296 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001297 // Member data pointers have special handling too to compute the fixed
1298 // offset within the object.
1299 if (isa<FieldDecl>(D)) {
1300 // These five lines (& possibly the above member function pointer
1301 // handling) might be able to be refactored to use similar code in
1302 // CodeGenModule::getMemberPointerConstant
1303 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1304 CharUnits chars =
1305 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1306 V = CGM.getCXXABI().EmitMemberDataPointer(
1307 cast<MemberPointerType>(T.getTypePtr()), chars);
1308 }
1309 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001310 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1311 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001312 TemplateParams.push_back(TVP);
1313 } break;
1314 case TemplateArgument::NullPtr: {
1315 QualType T = TA.getNullPtrType();
1316 llvm::DIType TTy = getOrCreateType(T, Unit);
1317 llvm::Value *V = 0;
1318 // Special case member data pointer null values since they're actually -1
1319 // instead of zero.
1320 if (const MemberPointerType *MPT =
1321 dyn_cast<MemberPointerType>(T.getTypePtr()))
1322 // But treat member function pointers as simple zero integers because
1323 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1324 // CodeGen grows handling for values of non-null member function
1325 // pointers then perhaps we could remove this special case and rely on
1326 // EmitNullMemberPointer for member function pointers.
1327 if (MPT->isMemberDataPointer())
1328 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1329 if (!V)
1330 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1331 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001332 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001333 TemplateParams.push_back(TVP);
1334 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001335 case TemplateArgument::Template: {
1336 llvm::DITemplateValueParameter TVP =
1337 DBuilder.createTemplateTemplateParameter(
1338 TheCU, Name, llvm::DIType(),
1339 TA.getAsTemplate().getAsTemplateDecl()
1340 ->getQualifiedNameAsString());
1341 TemplateParams.push_back(TVP);
1342 } break;
1343 case TemplateArgument::Pack: {
1344 llvm::DITemplateValueParameter TVP =
1345 DBuilder.createTemplateParameterPack(
1346 TheCU, Name, llvm::DIType(),
1347 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1348 TemplateParams.push_back(TVP);
1349 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001350 case TemplateArgument::Expression: {
1351 const Expr *E = TA.getAsExpr();
1352 QualType T = E->getType();
1353 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1354 assert(V && "Expression in template argument isn't constant");
1355 llvm::DIType TTy = getOrCreateType(T, Unit);
1356 llvm::DITemplateValueParameter TVP =
1357 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1358 V->stripPointerCasts());
1359 TemplateParams.push_back(TVP);
1360 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001361 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001362 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001363 case TemplateArgument::Null:
1364 llvm_unreachable(
1365 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001366 }
1367 }
1368 return DBuilder.getOrCreateArray(TemplateParams);
1369}
1370
1371/// CollectFunctionTemplateParams - A helper function to collect debug
1372/// info for function template parameters.
1373llvm::DIArray CGDebugInfo::
1374CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1375 if (FD->getTemplatedKind() ==
1376 FunctionDecl::TK_FunctionTemplateSpecialization) {
1377 const TemplateParameterList *TList =
1378 FD->getTemplateSpecializationInfo()->getTemplate()
1379 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001380 return CollectTemplateParams(
1381 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001382 }
1383 return llvm::DIArray();
1384}
1385
1386/// CollectCXXTemplateParams - A helper function to collect debug info for
1387/// template parameters.
1388llvm::DIArray CGDebugInfo::
1389CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1390 llvm::DIFile Unit) {
1391 llvm::PointerUnion<ClassTemplateDecl *,
1392 ClassTemplatePartialSpecializationDecl *>
1393 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001394
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001395 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1396 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1397 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1398 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001399 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001400}
1401
1402/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1403llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1404 if (VTablePtrType.isValid())
1405 return VTablePtrType;
1406
1407 ASTContext &Context = CGM.getContext();
1408
1409 /* Function type */
1410 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1411 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1412 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1413 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1414 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1415 "__vtbl_ptr_type");
1416 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1417 return VTablePtrType;
1418}
1419
1420/// getVTableName - Get vtable name for the given Class.
1421StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1422 // Construct gdb compatible name name.
1423 std::string Name = "_vptr$" + RD->getNameAsString();
1424
1425 // Copy this name on the side and use its reference.
1426 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1427 memcpy(StrPtr, Name.data(), Name.length());
1428 return StringRef(StrPtr, Name.length());
1429}
1430
1431
1432/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1433/// debug info entry in EltTys vector.
1434void CGDebugInfo::
1435CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1436 SmallVectorImpl<llvm::Value *> &EltTys) {
1437 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1438
1439 // If there is a primary base then it will hold vtable info.
1440 if (RL.getPrimaryBase())
1441 return;
1442
1443 // If this class is not dynamic then there is not any vtable info to collect.
1444 if (!RD->isDynamicClass())
1445 return;
1446
1447 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1448 llvm::DIType VPTR
1449 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001450 0, Size, 0, 0,
1451 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001452 getOrCreateVTablePtrType(Unit));
1453 EltTys.push_back(VPTR);
1454}
1455
Eric Christopher6537f082013-05-16 00:45:12 +00001456/// getOrCreateRecordType - Emit record type's standalone debug info.
1457llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001458 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001459 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001460 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1461 return T;
1462}
1463
1464/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1465/// debug info.
1466llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001467 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001468 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001469 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001470 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001471 return T;
1472}
1473
David Blaikie27804892013-08-15 20:49:17 +00001474void CGDebugInfo::completeType(const RecordDecl *RD) {
1475 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1476 !CGM.getLangOpts().CPlusPlus)
1477 completeRequiredType(RD);
1478}
1479
1480void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001481 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1482 if (CXXDecl->isDynamicClass())
1483 return;
1484
David Blaikie27804892013-08-15 20:49:17 +00001485 QualType Ty = CGM.getContext().getRecordType(RD);
1486 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001487 if (T && T.isForwardDecl())
1488 completeClassData(RD);
1489}
1490
1491void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1492 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001493 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001494 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001495 void* TyPtr = Ty.getAsOpaquePtr();
1496 if (CompletedTypeCache.count(TyPtr))
1497 return;
1498 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1499 assert(!Res.isForwardDecl());
1500 CompletedTypeCache[TyPtr] = Res;
1501 TypeCache[TyPtr] = Res;
1502}
1503
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001504/// CreateType - get structure or union type.
David Blaikie47251962013-08-22 13:36:01 +00001505llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001506 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001507 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie47251962013-08-22 13:36:01 +00001508 // Always emit declarations for types that aren't required to be complete when
1509 // in limit-debug-info mode. If the type is later found to be required to be
1510 // complete this declaration will be upgraded to a definition by
1511 // `completeRequiredType`.
1512 // If the type is dynamic, only emit the definition in TUs that require class
1513 // data. This is handled by `completeClassData`.
1514 if ((DebugKind <= CodeGenOptions::LimitedDebugInfo &&
David Blaikie5434fc22013-08-20 01:28:15 +00001515 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1516 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001517 llvm::DIDescriptor FDContext =
1518 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Manman Renf3327332013-08-28 21:20:28 +00001519 llvm::DIType RetTy = getOrCreateRecordFwdDecl(Ty, FDContext);
David Blaikie5434fc22013-08-20 01:28:15 +00001520 // FIXME: This is conservatively correct. If we return a non-forward decl
1521 // that's not a full definition (such as those created by
1522 // createContextChain) then getOrCreateType will record is as a complete
1523 // type and we'll never record all its members. But this means we're
1524 // emitting full debug info in TUs where GCC successfully emits a partial
1525 // definition of the type.
1526 if (RetTy.isForwardDecl())
1527 return RetTy;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001528 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001529
David Blaikie27804892013-08-15 20:49:17 +00001530 return CreateTypeDefinition(Ty);
1531}
1532
1533llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1534 RecordDecl *RD = Ty->getDecl();
1535
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001536 // Get overall information about the record type for the debug info.
1537 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1538
1539 // Records and classes and unions can all be recursive. To handle them, we
1540 // first generate a debug descriptor for the struct as a forward declaration.
1541 // Then (if it is a definition) we go through and get debug info for all of
1542 // its members. Finally, we create a descriptor for the complete type (which
1543 // may refer to the forward decl if the struct is recursive) and replace all
1544 // uses of the forward declaration with the final definition.
1545
David Blaikie4a077162013-08-12 22:24:20 +00001546 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001547 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001548 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001549
1550 if (FwdDecl.isForwardDecl())
1551 return FwdDecl;
1552
David Blaikie498298d2013-08-18 16:55:33 +00001553 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1554 CollectContainingType(CXXDecl, FwdDecl);
1555
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001556 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001557 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001558 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1559
Adrian Prantl4919de62013-03-06 22:03:30 +00001560 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001561 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1562
1563 // Convert all the elements.
1564 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001565 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001566
1567 // Note: The split of CXXDecl information here is intentional, the
1568 // gdb tests will depend on a certain ordering at printout. The debug
1569 // information offsets are still correct if we merge them all together
1570 // though.
1571 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1572 if (CXXDecl) {
1573 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1574 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1575 }
1576
Eric Christopher0395de32013-01-16 01:22:32 +00001577 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001578 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001579 if (CXXDecl) {
1580 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1581 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001582 }
1583
1584 LexicalBlockStack.pop_back();
1585 RegionMap.erase(Ty->getDecl());
1586
1587 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001588 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001589
Eric Christopherf068c922013-04-02 22:59:11 +00001590 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1591 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001592}
1593
1594/// CreateType - get objective-c object type.
1595llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1596 llvm::DIFile Unit) {
1597 // Ignore protocols.
1598 return getOrCreateType(Ty->getBaseType(), Unit);
1599}
1600
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001601
1602/// \return true if Getter has the default name for the property PD.
1603static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1604 const ObjCMethodDecl *Getter) {
1605 assert(PD);
1606 if (!Getter)
1607 return true;
1608
1609 assert(Getter->getDeclName().isObjCZeroArgSelector());
1610 return PD->getName() ==
1611 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1612}
1613
1614/// \return true if Setter has the default name for the property PD.
1615static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1616 const ObjCMethodDecl *Setter) {
1617 assert(PD);
1618 if (!Setter)
1619 return true;
1620
1621 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001622 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001623 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1624}
1625
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001626/// CreateType - get objective-c interface type.
1627llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1628 llvm::DIFile Unit) {
1629 ObjCInterfaceDecl *ID = Ty->getDecl();
1630 if (!ID)
1631 return llvm::DIType();
1632
1633 // Get overall information about the record type for the debug info.
1634 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1635 unsigned Line = getLineNumber(ID->getLocation());
1636 unsigned RuntimeLang = TheCU.getLanguage();
1637
1638 // If this is just a forward declaration return a special forward-declaration
1639 // debug type since we won't be able to lay out the entire type.
1640 ObjCInterfaceDecl *Def = ID->getDefinition();
1641 if (!Def) {
1642 llvm::DIType FwdDecl =
1643 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001644 ID->getName(), TheCU, DefUnit, Line,
1645 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001646 return FwdDecl;
1647 }
1648
1649 ID = Def;
1650
1651 // Bit size, align and offset of the type.
1652 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1653 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1654
1655 unsigned Flags = 0;
1656 if (ID->getImplementation())
1657 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1658
Eric Christopherf068c922013-04-02 22:59:11 +00001659 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001660 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1661 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001662 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001663
1664 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1665 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001666 QualType QualTy = QualType(Ty, 0);
1667 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001668
Eric Christopherd3003dc2013-07-14 21:00:07 +00001669 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001670 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001671 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1672
1673 // Convert all the elements.
1674 SmallVector<llvm::Value *, 16> EltTys;
1675
1676 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1677 if (SClass) {
1678 llvm::DIType SClassTy =
1679 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1680 if (!SClassTy.isValid())
1681 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001682
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001683 llvm::DIType InhTag =
1684 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1685 EltTys.push_back(InhTag);
1686 }
1687
Eric Christopherd3003dc2013-07-14 21:00:07 +00001688 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001689 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1690 E = ID->prop_end(); I != E; ++I) {
1691 const ObjCPropertyDecl *PD = *I;
1692 SourceLocation Loc = PD->getLocation();
1693 llvm::DIFile PUnit = getOrCreateFile(Loc);
1694 unsigned PLine = getLineNumber(Loc);
1695 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1696 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1697 llvm::MDNode *PropertyNode =
1698 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001699 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001700 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001701 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001702 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001703 getSelectorName(PD->getSetterName()),
1704 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001705 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001706 EltTys.push_back(PropertyNode);
1707 }
1708
1709 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1710 unsigned FieldNo = 0;
1711 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1712 Field = Field->getNextIvar(), ++FieldNo) {
1713 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1714 if (!FieldTy.isValid())
1715 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001716
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001717 StringRef FieldName = Field->getName();
1718
1719 // Ignore unnamed fields.
1720 if (FieldName.empty())
1721 continue;
1722
1723 // Get the location for the field.
1724 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1725 unsigned FieldLine = getLineNumber(Field->getLocation());
1726 QualType FType = Field->getType();
1727 uint64_t FieldSize = 0;
1728 unsigned FieldAlign = 0;
1729
1730 if (!FType->isIncompleteArrayType()) {
1731
1732 // Bit size, align and offset of the type.
1733 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001734 ? Field->getBitWidthValue(CGM.getContext())
1735 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001736 FieldAlign = CGM.getContext().getTypeAlign(FType);
1737 }
1738
1739 uint64_t FieldOffset;
1740 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1741 // We don't know the runtime offset of an ivar if we're using the
1742 // non-fragile ABI. For bitfields, use the bit offset into the first
1743 // byte of storage of the bitfield. For other fields, use zero.
1744 if (Field->isBitField()) {
1745 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1746 CGM, ID, Field);
1747 FieldOffset %= CGM.getContext().getCharWidth();
1748 } else {
1749 FieldOffset = 0;
1750 }
1751 } else {
1752 FieldOffset = RL.getFieldOffset(FieldNo);
1753 }
1754
1755 unsigned Flags = 0;
1756 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1757 Flags = llvm::DIDescriptor::FlagProtected;
1758 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1759 Flags = llvm::DIDescriptor::FlagPrivate;
1760
1761 llvm::MDNode *PropertyNode = NULL;
1762 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001763 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001764 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1765 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001766 SourceLocation Loc = PD->getLocation();
1767 llvm::DIFile PUnit = getOrCreateFile(Loc);
1768 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001769 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1770 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1771 PropertyNode =
1772 DBuilder.createObjCProperty(PD->getName(),
1773 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001774 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001775 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001776 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001777 getSelectorName(PD->getSetterName()),
1778 PD->getPropertyAttributes(),
1779 getOrCreateType(PD->getType(), PUnit));
1780 }
1781 }
1782 }
1783 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1784 FieldLine, FieldSize, FieldAlign,
1785 FieldOffset, Flags, FieldTy,
1786 PropertyNode);
1787 EltTys.push_back(FieldTy);
1788 }
1789
1790 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001791 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001792
1793 // If the implementation is not yet set, we do not want to mark it
1794 // as complete. An implementation may declare additional
1795 // private ivars that we would miss otherwise.
1796 if (ID->getImplementation() == 0)
1797 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001798
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001799 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001800 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001801}
1802
1803llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1804 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1805 int64_t Count = Ty->getNumElements();
1806 if (Count == 0)
1807 // If number of elements are not known then this is an unbounded array.
1808 // Use Count == -1 to express such arrays.
1809 Count = -1;
1810
1811 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1812 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1813
1814 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1815 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1816
1817 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1818}
1819
1820llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1821 llvm::DIFile Unit) {
1822 uint64_t Size;
1823 uint64_t Align;
1824
1825 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1826 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1827 Size = 0;
1828 Align =
1829 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1830 } else if (Ty->isIncompleteArrayType()) {
1831 Size = 0;
1832 if (Ty->getElementType()->isIncompleteType())
1833 Align = 0;
1834 else
1835 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001836 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001837 Size = 0;
1838 Align = 0;
1839 } else {
1840 // Size and align of the whole array, not the element type.
1841 Size = CGM.getContext().getTypeSize(Ty);
1842 Align = CGM.getContext().getTypeAlign(Ty);
1843 }
1844
1845 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1846 // interior arrays, do we care? Why aren't nested arrays represented the
1847 // obvious/recursive way?
1848 SmallVector<llvm::Value *, 8> Subscripts;
1849 QualType EltTy(Ty, 0);
1850 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1851 // If the number of elements is known, then count is that number. Otherwise,
1852 // it's -1. This allows us to represent a subrange with an array of 0
1853 // elements, like this:
1854 //
1855 // struct foo {
1856 // int x[0];
1857 // };
1858 int64_t Count = -1; // Count == -1 is an unbounded array.
1859 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1860 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001861
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001862 // FIXME: Verify this is right for VLAs.
1863 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1864 EltTy = Ty->getElementType();
1865 }
1866
1867 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1868
Eric Christopher6537f082013-05-16 00:45:12 +00001869 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001870 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1871 SubscriptArray);
1872 return DbgTy;
1873}
1874
Eric Christopher6537f082013-05-16 00:45:12 +00001875llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001876 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001877 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001878 Ty, Ty->getPointeeType(), Unit);
1879}
1880
Eric Christopher6537f082013-05-16 00:45:12 +00001881llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001882 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001883 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001884 Ty, Ty->getPointeeType(), Unit);
1885}
1886
Eric Christopher6537f082013-05-16 00:45:12 +00001887llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001888 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001889 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1890 if (!Ty->getPointeeType()->isFunctionType())
1891 return DBuilder.createMemberPointerType(
David Blaikie47251962013-08-22 13:36:01 +00001892 getOrCreateType(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001893 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1894 CGM.getContext().getPointerType(
1895 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1896 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1897 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001898}
1899
Eric Christopher6537f082013-05-16 00:45:12 +00001900llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001901 llvm::DIFile U) {
1902 // Ignore the atomic wrapping
1903 // FIXME: What is the correct representation?
1904 return getOrCreateType(Ty->getValueType(), U);
1905}
1906
1907/// CreateEnumType - get enumeration type.
Manman Ren0a0be742013-08-28 21:46:36 +00001908llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Renf3327332013-08-28 21:20:28 +00001909 const EnumDecl *ED = Ty->getDecl();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001910 uint64_t Size = 0;
1911 uint64_t Align = 0;
1912 if (!ED->getTypeForDecl()->isIncompleteType()) {
1913 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1914 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1915 }
1916
Manman Renf1acc312013-08-29 18:51:51 +00001917 SmallString<256> FullName;
1918 getUniqueTagTypeName(Ty, CGM, TheCU, FullName);
1919 if (!FullName.empty()) {
1920 QualType QTy(Ty, 0);
1921 RetainedTypes.push_back(QTy.getAsOpaquePtr());
1922 }
1923
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001924 // If this is just a forward declaration, construct an appropriately
1925 // marked node and just return it.
1926 if (!ED->getDefinition()) {
1927 llvm::DIDescriptor EDContext;
1928 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1929 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1930 unsigned Line = getLineNumber(ED->getLocation());
1931 StringRef EDName = ED->getName();
1932 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1933 EDName, EDContext, DefUnit, Line, 0,
Manman Renf1acc312013-08-29 18:51:51 +00001934 Size, Align, FullName.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001935 }
1936
1937 // Create DIEnumerator elements for each enumerator.
1938 SmallVector<llvm::Value *, 16> Enumerators;
1939 ED = ED->getDefinition();
1940 for (EnumDecl::enumerator_iterator
1941 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1942 Enum != EnumEnd; ++Enum) {
1943 Enumerators.push_back(
1944 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001945 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001946 }
1947
1948 // Return a CompositeType for the enum itself.
1949 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1950
1951 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1952 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001953 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001954 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001955 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001956 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001957 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001958 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1959 Size, Align, EltArray,
Manman Renf1acc312013-08-29 18:51:51 +00001960 ClassTy, FullName.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961 return DbgTy;
1962}
1963
David Blaikie4b12be62013-01-21 04:37:12 +00001964static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1965 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001966 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001967 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001968 QualType LastT = T;
1969 switch (T->getTypeClass()) {
1970 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001971 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001972 case Type::TemplateSpecialization:
1973 T = cast<TemplateSpecializationType>(T)->desugar();
1974 break;
1975 case Type::TypeOfExpr:
1976 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1977 break;
1978 case Type::TypeOf:
1979 T = cast<TypeOfType>(T)->getUnderlyingType();
1980 break;
1981 case Type::Decltype:
1982 T = cast<DecltypeType>(T)->getUnderlyingType();
1983 break;
1984 case Type::UnaryTransform:
1985 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1986 break;
1987 case Type::Attributed:
1988 T = cast<AttributedType>(T)->getEquivalentType();
1989 break;
1990 case Type::Elaborated:
1991 T = cast<ElaboratedType>(T)->getNamedType();
1992 break;
1993 case Type::Paren:
1994 T = cast<ParenType>(T)->getInnerType();
1995 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001996 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001997 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001998 break;
1999 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00002000 QualType DT = cast<AutoType>(T)->getDeducedType();
2001 if (DT.isNull())
2002 return T;
2003 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002004 break;
2005 }
Eric Christopher6537f082013-05-16 00:45:12 +00002006
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002007 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00002008 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002009 } while (true);
2010}
2011
Eric Christopherf0890c42013-05-16 00:52:20 +00002012/// getType - Get the type from the cache or return null type if it doesn't
2013/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002014llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2015
2016 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002017 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00002018
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002019 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002020 if (Ty->getTypeClass() == Type::ObjCInterface) {
2021 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2022 if (V)
2023 return llvm::DIType(cast<llvm::MDNode>(V));
2024 else return llvm::DIType();
2025 }
2026
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002027 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2028 TypeCache.find(Ty.getAsOpaquePtr());
2029 if (it != TypeCache.end()) {
2030 // Verify that the debug info still exists.
2031 if (llvm::Value *V = it->second)
2032 return llvm::DIType(cast<llvm::MDNode>(V));
2033 }
2034
2035 return llvm::DIType();
2036}
2037
2038/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2039/// doesn't exist.
2040llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2041
2042 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002043 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002044
2045 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00002046 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2048 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00002049 if (it != CompletedTypeCache.end())
2050 V = it->second;
2051 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002052 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002053 }
2054
Adrian Prantl4919de62013-03-06 22:03:30 +00002055 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00002056 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002057}
2058
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002059/// getCachedInterfaceTypeOrNull - Get the type from the interface
2060/// cache, unless it needs to regenerated. Otherwise return null.
2061llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2062 // Is there a cached interface that hasn't changed?
2063 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2064 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2065
2066 if (it1 != ObjCInterfaceCache.end())
2067 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2068 if (Checksum(Decl) == it1->second.second)
2069 // Return cached forward declaration.
2070 return it1->second.first;
2071
2072 return 0;
2073}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002074
2075/// getOrCreateType - Get the type from the cache or create a new
2076/// one if necessary.
David Blaikie47251962013-08-22 13:36:01 +00002077llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002078 if (Ty.isNull())
2079 return llvm::DIType();
2080
2081 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002082 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002083
David Blaikie47251962013-08-22 13:36:01 +00002084 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002085 return T;
2086
2087 // Otherwise create the type.
David Blaikie47251962013-08-22 13:36:01 +00002088 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002089 void* TyPtr = Ty.getAsOpaquePtr();
2090
2091 // And update the type cache.
2092 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002093
David Blaikie492b1022013-08-15 21:21:19 +00002094 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2095 // into the cache - but getTypeOrNull has a special case for cached interface
2096 // types. We should probably just pull that out as a special case for the
2097 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002098 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002099 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002100 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2101 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2102 // Interface types may have elements added to them by a
2103 // subsequent implementation or extension, so we keep them in
2104 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002105 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002106 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002107 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2108 if (V.first)
2109 return llvm::DIType(cast<llvm::MDNode>(V.first));
2110 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2111 Decl->getName(), TheCU, Unit,
2112 getLineNumber(Decl->getLocation()),
2113 TheCU.getLanguage());
2114 // Store the forward declaration in the cache.
2115 V.first = TC;
2116 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002117
David Blaikiee2eb89a2013-05-21 18:29:40 +00002118 // Register the type for replacement in finalize().
2119 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2120
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002121 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002122 }
2123
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002124 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002125 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002126
2127 return Res;
2128}
2129
Adrian Prantlb5a50072013-06-07 01:10:41 +00002130/// Currently the checksum of an interface includes the number of
2131/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002132unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002133 // The assumption is that the number of ivars can only increase
2134 // monotonically, so it is safe to just use their current number as
2135 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002136 unsigned Sum = 0;
2137 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2138 Ivar != 0; Ivar = Ivar->getNextIvar())
2139 ++Sum;
2140
2141 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002142}
2143
2144ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2145 switch (Ty->getTypeClass()) {
2146 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002147 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2148 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002149 case Type::ObjCInterface:
2150 return cast<ObjCInterfaceType>(Ty)->getDecl();
2151 default:
2152 return 0;
2153 }
2154}
2155
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002156/// CreateTypeNode - Create a new debug type node.
David Blaikie47251962013-08-22 13:36:01 +00002157llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002158 // Handle qualifiers, which recursively handles what they refer to.
2159 if (Ty.hasLocalQualifiers())
David Blaikie47251962013-08-22 13:36:01 +00002160 return CreateQualifiedType(Ty, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002161
2162 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002163
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002164 // Work out details of type.
2165 switch (Ty->getTypeClass()) {
2166#define TYPE(Class, Base)
2167#define ABSTRACT_TYPE(Class, Base)
2168#define NON_CANONICAL_TYPE(Class, Base)
2169#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2170#include "clang/AST/TypeNodes.def"
2171 llvm_unreachable("Dependent types cannot show up in debug information");
2172
2173 case Type::ExtVector:
2174 case Type::Vector:
2175 return CreateType(cast<VectorType>(Ty), Unit);
2176 case Type::ObjCObjectPointer:
2177 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2178 case Type::ObjCObject:
2179 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2180 case Type::ObjCInterface:
2181 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2182 case Type::Builtin:
2183 return CreateType(cast<BuiltinType>(Ty));
2184 case Type::Complex:
2185 return CreateType(cast<ComplexType>(Ty));
2186 case Type::Pointer:
2187 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002188 case Type::Decayed:
2189 // Decayed types are just pointers in LLVM and DWARF.
2190 return CreateType(
2191 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002192 case Type::BlockPointer:
2193 return CreateType(cast<BlockPointerType>(Ty), Unit);
2194 case Type::Typedef:
David Blaikie47251962013-08-22 13:36:01 +00002195 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002196 case Type::Record:
David Blaikie47251962013-08-22 13:36:01 +00002197 return CreateType(cast<RecordType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002198 case Type::Enum:
Manman Renf3327332013-08-28 21:20:28 +00002199 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002200 case Type::FunctionProto:
2201 case Type::FunctionNoProto:
2202 return CreateType(cast<FunctionType>(Ty), Unit);
2203 case Type::ConstantArray:
2204 case Type::VariableArray:
2205 case Type::IncompleteArray:
2206 return CreateType(cast<ArrayType>(Ty), Unit);
2207
2208 case Type::LValueReference:
2209 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2210 case Type::RValueReference:
2211 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2212
2213 case Type::MemberPointer:
2214 return CreateType(cast<MemberPointerType>(Ty), Unit);
2215
2216 case Type::Atomic:
2217 return CreateType(cast<AtomicType>(Ty), Unit);
2218
2219 case Type::Attributed:
2220 case Type::TemplateSpecialization:
2221 case Type::Elaborated:
2222 case Type::Paren:
2223 case Type::SubstTemplateTypeParm:
2224 case Type::TypeOfExpr:
2225 case Type::TypeOf:
2226 case Type::Decltype:
2227 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002228 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002229 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002230 case Type::Auto:
2231 Diag = "auto";
2232 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002233 }
Eric Christopher6537f082013-05-16 00:45:12 +00002234
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002235 assert(Diag && "Fall through without a diagnostic?");
2236 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2237 "debug information for %0 is not yet supported");
2238 CGM.getDiags().Report(DiagID)
2239 << Diag;
2240 return llvm::DIType();
2241}
2242
2243/// getOrCreateLimitedType - Get the type from the cache or create a new
2244/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002245llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002246 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002247 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002248
David Blaikieeaacc882013-08-20 21:03:29 +00002249 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002250
2251 // We may have cached a forward decl when we could have created
2252 // a non-forward decl. Go ahead and create a non-forward decl
2253 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002254 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002255
2256 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002257 llvm::DICompositeType Res = CreateLimitedType(Ty);
2258
2259 // Propagate members from the declaration to the definition
2260 // CreateType(const RecordType*) will overwrite this with the members in the
2261 // correct order if the full type is needed.
2262 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002263
Eric Christopherb2d13922013-07-18 00:52:50 +00002264 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002265 ReplaceMap.push_back(
2266 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002267
2268 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002269 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002270 return Res;
2271}
2272
2273// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002274llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002275 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002276
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002277 // Get overall information about the record type for the debug info.
2278 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2279 unsigned Line = getLineNumber(RD->getLocation());
2280 StringRef RDName = getClassName(RD);
2281
2282 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002283 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002284 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2285 else
2286 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2287
David Blaikiec138ff52013-08-18 17:36:19 +00002288 // If we ended up creating the type during the context chain construction,
2289 // just return that.
2290 // FIXME: this could be dealt with better if the type was recorded as
2291 // completed before we started this (see the CompletedTypeCache usage in
2292 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2293 // be pushed to before context creation, but after it was known to be
2294 // destined for completion (might still have an issue if this caller only
2295 // required a declaration but the context construction ended up creating a
2296 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002297 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2298 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002299 return T;
2300
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002301 // If this is just a forward declaration, construct an appropriately
2302 // marked node and just return it.
2303 if (!RD->getDefinition())
Manman Renf3327332013-08-28 21:20:28 +00002304 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002305
2306 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2307 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002308 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002309
Manman Renf1acc312013-08-29 18:51:51 +00002310 SmallString<256> FullName;
2311 getUniqueTagTypeName(Ty, CGM, TheCU, FullName);
2312 if (!FullName.empty()) {
2313 QualType QTy(Ty, 0);
2314 RetainedTypes.push_back(QTy.getAsOpaquePtr());
2315 }
2316
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002317 if (RD->isUnion())
2318 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Renf1acc312013-08-29 18:51:51 +00002319 Size, Align, 0, llvm::DIArray(), 0,
2320 FullName.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002321 else if (RD->isClass()) {
2322 // FIXME: This could be a struct type giving a default visibility different
2323 // than C++ class type, but needs llvm metadata changes first.
2324 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002325 Size, Align, 0, 0, llvm::DIType(),
2326 llvm::DIArray(), llvm::DIType(),
Manman Renf1acc312013-08-29 18:51:51 +00002327 llvm::DIArray(), FullName.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002328 } else
2329 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002330 Size, Align, 0, llvm::DIType(),
Manman Renf1acc312013-08-29 18:51:51 +00002331 llvm::DIArray(), 0, 0, FullName.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002332
2333 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002334 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002335
David Blaikie498298d2013-08-18 16:55:33 +00002336 if (const ClassTemplateSpecializationDecl *TSpecial =
2337 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2338 RealDecl.setTypeArray(llvm::DIArray(),
2339 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002340 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002341}
2342
David Blaikie498298d2013-08-18 16:55:33 +00002343void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2344 llvm::DICompositeType RealDecl) {
2345 // A class's primary base or the class itself contains the vtable.
2346 llvm::DICompositeType ContainingType;
2347 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2348 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2349 // Seek non virtual primary base root.
2350 while (1) {
2351 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2352 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2353 if (PBT && !BRL.isPrimaryBaseVirtual())
2354 PBase = PBT;
2355 else
2356 break;
2357 }
2358 ContainingType = llvm::DICompositeType(
2359 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2360 getOrCreateFile(RD->getLocation())));
2361 } else if (RD->isDynamicClass())
2362 ContainingType = RealDecl;
2363
2364 RealDecl.setContainingType(ContainingType);
2365}
2366
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002367/// CreateMemberType - Create new member and increase Offset by FType's size.
2368llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2369 StringRef Name,
2370 uint64_t *Offset) {
2371 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2372 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2373 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2374 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2375 FieldSize, FieldAlign,
2376 *Offset, 0, FieldTy);
2377 *Offset += FieldSize;
2378 return Ty;
2379}
2380
David Blaikie9faebd22013-05-20 04:58:53 +00002381llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2382 // We only need a declaration (not a definition) of the type - so use whatever
2383 // we would otherwise do to get a type for a pointee. (forward declarations in
2384 // limited debug info, full definitions (if the type definition is available)
2385 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002386 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2387 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie47251962013-08-22 13:36:01 +00002388 getOrCreateFile(TD->getLocation()));
David Blaikie9faebd22013-05-20 04:58:53 +00002389 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2390 // This doesn't handle providing declarations (for functions or variables) for
2391 // entities without definitions in this TU, nor when the definition proceeds
2392 // the call to this function.
2393 // FIXME: This should be split out into more specific maps with support for
2394 // emitting forward declarations and merging definitions with declarations,
2395 // the same way as we do for types.
2396 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2397 DeclCache.find(D->getCanonicalDecl());
2398 if (I == DeclCache.end())
2399 return llvm::DIDescriptor();
2400 llvm::Value *V = I->second;
2401 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2402}
2403
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002404/// getFunctionDeclaration - Return debug info descriptor to describe method
2405/// declaration for the given method definition.
2406llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002407 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2408 return llvm::DISubprogram();
2409
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002410 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2411 if (!FD) return llvm::DISubprogram();
2412
2413 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002414 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002415
2416 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2417 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002418 if (MI == SPCache.end()) {
Eric Christopherac7c25f2013-08-28 23:12:10 +00002419 if (const CXXMethodDecl *MD =
2420 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002421 llvm::DICompositeType T(S);
Eric Christopherac7c25f2013-08-28 23:12:10 +00002422 llvm::DISubprogram SP =
2423 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikied6d5d692013-08-09 17:20:05 +00002424 T.addMember(SP);
2425 return SP;
2426 }
2427 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002428 if (MI != SPCache.end()) {
2429 llvm::Value *V = MI->second;
2430 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002431 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002432 return SP;
2433 }
2434
2435 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2436 E = FD->redecls_end(); I != E; ++I) {
2437 const FunctionDecl *NextFD = *I;
2438 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2439 MI = SPCache.find(NextFD->getCanonicalDecl());
2440 if (MI != SPCache.end()) {
2441 llvm::Value *V = MI->second;
2442 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002443 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002444 return SP;
2445 }
2446 }
2447 return llvm::DISubprogram();
2448}
2449
2450// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2451// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002452llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2453 QualType FnType,
2454 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002455 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2456 // Create fake but valid subroutine type. Otherwise
2457 // llvm::DISubprogram::Verify() would return false, and
2458 // subprogram DIE will miss DW_AT_decl_file and
2459 // DW_AT_decl_line fields.
2460 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002461
2462 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2463 return getOrCreateMethodType(Method, F);
2464 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2465 // Add "self" and "_cmd"
2466 SmallVector<llvm::Value *, 16> Elts;
2467
2468 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002469 QualType ResultTy = OMethod->getResultType();
2470
2471 // Replace the instancetype keyword with the actual type.
2472 if (ResultTy == CGM.getContext().getObjCInstanceType())
2473 ResultTy = CGM.getContext().getPointerType(
2474 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2475
Adrian Prantl566a9c32013-05-10 21:08:31 +00002476 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002477 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002478 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2479 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2480 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002481 // "_cmd" pointer is always second argument.
2482 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2483 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2484 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002485 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002486 PE = OMethod->param_end(); PI != PE; ++PI)
2487 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2488
2489 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2490 return DBuilder.createSubroutineType(F, EltTypeArray);
2491 }
David Blaikie9a845292013-05-22 23:22:42 +00002492 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002493}
2494
2495/// EmitFunctionStart - Constructs the debug code for entering a function.
2496void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2497 llvm::Function *Fn,
2498 CGBuilderTy &Builder) {
2499
2500 StringRef Name;
2501 StringRef LinkageName;
2502
2503 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2504
2505 const Decl *D = GD.getDecl();
2506 // Function may lack declaration in source code if it is created by Clang
2507 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2508 bool HasDecl = (D != 0);
2509 // Use the location of the declaration.
2510 SourceLocation Loc;
2511 if (HasDecl)
2512 Loc = D->getLocation();
2513
2514 unsigned Flags = 0;
2515 llvm::DIFile Unit = getOrCreateFile(Loc);
2516 llvm::DIDescriptor FDContext(Unit);
2517 llvm::DIArray TParamsArray;
2518 if (!HasDecl) {
2519 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002520 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002521 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2522 // If there is a DISubprogram for this function available then use it.
2523 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2524 FI = SPCache.find(FD->getCanonicalDecl());
2525 if (FI != SPCache.end()) {
2526 llvm::Value *V = FI->second;
2527 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2528 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2529 llvm::MDNode *SPN = SP;
2530 LexicalBlockStack.push_back(SPN);
2531 RegionMap[D] = llvm::WeakVH(SP);
2532 return;
2533 }
2534 }
2535 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002536 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002537 if (FD->hasPrototype()) {
2538 LinkageName = CGM.getMangledName(GD);
2539 Flags |= llvm::DIDescriptor::FlagPrototyped;
2540 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002541 // No need to replicate the linkage name if it isn't different from the
2542 // subprogram name, no need to have it at all unless coverage is enabled or
2543 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002544 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002545 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2546 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002547 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548 LinkageName = StringRef();
2549
Eric Christopher13c97672013-05-16 00:45:23 +00002550 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002551 if (const NamespaceDecl *NSDecl =
2552 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2553 FDContext = getOrCreateNameSpace(NSDecl);
2554 else if (const RecordDecl *RDecl =
2555 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2556 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2557
2558 // Collect template parameters.
2559 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2560 }
2561 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2562 Name = getObjCMethodName(OMD);
2563 Flags |= llvm::DIDescriptor::FlagPrototyped;
2564 } else {
2565 // Use llvm function name.
2566 Name = Fn->getName();
2567 Flags |= llvm::DIDescriptor::FlagPrototyped;
2568 }
2569 if (!Name.empty() && Name[0] == '\01')
2570 Name = Name.substr(1);
2571
2572 unsigned LineNo = getLineNumber(Loc);
2573 if (!HasDecl || D->isImplicit())
2574 Flags |= llvm::DIDescriptor::FlagArtificial;
2575
David Blaikie23e66db2013-06-22 00:09:36 +00002576 llvm::DISubprogram SP = DBuilder.createFunction(
2577 FDContext, Name, LinkageName, Unit, LineNo,
2578 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2579 true /*definition*/, getLineNumber(CurLoc), Flags,
2580 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002581 if (HasDecl)
2582 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002583
2584 // Push function on region stack.
2585 llvm::MDNode *SPN = SP;
2586 LexicalBlockStack.push_back(SPN);
2587 if (HasDecl)
2588 RegionMap[D] = llvm::WeakVH(SP);
2589}
2590
2591/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002592/// information in the source file. If the location is invalid, the
2593/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002594void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2595 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002596 // Update our current location
2597 setLocation(Loc);
2598
2599 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2600
2601 // Don't bother if things are the same as last time.
2602 SourceManager &SM = CGM.getContext().getSourceManager();
2603 if (CurLoc == PrevLoc ||
2604 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2605 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002606 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2607 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2608 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002609 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002610
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002611 // Update last state.
2612 PrevLoc = CurLoc;
2613
2614 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002615 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2616 (getLineNumber(CurLoc),
2617 getColumnNumber(CurLoc, ForceColumnInfo),
2618 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619}
2620
2621/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2622/// the stack.
2623void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2624 llvm::DIDescriptor D =
2625 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2626 llvm::DIDescriptor() :
2627 llvm::DIDescriptor(LexicalBlockStack.back()),
2628 getOrCreateFile(CurLoc),
2629 getLineNumber(CurLoc),
2630 getColumnNumber(CurLoc));
2631 llvm::MDNode *DN = D;
2632 LexicalBlockStack.push_back(DN);
2633}
2634
2635/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2636/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002637void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2638 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002639 // Set our current location.
2640 setLocation(Loc);
2641
2642 // Create a new lexical block and push it on the stack.
2643 CreateLexicalBlock(Loc);
2644
2645 // Emit a line table change for the current location inside the new scope.
2646 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2647 getColumnNumber(Loc),
2648 LexicalBlockStack.back()));
2649}
2650
2651/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2652/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002653void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2654 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002655 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2656
2657 // Provide an entry in the line table for the end of the block.
2658 EmitLocation(Builder, Loc);
2659
2660 LexicalBlockStack.pop_back();
2661}
2662
2663/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2664void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2665 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2666 unsigned RCount = FnBeginRegionCount.back();
2667 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2668
2669 // Pop all regions for this function.
2670 while (LexicalBlockStack.size() != RCount)
2671 EmitLexicalBlockEnd(Builder, CurLoc);
2672 FnBeginRegionCount.pop_back();
2673}
2674
Eric Christopher6537f082013-05-16 00:45:12 +00002675// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002676// See BuildByRefType.
2677llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2678 uint64_t *XOffset) {
2679
2680 SmallVector<llvm::Value *, 5> EltTys;
2681 QualType FType;
2682 uint64_t FieldSize, FieldOffset;
2683 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002684
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002685 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002686 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002687
2688 FieldOffset = 0;
2689 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2690 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2691 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2692 FType = CGM.getContext().IntTy;
2693 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2694 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2695
2696 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2697 if (HasCopyAndDispose) {
2698 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2699 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2700 &FieldOffset));
2701 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2702 &FieldOffset));
2703 }
2704 bool HasByrefExtendedLayout;
2705 Qualifiers::ObjCLifetime Lifetime;
2706 if (CGM.getContext().getByrefLifetime(Type,
2707 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002708 && HasByrefExtendedLayout) {
2709 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002710 EltTys.push_back(CreateMemberType(Unit, FType,
2711 "__byref_variable_layout",
2712 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002713 }
Eric Christopher6537f082013-05-16 00:45:12 +00002714
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002715 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2716 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002717 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002718 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2720 CharUnits AlignedOffsetInBytes
2721 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2722 CharUnits NumPaddingBytes
2723 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002724
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002725 if (NumPaddingBytes.isPositive()) {
2726 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2727 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2728 pad, ArrayType::Normal, 0);
2729 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2730 }
2731 }
Eric Christopher6537f082013-05-16 00:45:12 +00002732
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002733 FType = Type;
2734 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2735 FieldSize = CGM.getContext().getTypeSize(FType);
2736 FieldAlign = CGM.getContext().toBits(Align);
2737
Eric Christopher6537f082013-05-16 00:45:12 +00002738 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2740 0, FieldSize, FieldAlign,
2741 FieldOffset, 0, FieldTy);
2742 EltTys.push_back(FieldTy);
2743 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002744
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002745 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002746
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002747 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002748
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002749 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002750 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002751}
2752
2753/// EmitDeclare - Emit local variable declaration debug info.
2754void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002755 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002756 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002757 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002758 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2759
David Blaikiefc946272013-08-19 03:37:48 +00002760 bool Unwritten =
2761 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2762 cast<Decl>(VD->getDeclContext())->isImplicit());
2763 llvm::DIFile Unit;
2764 if (!Unwritten)
2765 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002766 llvm::DIType Ty;
2767 uint64_t XOffset = 0;
2768 if (VD->hasAttr<BlocksAttr>())
2769 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002770 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002771 Ty = getOrCreateType(VD->getType(), Unit);
2772
2773 // If there is no debug info for this type then do not emit debug info
2774 // for this variable.
2775 if (!Ty)
2776 return;
2777
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002778 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002779 unsigned Line = 0;
2780 unsigned Column = 0;
2781 if (!Unwritten) {
2782 Line = getLineNumber(VD->getLocation());
2783 Column = getColumnNumber(VD->getLocation());
2784 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 unsigned Flags = 0;
2786 if (VD->isImplicit())
2787 Flags |= llvm::DIDescriptor::FlagArtificial;
2788 // If this is the first argument and it is implicit then
2789 // give it an object pointer flag.
2790 // FIXME: There has to be a better way to do this, but for static
2791 // functions there won't be an implicit param at arg1 and
2792 // otherwise it is 'self' or 'this'.
2793 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2794 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002795 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002796 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2797 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002798 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799
2800 llvm::MDNode *Scope = LexicalBlockStack.back();
2801
2802 StringRef Name = VD->getName();
2803 if (!Name.empty()) {
2804 if (VD->hasAttr<BlocksAttr>()) {
2805 CharUnits offset = CharUnits::fromQuantity(32);
2806 SmallVector<llvm::Value *, 9> addr;
2807 llvm::Type *Int64Ty = CGM.Int64Ty;
2808 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2809 // offset of __forwarding field
2810 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002811 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002812 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2813 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2814 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2815 // offset of x field
2816 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2817 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2818
2819 // Create the descriptor for the variable.
2820 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002821 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002822 llvm::DIDescriptor(Scope),
2823 VD->getName(), Unit, Line, Ty,
2824 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002825
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002826 // Insert an llvm.dbg.declare into the current block.
2827 llvm::Instruction *Call =
2828 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2829 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2830 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002831 }
David Blaikie436653b2013-01-05 05:58:35 +00002832 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2833 // If VD is an anonymous union then Storage represents value for
2834 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002835 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002836 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002837 for (RecordDecl::field_iterator I = RD->field_begin(),
2838 E = RD->field_end();
2839 I != E; ++I) {
2840 FieldDecl *Field = *I;
2841 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2842 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002843
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002844 // Ignore unnamed fields. Do not ignore unnamed records.
2845 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2846 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002847
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002848 // Use VarDecl's Tag, Scope and Line number.
2849 llvm::DIVariable D =
2850 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002851 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002852 CGM.getLangOpts().Optimize, Flags,
2853 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002854
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002855 // Insert an llvm.dbg.declare into the current block.
2856 llvm::Instruction *Call =
2857 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2858 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2859 }
David Blaikied8180cf2013-01-05 20:03:07 +00002860 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002861 }
2862 }
David Blaikie436653b2013-01-05 05:58:35 +00002863
2864 // Create the descriptor for the variable.
2865 llvm::DIVariable D =
2866 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2867 Name, Unit, Line, Ty,
2868 CGM.getLangOpts().Optimize, Flags, ArgNo);
2869
2870 // Insert an llvm.dbg.declare into the current block.
2871 llvm::Instruction *Call =
2872 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2873 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002874}
2875
2876void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2877 llvm::Value *Storage,
2878 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002879 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002880 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2881}
2882
Adrian Prantle86fcc42013-03-29 19:20:29 +00002883/// Look up the completed type for a self pointer in the TypeCache and
2884/// create a copy of it with the ObjectPointer and Artificial flags
2885/// set. If the type is not cached, a new one is created. This should
2886/// never happen though, since creating a type for the implicit self
2887/// argument implies that we already parsed the interface definition
2888/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002889llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2890 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002891 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002892 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002893 else DEBUG(llvm::dbgs() << "No cached type for self.");
2894 return DBuilder.createObjectPointerType(Ty);
2895}
2896
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002897void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2898 llvm::Value *Storage,
2899 CGBuilderTy &Builder,
2900 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002901 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002902 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002903
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002904 if (Builder.GetInsertBlock() == 0)
2905 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002906
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002907 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002908
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002909 uint64_t XOffset = 0;
2910 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2911 llvm::DIType Ty;
2912 if (isByRef)
2913 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002914 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002915 Ty = getOrCreateType(VD->getType(), Unit);
2916
2917 // Self is passed along as an implicit non-arg variable in a
2918 // block. Mark it as the object pointer.
2919 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002920 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002921
2922 // Get location information.
2923 unsigned Line = getLineNumber(VD->getLocation());
2924 unsigned Column = getColumnNumber(VD->getLocation());
2925
2926 const llvm::DataLayout &target = CGM.getDataLayout();
2927
2928 CharUnits offset = CharUnits::fromQuantity(
2929 target.getStructLayout(blockInfo.StructureType)
2930 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2931
2932 SmallVector<llvm::Value *, 9> addr;
2933 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002934 if (isa<llvm::AllocaInst>(Storage))
2935 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002936 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2937 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2938 if (isByRef) {
2939 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2940 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2941 // offset of __forwarding field
2942 offset = CGM.getContext()
2943 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2944 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2945 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2946 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2947 // offset of x field
2948 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2949 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2950 }
2951
2952 // Create the descriptor for the variable.
2953 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002954 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002955 llvm::DIDescriptor(LexicalBlockStack.back()),
2956 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002957
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002958 // Insert an llvm.dbg.declare into the current block.
2959 llvm::Instruction *Call =
2960 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2961 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2962 LexicalBlockStack.back()));
2963}
2964
2965/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2966/// variable declaration.
2967void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2968 unsigned ArgNo,
2969 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002970 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002971 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2972}
2973
2974namespace {
2975 struct BlockLayoutChunk {
2976 uint64_t OffsetInBits;
2977 const BlockDecl::Capture *Capture;
2978 };
2979 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2980 return l.OffsetInBits < r.OffsetInBits;
2981 }
2982}
2983
2984void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002985 llvm::Value *Arg,
2986 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002987 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002988 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002989 ASTContext &C = CGM.getContext();
2990 const BlockDecl *blockDecl = block.getBlockDecl();
2991
2992 // Collect some general information about the block's location.
2993 SourceLocation loc = blockDecl->getCaretLocation();
2994 llvm::DIFile tunit = getOrCreateFile(loc);
2995 unsigned line = getLineNumber(loc);
2996 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002997
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002998 // Build the debug-info type for the block literal.
2999 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3000
3001 const llvm::StructLayout *blockLayout =
3002 CGM.getDataLayout().getStructLayout(block.StructureType);
3003
3004 SmallVector<llvm::Value*, 16> fields;
3005 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3006 blockLayout->getElementOffsetInBits(0),
3007 tunit, tunit));
3008 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3009 blockLayout->getElementOffsetInBits(1),
3010 tunit, tunit));
3011 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3012 blockLayout->getElementOffsetInBits(2),
3013 tunit, tunit));
3014 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3015 blockLayout->getElementOffsetInBits(3),
3016 tunit, tunit));
3017 fields.push_back(createFieldType("__descriptor",
3018 C.getPointerType(block.NeedsCopyDispose ?
3019 C.getBlockDescriptorExtendedType() :
3020 C.getBlockDescriptorType()),
3021 0, loc, AS_public,
3022 blockLayout->getElementOffsetInBits(4),
3023 tunit, tunit));
3024
3025 // We want to sort the captures by offset, not because DWARF
3026 // requires this, but because we're paranoid about debuggers.
3027 SmallVector<BlockLayoutChunk, 8> chunks;
3028
3029 // 'this' capture.
3030 if (blockDecl->capturesCXXThis()) {
3031 BlockLayoutChunk chunk;
3032 chunk.OffsetInBits =
3033 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3034 chunk.Capture = 0;
3035 chunks.push_back(chunk);
3036 }
3037
3038 // Variable captures.
3039 for (BlockDecl::capture_const_iterator
3040 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3041 i != e; ++i) {
3042 const BlockDecl::Capture &capture = *i;
3043 const VarDecl *variable = capture.getVariable();
3044 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3045
3046 // Ignore constant captures.
3047 if (captureInfo.isConstant())
3048 continue;
3049
3050 BlockLayoutChunk chunk;
3051 chunk.OffsetInBits =
3052 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3053 chunk.Capture = &capture;
3054 chunks.push_back(chunk);
3055 }
3056
3057 // Sort by offset.
3058 llvm::array_pod_sort(chunks.begin(), chunks.end());
3059
3060 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3061 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3062 uint64_t offsetInBits = i->OffsetInBits;
3063 const BlockDecl::Capture *capture = i->Capture;
3064
3065 // If we have a null capture, this must be the C++ 'this' capture.
3066 if (!capture) {
3067 const CXXMethodDecl *method =
3068 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3069 QualType type = method->getThisType(C);
3070
3071 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3072 offsetInBits, tunit, tunit));
3073 continue;
3074 }
3075
3076 const VarDecl *variable = capture->getVariable();
3077 StringRef name = variable->getName();
3078
3079 llvm::DIType fieldType;
3080 if (capture->isByRef()) {
3081 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3082
3083 // FIXME: this creates a second copy of this type!
3084 uint64_t xoffset;
3085 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3086 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3087 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3088 ptrInfo.first, ptrInfo.second,
3089 offsetInBits, 0, fieldType);
3090 } else {
3091 fieldType = createFieldType(name, variable->getType(), 0,
3092 loc, AS_public, offsetInBits, tunit, tunit);
3093 }
3094 fields.push_back(fieldType);
3095 }
3096
3097 SmallString<36> typeName;
3098 llvm::raw_svector_ostream(typeName)
3099 << "__block_literal_" << CGM.getUniqueBlockCount();
3100
3101 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3102
3103 llvm::DIType type =
3104 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3105 CGM.getContext().toBits(block.BlockSize),
3106 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003107 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003108 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3109
3110 // Get overall information about the block.
3111 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3112 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003113
3114 // Create the descriptor for the parameter.
3115 llvm::DIVariable debugVar =
3116 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003117 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003118 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003119 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003120 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3121
Adrian Prantlbea407c2013-03-14 21:52:59 +00003122 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003123 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003124 llvm::Instruction *DbgVal =
3125 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003126 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003127 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3128 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003129
Adrian Prantlbea407c2013-03-14 21:52:59 +00003130 // Insert an llvm.dbg.declare into the current block.
3131 llvm::Instruction *DbgDecl =
3132 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3133 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003134}
3135
David Blaikie5434fc22013-08-20 01:28:15 +00003136/// If D is an out-of-class definition of a static data member of a class, find
3137/// its corresponding in-class declaration.
3138llvm::DIDerivedType
3139CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3140 if (!D->isStaticDataMember())
3141 return llvm::DIDerivedType();
3142 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3143 StaticDataMemberCache.find(D->getCanonicalDecl());
3144 if (MI != StaticDataMemberCache.end()) {
3145 assert(MI->second && "Static data member declaration should still exist");
3146 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003147 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003148
3149 // If the member wasn't found in the cache, lazily construct and add it to the
3150 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003151 llvm::DICompositeType Ctxt(
3152 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3153 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3154 Ctxt.addMember(T);
3155 return T;
3156}
3157
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003158/// EmitGlobalVariable - Emit information about a global variable.
3159void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3160 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003161 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003162 // Create global variable debug descriptor.
3163 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3164 unsigned LineNo = getLineNumber(D->getLocation());
3165
3166 setLocation(D->getLocation());
3167
3168 QualType T = D->getType();
3169 if (T->isIncompleteArrayType()) {
3170
3171 // CodeGen turns int[] into int[1] so we'll do the same here.
3172 llvm::APInt ConstVal(32, 1);
3173 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3174
3175 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3176 ArrayType::Normal, 0);
3177 }
3178 StringRef DeclName = D->getName();
3179 StringRef LinkageName;
3180 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3181 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3182 LinkageName = Var->getName();
3183 if (LinkageName == DeclName)
3184 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003185 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003186 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003187 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3188 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3189 Var->hasInternalLinkage(), Var,
3190 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003191 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003192}
3193
3194/// EmitGlobalVariable - Emit information about an objective-c interface.
3195void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3196 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003197 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003198 // Create global variable debug descriptor.
3199 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3200 unsigned LineNo = getLineNumber(ID->getLocation());
3201
3202 StringRef Name = ID->getName();
3203
3204 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3205 if (T->isIncompleteArrayType()) {
3206
3207 // CodeGen turns int[] into int[1] so we'll do the same here.
3208 llvm::APInt ConstVal(32, 1);
3209 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3210
3211 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3212 ArrayType::Normal, 0);
3213 }
3214
3215 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3216 getOrCreateType(T, Unit),
3217 Var->hasInternalLinkage(), Var);
3218}
3219
3220/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003221void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003222 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003223 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003224 // Create the descriptor for the variable.
3225 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3226 StringRef Name = VD->getName();
3227 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3228 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3229 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3230 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3231 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3232 }
3233 // Do not use DIGlobalVariable for enums.
3234 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3235 return;
David Blaikie27ab0362013-08-15 21:42:43 +00003236 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3237 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
David Blaikie5434fc22013-08-20 01:28:15 +00003238 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikie9faebd22013-05-20 04:58:53 +00003239 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3240}
3241
3242llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3243 if (!LexicalBlockStack.empty())
3244 return llvm::DIScope(LexicalBlockStack.back());
3245 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003246}
3247
David Blaikie957dac52013-04-22 06:13:21 +00003248void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003249 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3250 return;
David Blaikie957dac52013-04-22 06:13:21 +00003251 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003252 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3253 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003254 getLineNumber(UD.getLocation()));
3255}
3256
David Blaikie9faebd22013-05-20 04:58:53 +00003257void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3258 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3259 return;
3260 assert(UD.shadow_size() &&
3261 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3262 // Emitting one decl is sufficient - debuggers can detect that this is an
3263 // overloaded name & provide lookup for all the overloads.
3264 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003265 if (llvm::DIDescriptor Target =
3266 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003267 DBuilder.createImportedDeclaration(
3268 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3269 getLineNumber(USD.getLocation()));
3270}
3271
David Blaikiefc46ebc2013-05-20 22:50:41 +00003272llvm::DIImportedEntity
3273CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3274 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3275 return llvm::DIImportedEntity(0);
3276 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3277 if (VH)
3278 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3279 llvm::DIImportedEntity R(0);
3280 if (const NamespaceAliasDecl *Underlying =
3281 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3282 // This could cache & dedup here rather than relying on metadata deduping.
3283 R = DBuilder.createImportedModule(
3284 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3285 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3286 NA.getName());
3287 else
3288 R = DBuilder.createImportedModule(
3289 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3290 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3291 getLineNumber(NA.getLocation()), NA.getName());
3292 VH = R;
3293 return R;
3294}
3295
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003296/// getOrCreateNamesSpace - Return namespace descriptor for the given
3297/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003298llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003299CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003300 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003301 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003302 NameSpaceCache.find(NSDecl);
3303 if (I != NameSpaceCache.end())
3304 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003305
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003306 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3307 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003308 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003309 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3310 llvm::DINameSpace NS =
3311 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3312 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3313 return NS;
3314}
3315
3316void CGDebugInfo::finalize() {
3317 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3318 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3319 llvm::DIType Ty, RepTy;
3320 // Verify that the debug info still exists.
3321 if (llvm::Value *V = VI->second)
3322 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003323
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003324 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3325 TypeCache.find(VI->first);
3326 if (it != TypeCache.end()) {
3327 // Verify that the debug info still exists.
3328 if (llvm::Value *V = it->second)
3329 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3330 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003331
Eric Christopherb2d13922013-07-18 00:52:50 +00003332 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003333 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003334 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003335
3336 // We keep our own list of retained types, because we need to look
3337 // up the final type in the type cache.
Manman Renf1acc312013-08-29 18:51:51 +00003338 // Both createForwardDecl and createLimitedType can add the same type to
3339 // RetainedTypes. A set is used to avoid duplication.
3340 llvm::SmallPtrSet<void *, 16> RetainSet;
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003341 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3342 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf1acc312013-08-29 18:51:51 +00003343 if (RetainSet.insert(*RI)) {
3344 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3345 TypeCache.find(*RI);
3346 if (it != TypeCache.end() && it->second)
3347 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(it->second)));
3348 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003349
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003350 DBuilder.finalize();
3351}