blob: 4126e208604ba01ce6d5d61bc800f872e801e4f1 [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 Blaikie2a7002e2013-09-04 02:12:12 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
547 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000548 QualifierCollector Qc;
549 const Type *T = Qc.strip(Ty);
550
551 // Ignore these qualifiers for now.
552 Qc.removeObjCGCAttr();
553 Qc.removeAddressSpace();
554 Qc.removeObjCLifetime();
555
556 // We will create one Derived type for one qualifier and recurse to handle any
557 // additional ones.
558 unsigned Tag;
559 if (Qc.hasConst()) {
560 Tag = llvm::dwarf::DW_TAG_const_type;
561 Qc.removeConst();
562 } else if (Qc.hasVolatile()) {
563 Tag = llvm::dwarf::DW_TAG_volatile_type;
564 Qc.removeVolatile();
565 } else if (Qc.hasRestrict()) {
566 Tag = llvm::dwarf::DW_TAG_restrict_type;
567 Qc.removeRestrict();
568 } else {
569 assert(Qc.empty() && "Unknown type qualifier for debug info");
570 return getOrCreateType(QualType(T, 0), Unit);
571 }
572
David Blaikie2a7002e2013-09-04 02:12:12 +0000573 llvm::DIType FromTy =
574 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000575
576 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
577 // CVR derived types.
578 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000579
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000580 return DbgTy;
581}
582
583llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
584 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000585
586 // The frontend treats 'id' as a typedef to an ObjCObjectType,
587 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
588 // debug info, we want to emit 'id' in both cases.
589 if (Ty->isObjCQualifiedIdType())
590 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
591
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000592 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000593 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000594 Ty->getPointeeType(), Unit);
595 return DbgTy;
596}
597
598llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
599 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000600 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000601 Ty->getPointeeType(), Unit);
602}
603
Manman Ren83369bf2013-08-29 23:19:58 +0000604/// In C++ mode, types have linkage, so we can rely on the ODR and
605/// on their mangled names, if they're external.
606static SmallString<256>
607getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
608 llvm::DICompileUnit TheCU) {
609 SmallString<256> FullName;
610 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
611 // For now, only apply ODR with C++.
612 const TagDecl *TD = Ty->getDecl();
613 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
614 !TD->isExternallyVisible())
615 return FullName;
616 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
617 if (CGM.getTarget().getCXXABI().isMicrosoft())
618 return FullName;
619
620 // TODO: This is using the RTTI name. Is there a better way to get
621 // a unique string for a type?
622 llvm::raw_svector_ostream Out(FullName);
623 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
624 Out.flush();
625 return FullName;
626}
627
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000628// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000629llvm::DICompositeType
Manman Renf3327332013-08-28 21:20:28 +0000630CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikieeaacc882013-08-20 21:03:29 +0000631 llvm::DIDescriptor Ctx) {
Manman Renf3327332013-08-28 21:20:28 +0000632 const RecordDecl *RD = Ty->getDecl();
David Blaikiec5cd1a72013-08-15 20:17:25 +0000633 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000634 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000635 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
636 unsigned Line = getLineNumber(RD->getLocation());
637 StringRef RDName = getClassName(RD);
638
639 unsigned Tag = 0;
640 if (RD->isStruct() || RD->isInterface())
641 Tag = llvm::dwarf::DW_TAG_structure_type;
642 else if (RD->isUnion())
643 Tag = llvm::dwarf::DW_TAG_union_type;
644 else {
645 assert(RD->isClass());
646 Tag = llvm::dwarf::DW_TAG_class_type;
647 }
648
649 // Create the type.
Manman Ren83369bf2013-08-29 23:19:58 +0000650 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
651 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
652 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653}
654
655// Walk up the context chain and create forward decls for record decls,
656// and normal descriptors for namespaces.
657llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
658 if (!Context)
659 return TheCU;
660
661 // See if we already have the parent.
662 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
663 I = RegionMap.find(Context);
664 if (I != RegionMap.end()) {
665 llvm::Value *V = I->second;
666 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
667 }
Eric Christopher6537f082013-05-16 00:45:12 +0000668
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000669 // Check namespace.
670 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
671 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
672
David Blaikieeaacc882013-08-20 21:03:29 +0000673 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context))
674 if (!RD->isDependentType())
675 return getOrCreateLimitedType(
David Blaikie5434fc22013-08-20 01:28:15 +0000676 CGM.getContext().getRecordType(RD)->castAs<RecordType>(),
David Blaikieeaacc882013-08-20 21:03:29 +0000677 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000678 return TheCU;
679}
680
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000681llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000682 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000683 QualType PointeeTy,
684 llvm::DIFile Unit) {
685 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
686 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie2a7002e2013-09-04 02:12:12 +0000687 return DBuilder.createReferenceType(
688 Tag, getOrCreateType(PointeeTy, Unit, true));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000689
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000690 // Bit size, align and offset of the type.
691 // Size is always the size of a pointer. We can't use getTypeSize here
692 // because that does not return the correct value for references.
693 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000694 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000695 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
696
David Blaikie2a7002e2013-09-04 02:12:12 +0000697 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit, true),
698 Size, Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000699}
700
Eric Christopherf0890c42013-05-16 00:52:20 +0000701llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
702 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000703 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000704 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000705 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
706 TheCU, getOrCreateMainFile(), 0);
707 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
708 Cache = DBuilder.createPointerType(Cache, Size);
709 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000710}
711
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000712llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
713 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000714 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000715 return BlockLiteralGeneric;
716
717 SmallVector<llvm::Value *, 8> EltTys;
718 llvm::DIType FieldTy;
719 QualType FType;
720 uint64_t FieldSize, FieldOffset;
721 unsigned FieldAlign;
722 llvm::DIArray Elements;
723 llvm::DIType EltTy, DescTy;
724
725 FieldOffset = 0;
726 FType = CGM.getContext().UnsignedLongTy;
727 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
728 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
729
730 Elements = DBuilder.getOrCreateArray(EltTys);
731 EltTys.clear();
732
733 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
734 unsigned LineNo = getLineNumber(CurLoc);
735
736 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
737 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000738 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000739
740 // Bit size, align and offset of the type.
741 uint64_t Size = CGM.getContext().getTypeSize(Ty);
742
743 DescTy = DBuilder.createPointerType(EltTy, Size);
744
745 FieldOffset = 0;
746 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
747 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
748 FType = CGM.getContext().IntTy;
749 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
750 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
751 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
752 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
753
754 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
755 FieldTy = DescTy;
756 FieldSize = CGM.getContext().getTypeSize(Ty);
757 FieldAlign = CGM.getContext().getTypeAlign(Ty);
758 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
759 LineNo, FieldSize, FieldAlign,
760 FieldOffset, 0, FieldTy);
761 EltTys.push_back(FieldTy);
762
763 FieldOffset += FieldSize;
764 Elements = DBuilder.getOrCreateArray(EltTys);
765
766 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
767 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000768 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000769
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000770 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
771 return BlockLiteralGeneric;
772}
773
David Blaikie2a7002e2013-09-04 02:12:12 +0000774llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
775 bool Declaration) {
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 Blaikie2a7002e2013-09-04 02:12:12 +0000778 llvm::DIType Src =
779 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherb2d13922013-07-18 00:52:50 +0000780 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000781 return llvm::DIType();
782 // We don't set size information, but do specify where the typedef was
783 // declared.
784 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
785 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000786
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000787 llvm::DIDescriptor TypedefContext =
788 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000789
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000790 return
791 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
792}
793
794llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
795 llvm::DIFile Unit) {
796 SmallVector<llvm::Value *, 16> EltTys;
797
798 // Add the result type at least.
David Blaikie2a7002e2013-09-04 02:12:12 +0000799 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit, true));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000800
801 // Set up remainder of arguments if there is a prototype.
802 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
803 if (isa<FunctionNoProtoType>(Ty))
804 EltTys.push_back(DBuilder.createUnspecifiedParameter());
805 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
806 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie2a7002e2013-09-04 02:12:12 +0000807 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit, true));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000808 }
809
810 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
811 return DBuilder.createSubroutineType(Unit, EltTypeArray);
812}
813
814
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000815llvm::DIType CGDebugInfo::createFieldType(StringRef name,
816 QualType type,
817 uint64_t sizeInBitsOverride,
818 SourceLocation loc,
819 AccessSpecifier AS,
820 uint64_t offsetInBits,
821 llvm::DIFile tunit,
822 llvm::DIDescriptor scope) {
823 llvm::DIType debugType = getOrCreateType(type, tunit);
824
825 // Get the location for the field.
826 llvm::DIFile file = getOrCreateFile(loc);
827 unsigned line = getLineNumber(loc);
828
829 uint64_t sizeInBits = 0;
830 unsigned alignInBits = 0;
831 if (!type->isIncompleteArrayType()) {
832 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
833
834 if (sizeInBitsOverride)
835 sizeInBits = sizeInBitsOverride;
836 }
837
838 unsigned flags = 0;
839 if (AS == clang::AS_private)
840 flags |= llvm::DIDescriptor::FlagPrivate;
841 else if (AS == clang::AS_protected)
842 flags |= llvm::DIDescriptor::FlagProtected;
843
844 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
845 alignInBits, offsetInBits, flags, debugType);
846}
847
Eric Christopher0395de32013-01-16 01:22:32 +0000848/// CollectRecordLambdaFields - Helper for CollectRecordFields.
849void CGDebugInfo::
850CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
851 SmallVectorImpl<llvm::Value *> &elements,
852 llvm::DIType RecordTy) {
853 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
854 // has the name and the location of the variable so we should iterate over
855 // both concurrently.
856 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
857 RecordDecl::field_iterator Field = CXXDecl->field_begin();
858 unsigned fieldno = 0;
859 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
860 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
861 const LambdaExpr::Capture C = *I;
862 if (C.capturesVariable()) {
863 VarDecl *V = C.getCapturedVar();
864 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
865 StringRef VName = V->getName();
866 uint64_t SizeInBitsOverride = 0;
867 if (Field->isBitField()) {
868 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
869 assert(SizeInBitsOverride && "found named 0-width bitfield");
870 }
871 llvm::DIType fieldType
872 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
873 C.getLocation(), Field->getAccess(),
874 layout.getFieldOffset(fieldno), VUnit, RecordTy);
875 elements.push_back(fieldType);
876 } else {
877 // TODO: Need to handle 'this' in some way by probably renaming the
878 // this of the lambda class and having a field member of 'this' or
879 // by using AT_object_pointer for the function and having that be
880 // used as 'this' for semantic references.
881 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
882 FieldDecl *f = *Field;
883 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
884 QualType type = f->getType();
885 llvm::DIType fieldType
886 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
887 layout.getFieldOffset(fieldno), VUnit, RecordTy);
888
889 elements.push_back(fieldType);
890 }
891 }
892}
893
David Blaikie5434fc22013-08-20 01:28:15 +0000894/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000895llvm::DIDerivedType
896CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
897 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000898 // Create the descriptor for the static variable, with or without
899 // constant initializers.
900 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
901 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
902
Eric Christopher0395de32013-01-16 01:22:32 +0000903 unsigned LineNumber = getLineNumber(Var->getLocation());
904 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000905 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000906 if (Var->getInit()) {
907 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000908 if (Value) {
909 if (Value->isInt())
910 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
911 if (Value->isFloat())
912 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
913 }
Eric Christopher0395de32013-01-16 01:22:32 +0000914 }
915
916 unsigned Flags = 0;
917 AccessSpecifier Access = Var->getAccess();
918 if (Access == clang::AS_private)
919 Flags |= llvm::DIDescriptor::FlagPrivate;
920 else if (Access == clang::AS_protected)
921 Flags |= llvm::DIDescriptor::FlagProtected;
922
David Blaikiecbcb0302013-08-15 22:50:29 +0000923 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
924 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000925 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000926 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000927}
928
929/// CollectRecordNormalField - Helper for CollectRecordFields.
930void CGDebugInfo::
931CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
932 llvm::DIFile tunit,
933 SmallVectorImpl<llvm::Value *> &elements,
934 llvm::DIType RecordTy) {
935 StringRef name = field->getName();
936 QualType type = field->getType();
937
938 // Ignore unnamed fields unless they're anonymous structs/unions.
939 if (name.empty() && !type->isRecordType())
940 return;
941
942 uint64_t SizeInBitsOverride = 0;
943 if (field->isBitField()) {
944 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
945 assert(SizeInBitsOverride && "found named 0-width bitfield");
946 }
947
948 llvm::DIType fieldType
949 = createFieldType(name, type, SizeInBitsOverride,
950 field->getLocation(), field->getAccess(),
951 OffsetInBits, tunit, RecordTy);
952
953 elements.push_back(fieldType);
954}
955
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000956/// CollectRecordFields - A helper function to collect debug info for
957/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000958void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
959 llvm::DIFile tunit,
960 SmallVectorImpl<llvm::Value *> &elements,
961 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000962 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
963
Eric Christopher0395de32013-01-16 01:22:32 +0000964 if (CXXDecl && CXXDecl->isLambda())
965 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
966 else {
967 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000968
Eric Christopher0395de32013-01-16 01:22:32 +0000969 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000970 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000971
Eric Christopher0395de32013-01-16 01:22:32 +0000972 // Static and non-static members should appear in the same order as
973 // the corresponding declarations in the source program.
974 for (RecordDecl::decl_iterator I = record->decls_begin(),
975 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000976 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
977 // Reuse the existing static member declaration if one exists
978 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
979 StaticDataMemberCache.find(V->getCanonicalDecl());
980 if (MI != StaticDataMemberCache.end()) {
981 assert(MI->second &&
982 "Static data member declaration should still exist");
983 elements.push_back(
984 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
985 } else
986 elements.push_back(CreateRecordStaticField(V, RecordTy));
987 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000988 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
989 tunit, elements, RecordTy);
990
991 // Bump field number for next field.
992 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000993 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000994 }
995}
996
997/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
998/// function type is not updated to include implicit "this" pointer. Use this
999/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +00001000llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001001CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1002 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +00001003 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +00001004 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +00001005 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +00001006 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1007 Func, Unit);
1008}
David Blaikie67f8b5e2013-01-07 22:24:59 +00001009
David Blaikie9a845292013-05-22 23:22:42 +00001010llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +00001011 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001012 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +00001013 llvm::DIArray Args = llvm::DICompositeType(
1014 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001015 assert (Args.getNumElements() && "Invalid number of arguments!");
1016
1017 SmallVector<llvm::Value *, 16> Elts;
1018
1019 // First element is always return type. For 'void' functions it is NULL.
1020 Elts.push_back(Args.getElement(0));
1021
David Blaikie67f8b5e2013-01-07 22:24:59 +00001022 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +00001023 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +00001024 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1025 // Create pointer type directly in this case.
1026 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1027 QualType PointeeTy = ThisPtrTy->getPointeeType();
1028 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001029 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001030 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1031 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001032 llvm::DIType ThisPtrType =
1033 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001034 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1035 // TODO: This and the artificial type below are misleading, the
1036 // types aren't artificial the argument is, but the current
1037 // metadata doesn't represent that.
1038 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1039 Elts.push_back(ThisPtrType);
1040 } else {
1041 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1042 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1043 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1044 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001045 }
1046
1047 // Copy rest of the arguments.
1048 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1049 Elts.push_back(Args.getElement(i));
1050
1051 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1052
1053 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1054}
1055
Eric Christopher6537f082013-05-16 00:45:12 +00001056/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001057/// inside a function.
1058static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1059 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1060 return isFunctionLocalClass(NRD);
1061 if (isa<FunctionDecl>(RD->getDeclContext()))
1062 return true;
1063 return false;
1064}
1065
1066/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1067/// a single member function GlobalDecl.
1068llvm::DISubprogram
1069CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1070 llvm::DIFile Unit,
1071 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001072 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001073 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001074
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001075 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001076 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001077
1078 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1079 // make sense to give a single ctor/dtor a linkage name.
1080 StringRef MethodLinkageName;
1081 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1082 MethodLinkageName = CGM.getMangledName(Method);
1083
1084 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001085 llvm::DIFile MethodDefUnit;
1086 unsigned MethodLine = 0;
1087 if (!Method->isImplicit()) {
1088 MethodDefUnit = getOrCreateFile(Method->getLocation());
1089 MethodLine = getLineNumber(Method->getLocation());
1090 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001091
1092 // Collect virtual method info.
1093 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001094 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001095 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001096
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001097 if (Method->isVirtual()) {
1098 if (Method->isPure())
1099 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1100 else
1101 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001102
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001103 // It doesn't make sense to give a virtual destructor a vtable index,
1104 // since a single destructor has two entries in the vtable.
1105 if (!isa<CXXDestructorDecl>(Method))
1106 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1107 ContainingType = RecordTy;
1108 }
1109
1110 unsigned Flags = 0;
1111 if (Method->isImplicit())
1112 Flags |= llvm::DIDescriptor::FlagArtificial;
1113 AccessSpecifier Access = Method->getAccess();
1114 if (Access == clang::AS_private)
1115 Flags |= llvm::DIDescriptor::FlagPrivate;
1116 else if (Access == clang::AS_protected)
1117 Flags |= llvm::DIDescriptor::FlagProtected;
1118 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1119 if (CXXC->isExplicit())
1120 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001121 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001122 dyn_cast<CXXConversionDecl>(Method)) {
1123 if (CXXC->isExplicit())
1124 Flags |= llvm::DIDescriptor::FlagExplicit;
1125 }
1126 if (Method->hasPrototype())
1127 Flags |= llvm::DIDescriptor::FlagPrototyped;
1128
1129 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1130 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001131 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001132 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001133 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001134 /* isDefinition=*/ false,
1135 Virtuality, VIndex, ContainingType,
1136 Flags, CGM.getLangOpts().Optimize, NULL,
1137 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001138
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001139 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1140
1141 return SP;
1142}
1143
1144/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001145/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001146/// a Record.
1147void CGDebugInfo::
1148CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1149 SmallVectorImpl<llvm::Value *> &EltTys,
1150 llvm::DIType RecordTy) {
1151
1152 // Since we want more than just the individual member decls if we
1153 // have templated functions iterate over every declaration to gather
1154 // the functions.
1155 for(DeclContext::decl_iterator I = RD->decls_begin(),
1156 E = RD->decls_end(); I != E; ++I) {
David Blaikiec5761272013-08-28 17:27:13 +00001157 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001158 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001159 // It may be associated with the declaration of the type & should be
1160 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001161 //
1162 // This situation can arise in the vtable-based debug info reduction where
1163 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001164 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1165 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001166 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001167 // If the member is implicit, lazily create it when we see the
1168 // definition, not before. (an ODR-used implicit default ctor that's
1169 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001170 if (!Method->isImplicit())
1171 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1172 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001173 EltTys.push_back(MI->second);
Eric Christopherac7c25f2013-08-28 23:12:10 +00001174 } else if (const FunctionTemplateDecl *FTD =
1175 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikie11fa7512013-08-28 23:06:52 +00001176 // Add any template specializations that have already been seen. Like
1177 // implicit member functions, these may have been added to a declaration
1178 // in the case of vtable-based debug info reduction.
Eric Christopherac7c25f2013-08-28 23:12:10 +00001179 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1180 SE = FTD->spec_end();
1181 SI != SE; ++SI) {
David Blaikie11fa7512013-08-28 23:06:52 +00001182 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1183 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1184 if (MI != SPCache.end())
1185 EltTys.push_back(MI->second);
1186 }
David Blaikie5434fc22013-08-20 01:28:15 +00001187 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001188 }
Eric Christopher6537f082013-05-16 00:45:12 +00001189}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001190
1191/// CollectCXXFriends - A helper function to collect debug info for
1192/// C++ base classes. This is used while creating debug info entry for
1193/// a Record.
1194void CGDebugInfo::
1195CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1196 SmallVectorImpl<llvm::Value *> &EltTys,
1197 llvm::DIType RecordTy) {
1198 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1199 BE = RD->friend_end(); BI != BE; ++BI) {
1200 if ((*BI)->isUnsupportedFriend())
1201 continue;
1202 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001203 EltTys.push_back(DBuilder.createFriend(
David Blaikie2a7002e2013-09-04 02:12:12 +00001204 RecordTy, getOrCreateType(TInfo->getType(), Unit, true)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001205 }
1206}
1207
1208/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001209/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001210/// a Record.
1211void CGDebugInfo::
1212CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1213 SmallVectorImpl<llvm::Value *> &EltTys,
1214 llvm::DIType RecordTy) {
1215
1216 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1217 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1218 BE = RD->bases_end(); BI != BE; ++BI) {
1219 unsigned BFlags = 0;
1220 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001221
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001222 const CXXRecordDecl *Base =
1223 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001224
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001225 if (BI->isVirtual()) {
1226 // virtual base offset offset is -ve. The code generator emits dwarf
1227 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001228 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001229 0 - CGM.getVTableContext()
1230 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1231 BFlags = llvm::DIDescriptor::FlagVirtual;
1232 } else
1233 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1234 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1235 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001236
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001237 AccessSpecifier Access = BI->getAccessSpecifier();
1238 if (Access == clang::AS_private)
1239 BFlags |= llvm::DIDescriptor::FlagPrivate;
1240 else if (Access == clang::AS_protected)
1241 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001242
1243 llvm::DIType DTy =
1244 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001245 getOrCreateType(BI->getType(), Unit),
1246 BaseOffset, BFlags);
1247 EltTys.push_back(DTy);
1248 }
1249}
1250
1251/// CollectTemplateParams - A helper function to collect template parameters.
1252llvm::DIArray CGDebugInfo::
1253CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001254 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001255 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001256 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001257 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1258 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001259 StringRef Name;
1260 if (TPList)
1261 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001262 switch (TA.getKind()) {
1263 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001264 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1265 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001266 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001267 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001268 } break;
1269 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001270 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1271 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001272 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001273 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001274 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1275 TemplateParams.push_back(TVP);
1276 } break;
1277 case TemplateArgument::Declaration: {
1278 const ValueDecl *D = TA.getAsDecl();
1279 bool InstanceMember = D->isCXXInstanceMember();
1280 QualType T = InstanceMember
1281 ? CGM.getContext().getMemberPointerType(
1282 D->getType(), cast<RecordDecl>(D->getDeclContext())
1283 ->getTypeForDecl())
1284 : CGM.getContext().getPointerType(D->getType());
1285 llvm::DIType TTy = getOrCreateType(T, Unit);
1286 llvm::Value *V = 0;
1287 // Variable pointer template parameters have a value that is the address
1288 // of the variable.
1289 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1290 V = CGM.GetAddrOfGlobalVar(VD);
1291 // Member function pointers have special support for building them, though
1292 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001293 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001294 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1295 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001296 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1297 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001298 // Member data pointers have special handling too to compute the fixed
1299 // offset within the object.
1300 if (isa<FieldDecl>(D)) {
1301 // These five lines (& possibly the above member function pointer
1302 // handling) might be able to be refactored to use similar code in
1303 // CodeGenModule::getMemberPointerConstant
1304 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1305 CharUnits chars =
1306 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1307 V = CGM.getCXXABI().EmitMemberDataPointer(
1308 cast<MemberPointerType>(T.getTypePtr()), chars);
1309 }
1310 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001311 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1312 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001313 TemplateParams.push_back(TVP);
1314 } break;
1315 case TemplateArgument::NullPtr: {
1316 QualType T = TA.getNullPtrType();
1317 llvm::DIType TTy = getOrCreateType(T, Unit);
1318 llvm::Value *V = 0;
1319 // Special case member data pointer null values since they're actually -1
1320 // instead of zero.
1321 if (const MemberPointerType *MPT =
1322 dyn_cast<MemberPointerType>(T.getTypePtr()))
1323 // But treat member function pointers as simple zero integers because
1324 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1325 // CodeGen grows handling for values of non-null member function
1326 // pointers then perhaps we could remove this special case and rely on
1327 // EmitNullMemberPointer for member function pointers.
1328 if (MPT->isMemberDataPointer())
1329 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1330 if (!V)
1331 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1332 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001333 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001334 TemplateParams.push_back(TVP);
1335 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001336 case TemplateArgument::Template: {
1337 llvm::DITemplateValueParameter TVP =
1338 DBuilder.createTemplateTemplateParameter(
1339 TheCU, Name, llvm::DIType(),
1340 TA.getAsTemplate().getAsTemplateDecl()
1341 ->getQualifiedNameAsString());
1342 TemplateParams.push_back(TVP);
1343 } break;
1344 case TemplateArgument::Pack: {
1345 llvm::DITemplateValueParameter TVP =
1346 DBuilder.createTemplateParameterPack(
1347 TheCU, Name, llvm::DIType(),
1348 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1349 TemplateParams.push_back(TVP);
1350 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001351 case TemplateArgument::Expression: {
1352 const Expr *E = TA.getAsExpr();
1353 QualType T = E->getType();
1354 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1355 assert(V && "Expression in template argument isn't constant");
1356 llvm::DIType TTy = getOrCreateType(T, Unit);
1357 llvm::DITemplateValueParameter TVP =
1358 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1359 V->stripPointerCasts());
1360 TemplateParams.push_back(TVP);
1361 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001362 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001363 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001364 case TemplateArgument::Null:
1365 llvm_unreachable(
1366 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001367 }
1368 }
1369 return DBuilder.getOrCreateArray(TemplateParams);
1370}
1371
1372/// CollectFunctionTemplateParams - A helper function to collect debug
1373/// info for function template parameters.
1374llvm::DIArray CGDebugInfo::
1375CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1376 if (FD->getTemplatedKind() ==
1377 FunctionDecl::TK_FunctionTemplateSpecialization) {
1378 const TemplateParameterList *TList =
1379 FD->getTemplateSpecializationInfo()->getTemplate()
1380 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001381 return CollectTemplateParams(
1382 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001383 }
1384 return llvm::DIArray();
1385}
1386
1387/// CollectCXXTemplateParams - A helper function to collect debug info for
1388/// template parameters.
1389llvm::DIArray CGDebugInfo::
1390CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1391 llvm::DIFile Unit) {
1392 llvm::PointerUnion<ClassTemplateDecl *,
1393 ClassTemplatePartialSpecializationDecl *>
1394 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001395
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001396 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1397 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1398 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1399 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001400 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001401}
1402
1403/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1404llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1405 if (VTablePtrType.isValid())
1406 return VTablePtrType;
1407
1408 ASTContext &Context = CGM.getContext();
1409
1410 /* Function type */
1411 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1412 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1413 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1414 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1415 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1416 "__vtbl_ptr_type");
1417 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1418 return VTablePtrType;
1419}
1420
1421/// getVTableName - Get vtable name for the given Class.
1422StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1423 // Construct gdb compatible name name.
1424 std::string Name = "_vptr$" + RD->getNameAsString();
1425
1426 // Copy this name on the side and use its reference.
1427 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1428 memcpy(StrPtr, Name.data(), Name.length());
1429 return StringRef(StrPtr, Name.length());
1430}
1431
1432
1433/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1434/// debug info entry in EltTys vector.
1435void CGDebugInfo::
1436CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1437 SmallVectorImpl<llvm::Value *> &EltTys) {
1438 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1439
1440 // If there is a primary base then it will hold vtable info.
1441 if (RL.getPrimaryBase())
1442 return;
1443
1444 // If this class is not dynamic then there is not any vtable info to collect.
1445 if (!RD->isDynamicClass())
1446 return;
1447
1448 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1449 llvm::DIType VPTR
1450 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001451 0, Size, 0, 0,
1452 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001453 getOrCreateVTablePtrType(Unit));
1454 EltTys.push_back(VPTR);
1455}
1456
Eric Christopher6537f082013-05-16 00:45:12 +00001457/// getOrCreateRecordType - Emit record type's standalone debug info.
1458llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001459 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001460 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001461 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1462 return T;
1463}
1464
1465/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1466/// debug info.
1467llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001468 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001469 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001470 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001471 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001472 return T;
1473}
1474
David Blaikie27804892013-08-15 20:49:17 +00001475void CGDebugInfo::completeType(const RecordDecl *RD) {
1476 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1477 !CGM.getLangOpts().CPlusPlus)
1478 completeRequiredType(RD);
1479}
1480
1481void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001482 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1483 if (CXXDecl->isDynamicClass())
1484 return;
1485
David Blaikie27804892013-08-15 20:49:17 +00001486 QualType Ty = CGM.getContext().getRecordType(RD);
1487 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001488 if (T && T.isForwardDecl())
1489 completeClassData(RD);
1490}
1491
1492void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1493 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001494 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001495 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001496 void* TyPtr = Ty.getAsOpaquePtr();
1497 if (CompletedTypeCache.count(TyPtr))
1498 return;
1499 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1500 assert(!Res.isForwardDecl());
1501 CompletedTypeCache[TyPtr] = Res;
1502 TypeCache[TyPtr] = Res;
1503}
1504
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001505/// CreateType - get structure or union type.
David Blaikie2a7002e2013-09-04 02:12:12 +00001506llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001507 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001508 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2a7002e2013-09-04 02:12:12 +00001509 // Limited debug info should only remove struct definitions that can
1510 // safely be replaced by a forward declaration in the source code.
1511 if ((DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
David Blaikie5434fc22013-08-20 01:28:15 +00001512 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1513 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001514 llvm::DIDescriptor FDContext =
1515 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Manman Renf3327332013-08-28 21:20:28 +00001516 llvm::DIType RetTy = getOrCreateRecordFwdDecl(Ty, FDContext);
David Blaikie5434fc22013-08-20 01:28:15 +00001517 // FIXME: This is conservatively correct. If we return a non-forward decl
1518 // that's not a full definition (such as those created by
1519 // createContextChain) then getOrCreateType will record is as a complete
1520 // type and we'll never record all its members. But this means we're
1521 // emitting full debug info in TUs where GCC successfully emits a partial
1522 // definition of the type.
1523 if (RetTy.isForwardDecl())
1524 return RetTy;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001525 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001526
David Blaikie27804892013-08-15 20:49:17 +00001527 return CreateTypeDefinition(Ty);
1528}
1529
1530llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1531 RecordDecl *RD = Ty->getDecl();
1532
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001533 // Get overall information about the record type for the debug info.
1534 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1535
1536 // Records and classes and unions can all be recursive. To handle them, we
1537 // first generate a debug descriptor for the struct as a forward declaration.
1538 // Then (if it is a definition) we go through and get debug info for all of
1539 // its members. Finally, we create a descriptor for the complete type (which
1540 // may refer to the forward decl if the struct is recursive) and replace all
1541 // uses of the forward declaration with the final definition.
1542
David Blaikie4a077162013-08-12 22:24:20 +00001543 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001544 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001545 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001546
1547 if (FwdDecl.isForwardDecl())
1548 return FwdDecl;
1549
David Blaikie498298d2013-08-18 16:55:33 +00001550 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1551 CollectContainingType(CXXDecl, FwdDecl);
1552
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001553 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001554 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001555 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1556
Adrian Prantl4919de62013-03-06 22:03:30 +00001557 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001558 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1559
1560 // Convert all the elements.
1561 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001562 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001563
1564 // Note: The split of CXXDecl information here is intentional, the
1565 // gdb tests will depend on a certain ordering at printout. The debug
1566 // information offsets are still correct if we merge them all together
1567 // though.
1568 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1569 if (CXXDecl) {
1570 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1571 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1572 }
1573
Eric Christopher0395de32013-01-16 01:22:32 +00001574 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001575 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001576 if (CXXDecl) {
1577 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1578 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001579 }
1580
1581 LexicalBlockStack.pop_back();
1582 RegionMap.erase(Ty->getDecl());
1583
1584 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001585 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001586
Eric Christopherf068c922013-04-02 22:59:11 +00001587 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1588 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001589}
1590
1591/// CreateType - get objective-c object type.
1592llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1593 llvm::DIFile Unit) {
1594 // Ignore protocols.
1595 return getOrCreateType(Ty->getBaseType(), Unit);
1596}
1597
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001598
1599/// \return true if Getter has the default name for the property PD.
1600static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1601 const ObjCMethodDecl *Getter) {
1602 assert(PD);
1603 if (!Getter)
1604 return true;
1605
1606 assert(Getter->getDeclName().isObjCZeroArgSelector());
1607 return PD->getName() ==
1608 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1609}
1610
1611/// \return true if Setter has the default name for the property PD.
1612static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1613 const ObjCMethodDecl *Setter) {
1614 assert(PD);
1615 if (!Setter)
1616 return true;
1617
1618 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001619 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001620 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1621}
1622
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001623/// CreateType - get objective-c interface type.
1624llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1625 llvm::DIFile Unit) {
1626 ObjCInterfaceDecl *ID = Ty->getDecl();
1627 if (!ID)
1628 return llvm::DIType();
1629
1630 // Get overall information about the record type for the debug info.
1631 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1632 unsigned Line = getLineNumber(ID->getLocation());
1633 unsigned RuntimeLang = TheCU.getLanguage();
1634
1635 // If this is just a forward declaration return a special forward-declaration
1636 // debug type since we won't be able to lay out the entire type.
1637 ObjCInterfaceDecl *Def = ID->getDefinition();
1638 if (!Def) {
1639 llvm::DIType FwdDecl =
1640 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001641 ID->getName(), TheCU, DefUnit, Line,
1642 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001643 return FwdDecl;
1644 }
1645
1646 ID = Def;
1647
1648 // Bit size, align and offset of the type.
1649 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1650 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1651
1652 unsigned Flags = 0;
1653 if (ID->getImplementation())
1654 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1655
Eric Christopherf068c922013-04-02 22:59:11 +00001656 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001657 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1658 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001659 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001660
1661 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1662 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001663 QualType QualTy = QualType(Ty, 0);
1664 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001665
Eric Christopherd3003dc2013-07-14 21:00:07 +00001666 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001667 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001668 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1669
1670 // Convert all the elements.
1671 SmallVector<llvm::Value *, 16> EltTys;
1672
1673 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1674 if (SClass) {
1675 llvm::DIType SClassTy =
1676 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1677 if (!SClassTy.isValid())
1678 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001679
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001680 llvm::DIType InhTag =
1681 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1682 EltTys.push_back(InhTag);
1683 }
1684
Eric Christopherd3003dc2013-07-14 21:00:07 +00001685 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001686 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1687 E = ID->prop_end(); I != E; ++I) {
1688 const ObjCPropertyDecl *PD = *I;
1689 SourceLocation Loc = PD->getLocation();
1690 llvm::DIFile PUnit = getOrCreateFile(Loc);
1691 unsigned PLine = getLineNumber(Loc);
1692 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1693 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1694 llvm::MDNode *PropertyNode =
1695 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001696 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001697 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001698 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001699 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001700 getSelectorName(PD->getSetterName()),
1701 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001702 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001703 EltTys.push_back(PropertyNode);
1704 }
1705
1706 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1707 unsigned FieldNo = 0;
1708 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1709 Field = Field->getNextIvar(), ++FieldNo) {
1710 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1711 if (!FieldTy.isValid())
1712 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001713
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 StringRef FieldName = Field->getName();
1715
1716 // Ignore unnamed fields.
1717 if (FieldName.empty())
1718 continue;
1719
1720 // Get the location for the field.
1721 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1722 unsigned FieldLine = getLineNumber(Field->getLocation());
1723 QualType FType = Field->getType();
1724 uint64_t FieldSize = 0;
1725 unsigned FieldAlign = 0;
1726
1727 if (!FType->isIncompleteArrayType()) {
1728
1729 // Bit size, align and offset of the type.
1730 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001731 ? Field->getBitWidthValue(CGM.getContext())
1732 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001733 FieldAlign = CGM.getContext().getTypeAlign(FType);
1734 }
1735
1736 uint64_t FieldOffset;
1737 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1738 // We don't know the runtime offset of an ivar if we're using the
1739 // non-fragile ABI. For bitfields, use the bit offset into the first
1740 // byte of storage of the bitfield. For other fields, use zero.
1741 if (Field->isBitField()) {
1742 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1743 CGM, ID, Field);
1744 FieldOffset %= CGM.getContext().getCharWidth();
1745 } else {
1746 FieldOffset = 0;
1747 }
1748 } else {
1749 FieldOffset = RL.getFieldOffset(FieldNo);
1750 }
1751
1752 unsigned Flags = 0;
1753 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1754 Flags = llvm::DIDescriptor::FlagProtected;
1755 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1756 Flags = llvm::DIDescriptor::FlagPrivate;
1757
1758 llvm::MDNode *PropertyNode = NULL;
1759 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001760 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001761 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1762 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001763 SourceLocation Loc = PD->getLocation();
1764 llvm::DIFile PUnit = getOrCreateFile(Loc);
1765 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001766 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1767 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1768 PropertyNode =
1769 DBuilder.createObjCProperty(PD->getName(),
1770 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001771 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001772 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001773 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001774 getSelectorName(PD->getSetterName()),
1775 PD->getPropertyAttributes(),
1776 getOrCreateType(PD->getType(), PUnit));
1777 }
1778 }
1779 }
1780 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1781 FieldLine, FieldSize, FieldAlign,
1782 FieldOffset, Flags, FieldTy,
1783 PropertyNode);
1784 EltTys.push_back(FieldTy);
1785 }
1786
1787 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001788 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001789
1790 // If the implementation is not yet set, we do not want to mark it
1791 // as complete. An implementation may declare additional
1792 // private ivars that we would miss otherwise.
1793 if (ID->getImplementation() == 0)
1794 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001795
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001796 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001797 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001798}
1799
1800llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1801 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1802 int64_t Count = Ty->getNumElements();
1803 if (Count == 0)
1804 // If number of elements are not known then this is an unbounded array.
1805 // Use Count == -1 to express such arrays.
1806 Count = -1;
1807
1808 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1809 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1810
1811 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1812 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1813
1814 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1815}
1816
1817llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1818 llvm::DIFile Unit) {
1819 uint64_t Size;
1820 uint64_t Align;
1821
1822 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1823 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1824 Size = 0;
1825 Align =
1826 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1827 } else if (Ty->isIncompleteArrayType()) {
1828 Size = 0;
1829 if (Ty->getElementType()->isIncompleteType())
1830 Align = 0;
1831 else
1832 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001833 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 Size = 0;
1835 Align = 0;
1836 } else {
1837 // Size and align of the whole array, not the element type.
1838 Size = CGM.getContext().getTypeSize(Ty);
1839 Align = CGM.getContext().getTypeAlign(Ty);
1840 }
1841
1842 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1843 // interior arrays, do we care? Why aren't nested arrays represented the
1844 // obvious/recursive way?
1845 SmallVector<llvm::Value *, 8> Subscripts;
1846 QualType EltTy(Ty, 0);
1847 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1848 // If the number of elements is known, then count is that number. Otherwise,
1849 // it's -1. This allows us to represent a subrange with an array of 0
1850 // elements, like this:
1851 //
1852 // struct foo {
1853 // int x[0];
1854 // };
1855 int64_t Count = -1; // Count == -1 is an unbounded array.
1856 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1857 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001858
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001859 // FIXME: Verify this is right for VLAs.
1860 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1861 EltTy = Ty->getElementType();
1862 }
1863
1864 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1865
Eric Christopher6537f082013-05-16 00:45:12 +00001866 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001867 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1868 SubscriptArray);
1869 return DbgTy;
1870}
1871
Eric Christopher6537f082013-05-16 00:45:12 +00001872llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001873 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001874 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001875 Ty, Ty->getPointeeType(), Unit);
1876}
1877
Eric Christopher6537f082013-05-16 00:45:12 +00001878llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001879 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001880 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001881 Ty, Ty->getPointeeType(), Unit);
1882}
1883
Eric Christopher6537f082013-05-16 00:45:12 +00001884llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001885 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001886 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1887 if (!Ty->getPointeeType()->isFunctionType())
1888 return DBuilder.createMemberPointerType(
David Blaikie2a7002e2013-09-04 02:12:12 +00001889 getOrCreateType(Ty->getPointeeType(), U, true), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001890 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1891 CGM.getContext().getPointerType(
1892 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1893 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1894 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001895}
1896
Eric Christopher6537f082013-05-16 00:45:12 +00001897llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001898 llvm::DIFile U) {
1899 // Ignore the atomic wrapping
1900 // FIXME: What is the correct representation?
1901 return getOrCreateType(Ty->getValueType(), U);
1902}
1903
1904/// CreateEnumType - get enumeration type.
Manman Ren0a0be742013-08-28 21:46:36 +00001905llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Renf3327332013-08-28 21:20:28 +00001906 const EnumDecl *ED = Ty->getDecl();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001907 uint64_t Size = 0;
1908 uint64_t Align = 0;
1909 if (!ED->getTypeForDecl()->isIncompleteType()) {
1910 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1911 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1912 }
1913
Manman Ren83369bf2013-08-29 23:19:58 +00001914 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1915
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001916 // If this is just a forward declaration, construct an appropriately
1917 // marked node and just return it.
1918 if (!ED->getDefinition()) {
1919 llvm::DIDescriptor EDContext;
1920 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1921 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1922 unsigned Line = getLineNumber(ED->getLocation());
1923 StringRef EDName = ED->getName();
1924 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1925 EDName, EDContext, DefUnit, Line, 0,
Manman Ren83369bf2013-08-29 23:19:58 +00001926 Size, Align, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001927 }
1928
1929 // Create DIEnumerator elements for each enumerator.
1930 SmallVector<llvm::Value *, 16> Enumerators;
1931 ED = ED->getDefinition();
1932 for (EnumDecl::enumerator_iterator
1933 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1934 Enum != EnumEnd; ++Enum) {
1935 Enumerators.push_back(
1936 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001937 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001938 }
1939
1940 // Return a CompositeType for the enum itself.
1941 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1942
1943 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1944 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001945 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001946 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001947 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001948 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001949 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001950 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1951 Size, Align, EltArray,
Manman Ren83369bf2013-08-29 23:19:58 +00001952 ClassTy, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001953 return DbgTy;
1954}
1955
David Blaikie4b12be62013-01-21 04:37:12 +00001956static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1957 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001958 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001959 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001960 QualType LastT = T;
1961 switch (T->getTypeClass()) {
1962 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001963 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001964 case Type::TemplateSpecialization:
1965 T = cast<TemplateSpecializationType>(T)->desugar();
1966 break;
1967 case Type::TypeOfExpr:
1968 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1969 break;
1970 case Type::TypeOf:
1971 T = cast<TypeOfType>(T)->getUnderlyingType();
1972 break;
1973 case Type::Decltype:
1974 T = cast<DecltypeType>(T)->getUnderlyingType();
1975 break;
1976 case Type::UnaryTransform:
1977 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1978 break;
1979 case Type::Attributed:
1980 T = cast<AttributedType>(T)->getEquivalentType();
1981 break;
1982 case Type::Elaborated:
1983 T = cast<ElaboratedType>(T)->getNamedType();
1984 break;
1985 case Type::Paren:
1986 T = cast<ParenType>(T)->getInnerType();
1987 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001988 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001989 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001990 break;
1991 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001992 QualType DT = cast<AutoType>(T)->getDeducedType();
1993 if (DT.isNull())
1994 return T;
1995 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001996 break;
1997 }
Eric Christopher6537f082013-05-16 00:45:12 +00001998
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001999 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00002000 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002001 } while (true);
2002}
2003
Eric Christopherf0890c42013-05-16 00:52:20 +00002004/// getType - Get the type from the cache or return null type if it doesn't
2005/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002006llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2007
2008 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002009 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00002010
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002011 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002012 if (Ty->getTypeClass() == Type::ObjCInterface) {
2013 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2014 if (V)
2015 return llvm::DIType(cast<llvm::MDNode>(V));
2016 else return llvm::DIType();
2017 }
2018
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002019 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2020 TypeCache.find(Ty.getAsOpaquePtr());
2021 if (it != TypeCache.end()) {
2022 // Verify that the debug info still exists.
2023 if (llvm::Value *V = it->second)
2024 return llvm::DIType(cast<llvm::MDNode>(V));
2025 }
2026
2027 return llvm::DIType();
2028}
2029
2030/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2031/// doesn't exist.
2032llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2033
2034 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002035 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002036
2037 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00002038 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002039 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2040 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00002041 if (it != CompletedTypeCache.end())
2042 V = it->second;
2043 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002044 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002045 }
2046
Adrian Prantl4919de62013-03-06 22:03:30 +00002047 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00002048 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002049}
2050
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002051/// getCachedInterfaceTypeOrNull - Get the type from the interface
2052/// cache, unless it needs to regenerated. Otherwise return null.
2053llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2054 // Is there a cached interface that hasn't changed?
2055 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2056 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2057
2058 if (it1 != ObjCInterfaceCache.end())
2059 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2060 if (Checksum(Decl) == it1->second.second)
2061 // Return cached forward declaration.
2062 return it1->second.first;
2063
2064 return 0;
2065}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002066
2067/// getOrCreateType - Get the type from the cache or create a new
2068/// one if necessary.
David Blaikie2a7002e2013-09-04 02:12:12 +00002069llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
2070 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002071 if (Ty.isNull())
2072 return llvm::DIType();
2073
2074 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002075 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002076
David Blaikie2a7002e2013-09-04 02:12:12 +00002077 if (llvm::DIType T = getCompletedTypeOrNull(Ty)) {
2078 // If we're looking for a definition, make sure we have definitions of any
2079 // underlying types.
2080 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
2081 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
2082 if (Ty.hasLocalQualifiers())
2083 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002084 return T;
David Blaikie2a7002e2013-09-04 02:12:12 +00002085 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002086
2087 // Otherwise create the type.
David Blaikie2a7002e2013-09-04 02:12:12 +00002088 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
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 Blaikie2a7002e2013-09-04 02:12:12 +00002157llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2158 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002159 // Handle qualifiers, which recursively handles what they refer to.
2160 if (Ty.hasLocalQualifiers())
David Blaikie2a7002e2013-09-04 02:12:12 +00002161 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002162
2163 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002164
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002165 // Work out details of type.
2166 switch (Ty->getTypeClass()) {
2167#define TYPE(Class, Base)
2168#define ABSTRACT_TYPE(Class, Base)
2169#define NON_CANONICAL_TYPE(Class, Base)
2170#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2171#include "clang/AST/TypeNodes.def"
2172 llvm_unreachable("Dependent types cannot show up in debug information");
2173
2174 case Type::ExtVector:
2175 case Type::Vector:
2176 return CreateType(cast<VectorType>(Ty), Unit);
2177 case Type::ObjCObjectPointer:
2178 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2179 case Type::ObjCObject:
2180 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2181 case Type::ObjCInterface:
2182 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2183 case Type::Builtin:
2184 return CreateType(cast<BuiltinType>(Ty));
2185 case Type::Complex:
2186 return CreateType(cast<ComplexType>(Ty));
2187 case Type::Pointer:
2188 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002189 case Type::Decayed:
2190 // Decayed types are just pointers in LLVM and DWARF.
2191 return CreateType(
2192 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002193 case Type::BlockPointer:
2194 return CreateType(cast<BlockPointerType>(Ty), Unit);
2195 case Type::Typedef:
David Blaikie2a7002e2013-09-04 02:12:12 +00002196 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002197 case Type::Record:
David Blaikie2a7002e2013-09-04 02:12:12 +00002198 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002199 case Type::Enum:
Manman Renf3327332013-08-28 21:20:28 +00002200 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002201 case Type::FunctionProto:
2202 case Type::FunctionNoProto:
2203 return CreateType(cast<FunctionType>(Ty), Unit);
2204 case Type::ConstantArray:
2205 case Type::VariableArray:
2206 case Type::IncompleteArray:
2207 return CreateType(cast<ArrayType>(Ty), Unit);
2208
2209 case Type::LValueReference:
2210 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2211 case Type::RValueReference:
2212 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2213
2214 case Type::MemberPointer:
2215 return CreateType(cast<MemberPointerType>(Ty), Unit);
2216
2217 case Type::Atomic:
2218 return CreateType(cast<AtomicType>(Ty), Unit);
2219
2220 case Type::Attributed:
2221 case Type::TemplateSpecialization:
2222 case Type::Elaborated:
2223 case Type::Paren:
2224 case Type::SubstTemplateTypeParm:
2225 case Type::TypeOfExpr:
2226 case Type::TypeOf:
2227 case Type::Decltype:
2228 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002229 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002230 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002231 case Type::Auto:
2232 Diag = "auto";
2233 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002234 }
Eric Christopher6537f082013-05-16 00:45:12 +00002235
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002236 assert(Diag && "Fall through without a diagnostic?");
2237 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2238 "debug information for %0 is not yet supported");
2239 CGM.getDiags().Report(DiagID)
2240 << Diag;
2241 return llvm::DIType();
2242}
2243
2244/// getOrCreateLimitedType - Get the type from the cache or create a new
2245/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002246llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002247 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002248 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002249
David Blaikieeaacc882013-08-20 21:03:29 +00002250 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002251
2252 // We may have cached a forward decl when we could have created
2253 // a non-forward decl. Go ahead and create a non-forward decl
2254 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002255 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002256
2257 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002258 llvm::DICompositeType Res = CreateLimitedType(Ty);
2259
2260 // Propagate members from the declaration to the definition
2261 // CreateType(const RecordType*) will overwrite this with the members in the
2262 // correct order if the full type is needed.
2263 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002264
Eric Christopherb2d13922013-07-18 00:52:50 +00002265 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002266 ReplaceMap.push_back(
2267 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002268
2269 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002270 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002271 return Res;
2272}
2273
2274// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002275llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002276 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002277
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002278 // Get overall information about the record type for the debug info.
2279 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2280 unsigned Line = getLineNumber(RD->getLocation());
2281 StringRef RDName = getClassName(RD);
2282
2283 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002284 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002285 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2286 else
2287 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2288
David Blaikiec138ff52013-08-18 17:36:19 +00002289 // If we ended up creating the type during the context chain construction,
2290 // just return that.
2291 // FIXME: this could be dealt with better if the type was recorded as
2292 // completed before we started this (see the CompletedTypeCache usage in
2293 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2294 // be pushed to before context creation, but after it was known to be
2295 // destined for completion (might still have an issue if this caller only
2296 // required a declaration but the context construction ended up creating a
2297 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002298 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2299 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002300 return T;
2301
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002302 // If this is just a forward declaration, construct an appropriately
2303 // marked node and just return it.
2304 if (!RD->getDefinition())
Manman Renf3327332013-08-28 21:20:28 +00002305 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002306
2307 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2308 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002309 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002310
Manman Ren83369bf2013-08-29 23:19:58 +00002311 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2312
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002313 if (RD->isUnion())
2314 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Ren83369bf2013-08-29 23:19:58 +00002315 Size, Align, 0, llvm::DIArray(), 0,
2316 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002317 else if (RD->isClass()) {
2318 // FIXME: This could be a struct type giving a default visibility different
2319 // than C++ class type, but needs llvm metadata changes first.
2320 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002321 Size, Align, 0, 0, llvm::DIType(),
2322 llvm::DIArray(), llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002323 llvm::DIArray(), FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002324 } else
2325 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002326 Size, Align, 0, llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002327 llvm::DIArray(), 0, 0, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002328
2329 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002330 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002331
David Blaikie498298d2013-08-18 16:55:33 +00002332 if (const ClassTemplateSpecializationDecl *TSpecial =
2333 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2334 RealDecl.setTypeArray(llvm::DIArray(),
2335 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002336 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002337}
2338
David Blaikie498298d2013-08-18 16:55:33 +00002339void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2340 llvm::DICompositeType RealDecl) {
2341 // A class's primary base or the class itself contains the vtable.
2342 llvm::DICompositeType ContainingType;
2343 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2344 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2345 // Seek non virtual primary base root.
2346 while (1) {
2347 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2348 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2349 if (PBT && !BRL.isPrimaryBaseVirtual())
2350 PBase = PBT;
2351 else
2352 break;
2353 }
2354 ContainingType = llvm::DICompositeType(
2355 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2356 getOrCreateFile(RD->getLocation())));
2357 } else if (RD->isDynamicClass())
2358 ContainingType = RealDecl;
2359
2360 RealDecl.setContainingType(ContainingType);
2361}
2362
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002363/// CreateMemberType - Create new member and increase Offset by FType's size.
2364llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2365 StringRef Name,
2366 uint64_t *Offset) {
2367 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2368 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2369 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2370 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2371 FieldSize, FieldAlign,
2372 *Offset, 0, FieldTy);
2373 *Offset += FieldSize;
2374 return Ty;
2375}
2376
David Blaikie9faebd22013-05-20 04:58:53 +00002377llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2378 // We only need a declaration (not a definition) of the type - so use whatever
2379 // we would otherwise do to get a type for a pointee. (forward declarations in
2380 // limited debug info, full definitions (if the type definition is available)
2381 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002382 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2383 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie2a7002e2013-09-04 02:12:12 +00002384 getOrCreateFile(TD->getLocation()), true);
David Blaikie9faebd22013-05-20 04:58:53 +00002385 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2386 // This doesn't handle providing declarations (for functions or variables) for
2387 // entities without definitions in this TU, nor when the definition proceeds
2388 // the call to this function.
2389 // FIXME: This should be split out into more specific maps with support for
2390 // emitting forward declarations and merging definitions with declarations,
2391 // the same way as we do for types.
2392 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2393 DeclCache.find(D->getCanonicalDecl());
2394 if (I == DeclCache.end())
2395 return llvm::DIDescriptor();
2396 llvm::Value *V = I->second;
2397 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2398}
2399
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002400/// getFunctionDeclaration - Return debug info descriptor to describe method
2401/// declaration for the given method definition.
2402llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002403 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2404 return llvm::DISubprogram();
2405
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002406 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2407 if (!FD) return llvm::DISubprogram();
2408
2409 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002410 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002411
2412 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2413 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002414 if (MI == SPCache.end()) {
Eric Christopherac7c25f2013-08-28 23:12:10 +00002415 if (const CXXMethodDecl *MD =
2416 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002417 llvm::DICompositeType T(S);
Eric Christopherac7c25f2013-08-28 23:12:10 +00002418 llvm::DISubprogram SP =
2419 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikied6d5d692013-08-09 17:20:05 +00002420 T.addMember(SP);
2421 return SP;
2422 }
2423 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002424 if (MI != SPCache.end()) {
2425 llvm::Value *V = MI->second;
2426 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002427 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002428 return SP;
2429 }
2430
2431 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2432 E = FD->redecls_end(); I != E; ++I) {
2433 const FunctionDecl *NextFD = *I;
2434 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2435 MI = SPCache.find(NextFD->getCanonicalDecl());
2436 if (MI != SPCache.end()) {
2437 llvm::Value *V = MI->second;
2438 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002439 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002440 return SP;
2441 }
2442 }
2443 return llvm::DISubprogram();
2444}
2445
2446// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2447// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002448llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2449 QualType FnType,
2450 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002451 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2452 // Create fake but valid subroutine type. Otherwise
2453 // llvm::DISubprogram::Verify() would return false, and
2454 // subprogram DIE will miss DW_AT_decl_file and
2455 // DW_AT_decl_line fields.
2456 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002457
2458 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2459 return getOrCreateMethodType(Method, F);
2460 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2461 // Add "self" and "_cmd"
2462 SmallVector<llvm::Value *, 16> Elts;
2463
2464 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002465 QualType ResultTy = OMethod->getResultType();
2466
2467 // Replace the instancetype keyword with the actual type.
2468 if (ResultTy == CGM.getContext().getObjCInstanceType())
2469 ResultTy = CGM.getContext().getPointerType(
2470 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2471
Adrian Prantl566a9c32013-05-10 21:08:31 +00002472 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002473 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002474 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2475 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2476 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002477 // "_cmd" pointer is always second argument.
2478 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2479 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2480 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002481 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002482 PE = OMethod->param_end(); PI != PE; ++PI)
2483 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2484
2485 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2486 return DBuilder.createSubroutineType(F, EltTypeArray);
2487 }
David Blaikie9a845292013-05-22 23:22:42 +00002488 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002489}
2490
2491/// EmitFunctionStart - Constructs the debug code for entering a function.
2492void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2493 llvm::Function *Fn,
2494 CGBuilderTy &Builder) {
2495
2496 StringRef Name;
2497 StringRef LinkageName;
2498
2499 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2500
2501 const Decl *D = GD.getDecl();
2502 // Function may lack declaration in source code if it is created by Clang
2503 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2504 bool HasDecl = (D != 0);
2505 // Use the location of the declaration.
2506 SourceLocation Loc;
2507 if (HasDecl)
2508 Loc = D->getLocation();
2509
2510 unsigned Flags = 0;
2511 llvm::DIFile Unit = getOrCreateFile(Loc);
2512 llvm::DIDescriptor FDContext(Unit);
2513 llvm::DIArray TParamsArray;
2514 if (!HasDecl) {
2515 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002516 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002517 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2518 // If there is a DISubprogram for this function available then use it.
2519 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2520 FI = SPCache.find(FD->getCanonicalDecl());
2521 if (FI != SPCache.end()) {
2522 llvm::Value *V = FI->second;
2523 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2524 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2525 llvm::MDNode *SPN = SP;
2526 LexicalBlockStack.push_back(SPN);
2527 RegionMap[D] = llvm::WeakVH(SP);
2528 return;
2529 }
2530 }
2531 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002532 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002533 if (FD->hasPrototype()) {
2534 LinkageName = CGM.getMangledName(GD);
2535 Flags |= llvm::DIDescriptor::FlagPrototyped;
2536 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002537 // No need to replicate the linkage name if it isn't different from the
2538 // subprogram name, no need to have it at all unless coverage is enabled or
2539 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002540 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002541 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2542 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002543 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002544 LinkageName = StringRef();
2545
Eric Christopher13c97672013-05-16 00:45:23 +00002546 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002547 if (const NamespaceDecl *NSDecl =
2548 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2549 FDContext = getOrCreateNameSpace(NSDecl);
2550 else if (const RecordDecl *RDecl =
2551 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2552 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2553
2554 // Collect template parameters.
2555 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2556 }
2557 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2558 Name = getObjCMethodName(OMD);
2559 Flags |= llvm::DIDescriptor::FlagPrototyped;
2560 } else {
2561 // Use llvm function name.
2562 Name = Fn->getName();
2563 Flags |= llvm::DIDescriptor::FlagPrototyped;
2564 }
2565 if (!Name.empty() && Name[0] == '\01')
2566 Name = Name.substr(1);
2567
2568 unsigned LineNo = getLineNumber(Loc);
2569 if (!HasDecl || D->isImplicit())
2570 Flags |= llvm::DIDescriptor::FlagArtificial;
2571
David Blaikie23e66db2013-06-22 00:09:36 +00002572 llvm::DISubprogram SP = DBuilder.createFunction(
2573 FDContext, Name, LinkageName, Unit, LineNo,
2574 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2575 true /*definition*/, getLineNumber(CurLoc), Flags,
2576 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002577 if (HasDecl)
2578 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002579
2580 // Push function on region stack.
2581 llvm::MDNode *SPN = SP;
2582 LexicalBlockStack.push_back(SPN);
2583 if (HasDecl)
2584 RegionMap[D] = llvm::WeakVH(SP);
2585}
2586
2587/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002588/// information in the source file. If the location is invalid, the
2589/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002590void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2591 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002592 // Update our current location
2593 setLocation(Loc);
2594
2595 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2596
2597 // Don't bother if things are the same as last time.
2598 SourceManager &SM = CGM.getContext().getSourceManager();
2599 if (CurLoc == PrevLoc ||
2600 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2601 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002602 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2603 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2604 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002605 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002606
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002607 // Update last state.
2608 PrevLoc = CurLoc;
2609
2610 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002611 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2612 (getLineNumber(CurLoc),
2613 getColumnNumber(CurLoc, ForceColumnInfo),
2614 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002615}
2616
2617/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2618/// the stack.
2619void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2620 llvm::DIDescriptor D =
2621 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2622 llvm::DIDescriptor() :
2623 llvm::DIDescriptor(LexicalBlockStack.back()),
2624 getOrCreateFile(CurLoc),
2625 getLineNumber(CurLoc),
2626 getColumnNumber(CurLoc));
2627 llvm::MDNode *DN = D;
2628 LexicalBlockStack.push_back(DN);
2629}
2630
2631/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2632/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002633void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2634 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002635 // Set our current location.
2636 setLocation(Loc);
2637
2638 // Create a new lexical block and push it on the stack.
2639 CreateLexicalBlock(Loc);
2640
2641 // Emit a line table change for the current location inside the new scope.
2642 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2643 getColumnNumber(Loc),
2644 LexicalBlockStack.back()));
2645}
2646
2647/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2648/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002649void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2650 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002651 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2652
2653 // Provide an entry in the line table for the end of the block.
2654 EmitLocation(Builder, Loc);
2655
2656 LexicalBlockStack.pop_back();
2657}
2658
2659/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2660void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2661 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2662 unsigned RCount = FnBeginRegionCount.back();
2663 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2664
2665 // Pop all regions for this function.
2666 while (LexicalBlockStack.size() != RCount)
2667 EmitLexicalBlockEnd(Builder, CurLoc);
2668 FnBeginRegionCount.pop_back();
2669}
2670
Eric Christopher6537f082013-05-16 00:45:12 +00002671// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002672// See BuildByRefType.
2673llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2674 uint64_t *XOffset) {
2675
2676 SmallVector<llvm::Value *, 5> EltTys;
2677 QualType FType;
2678 uint64_t FieldSize, FieldOffset;
2679 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002680
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002681 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002682 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683
2684 FieldOffset = 0;
2685 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2686 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2687 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2688 FType = CGM.getContext().IntTy;
2689 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2690 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2691
2692 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2693 if (HasCopyAndDispose) {
2694 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2695 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2696 &FieldOffset));
2697 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2698 &FieldOffset));
2699 }
2700 bool HasByrefExtendedLayout;
2701 Qualifiers::ObjCLifetime Lifetime;
2702 if (CGM.getContext().getByrefLifetime(Type,
2703 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002704 && HasByrefExtendedLayout) {
2705 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002706 EltTys.push_back(CreateMemberType(Unit, FType,
2707 "__byref_variable_layout",
2708 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002709 }
Eric Christopher6537f082013-05-16 00:45:12 +00002710
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002711 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2712 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002713 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002714 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002715 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2716 CharUnits AlignedOffsetInBytes
2717 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2718 CharUnits NumPaddingBytes
2719 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002720
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002721 if (NumPaddingBytes.isPositive()) {
2722 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2723 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2724 pad, ArrayType::Normal, 0);
2725 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2726 }
2727 }
Eric Christopher6537f082013-05-16 00:45:12 +00002728
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002729 FType = Type;
2730 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2731 FieldSize = CGM.getContext().getTypeSize(FType);
2732 FieldAlign = CGM.getContext().toBits(Align);
2733
Eric Christopher6537f082013-05-16 00:45:12 +00002734 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002735 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2736 0, FieldSize, FieldAlign,
2737 FieldOffset, 0, FieldTy);
2738 EltTys.push_back(FieldTy);
2739 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002740
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002741 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002742
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002743 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002744
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002745 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002746 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002747}
2748
2749/// EmitDeclare - Emit local variable declaration debug info.
2750void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002751 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002752 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002753 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002754 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2755
David Blaikiefc946272013-08-19 03:37:48 +00002756 bool Unwritten =
2757 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2758 cast<Decl>(VD->getDeclContext())->isImplicit());
2759 llvm::DIFile Unit;
2760 if (!Unwritten)
2761 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002762 llvm::DIType Ty;
2763 uint64_t XOffset = 0;
2764 if (VD->hasAttr<BlocksAttr>())
2765 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002766 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002767 Ty = getOrCreateType(VD->getType(), Unit);
2768
2769 // If there is no debug info for this type then do not emit debug info
2770 // for this variable.
2771 if (!Ty)
2772 return;
2773
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002774 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002775 unsigned Line = 0;
2776 unsigned Column = 0;
2777 if (!Unwritten) {
2778 Line = getLineNumber(VD->getLocation());
2779 Column = getColumnNumber(VD->getLocation());
2780 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781 unsigned Flags = 0;
2782 if (VD->isImplicit())
2783 Flags |= llvm::DIDescriptor::FlagArtificial;
2784 // If this is the first argument and it is implicit then
2785 // give it an object pointer flag.
2786 // FIXME: There has to be a better way to do this, but for static
2787 // functions there won't be an implicit param at arg1 and
2788 // otherwise it is 'self' or 'this'.
2789 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2790 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002791 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002792 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2793 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002794 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002795
2796 llvm::MDNode *Scope = LexicalBlockStack.back();
2797
2798 StringRef Name = VD->getName();
2799 if (!Name.empty()) {
2800 if (VD->hasAttr<BlocksAttr>()) {
2801 CharUnits offset = CharUnits::fromQuantity(32);
2802 SmallVector<llvm::Value *, 9> addr;
2803 llvm::Type *Int64Ty = CGM.Int64Ty;
2804 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2805 // offset of __forwarding field
2806 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002807 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002808 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2809 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2810 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2811 // offset of x field
2812 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2813 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2814
2815 // Create the descriptor for the variable.
2816 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002817 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002818 llvm::DIDescriptor(Scope),
2819 VD->getName(), Unit, Line, Ty,
2820 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002821
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002822 // Insert an llvm.dbg.declare into the current block.
2823 llvm::Instruction *Call =
2824 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2825 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2826 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002827 }
David Blaikie436653b2013-01-05 05:58:35 +00002828 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2829 // If VD is an anonymous union then Storage represents value for
2830 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002831 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002832 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002833 for (RecordDecl::field_iterator I = RD->field_begin(),
2834 E = RD->field_end();
2835 I != E; ++I) {
2836 FieldDecl *Field = *I;
2837 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2838 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002839
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002840 // Ignore unnamed fields. Do not ignore unnamed records.
2841 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2842 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002843
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002844 // Use VarDecl's Tag, Scope and Line number.
2845 llvm::DIVariable D =
2846 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002847 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002848 CGM.getLangOpts().Optimize, Flags,
2849 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002850
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002851 // Insert an llvm.dbg.declare into the current block.
2852 llvm::Instruction *Call =
2853 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2854 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2855 }
David Blaikied8180cf2013-01-05 20:03:07 +00002856 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002857 }
2858 }
David Blaikie436653b2013-01-05 05:58:35 +00002859
2860 // Create the descriptor for the variable.
2861 llvm::DIVariable D =
2862 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2863 Name, Unit, Line, Ty,
2864 CGM.getLangOpts().Optimize, Flags, ArgNo);
2865
2866 // Insert an llvm.dbg.declare into the current block.
2867 llvm::Instruction *Call =
2868 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2869 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002870}
2871
2872void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2873 llvm::Value *Storage,
2874 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002875 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002876 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2877}
2878
Adrian Prantle86fcc42013-03-29 19:20:29 +00002879/// Look up the completed type for a self pointer in the TypeCache and
2880/// create a copy of it with the ObjectPointer and Artificial flags
2881/// set. If the type is not cached, a new one is created. This should
2882/// never happen though, since creating a type for the implicit self
2883/// argument implies that we already parsed the interface definition
2884/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002885llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2886 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002887 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002888 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002889 else DEBUG(llvm::dbgs() << "No cached type for self.");
2890 return DBuilder.createObjectPointerType(Ty);
2891}
2892
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002893void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2894 llvm::Value *Storage,
2895 CGBuilderTy &Builder,
2896 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002897 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002898 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002899
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002900 if (Builder.GetInsertBlock() == 0)
2901 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002902
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002903 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002904
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002905 uint64_t XOffset = 0;
2906 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2907 llvm::DIType Ty;
2908 if (isByRef)
2909 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002910 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002911 Ty = getOrCreateType(VD->getType(), Unit);
2912
2913 // Self is passed along as an implicit non-arg variable in a
2914 // block. Mark it as the object pointer.
2915 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002916 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002917
2918 // Get location information.
2919 unsigned Line = getLineNumber(VD->getLocation());
2920 unsigned Column = getColumnNumber(VD->getLocation());
2921
2922 const llvm::DataLayout &target = CGM.getDataLayout();
2923
2924 CharUnits offset = CharUnits::fromQuantity(
2925 target.getStructLayout(blockInfo.StructureType)
2926 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2927
2928 SmallVector<llvm::Value *, 9> addr;
2929 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002930 if (isa<llvm::AllocaInst>(Storage))
2931 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002932 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2933 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2934 if (isByRef) {
2935 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2936 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2937 // offset of __forwarding field
2938 offset = CGM.getContext()
2939 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2940 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2941 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2942 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2943 // offset of x field
2944 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2945 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2946 }
2947
2948 // Create the descriptor for the variable.
2949 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002950 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002951 llvm::DIDescriptor(LexicalBlockStack.back()),
2952 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002953
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002954 // Insert an llvm.dbg.declare into the current block.
2955 llvm::Instruction *Call =
2956 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2957 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2958 LexicalBlockStack.back()));
2959}
2960
2961/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2962/// variable declaration.
2963void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2964 unsigned ArgNo,
2965 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002966 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002967 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2968}
2969
2970namespace {
2971 struct BlockLayoutChunk {
2972 uint64_t OffsetInBits;
2973 const BlockDecl::Capture *Capture;
2974 };
2975 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2976 return l.OffsetInBits < r.OffsetInBits;
2977 }
2978}
2979
2980void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002981 llvm::Value *Arg,
2982 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002983 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002984 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002985 ASTContext &C = CGM.getContext();
2986 const BlockDecl *blockDecl = block.getBlockDecl();
2987
2988 // Collect some general information about the block's location.
2989 SourceLocation loc = blockDecl->getCaretLocation();
2990 llvm::DIFile tunit = getOrCreateFile(loc);
2991 unsigned line = getLineNumber(loc);
2992 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002993
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002994 // Build the debug-info type for the block literal.
2995 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2996
2997 const llvm::StructLayout *blockLayout =
2998 CGM.getDataLayout().getStructLayout(block.StructureType);
2999
3000 SmallVector<llvm::Value*, 16> fields;
3001 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3002 blockLayout->getElementOffsetInBits(0),
3003 tunit, tunit));
3004 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3005 blockLayout->getElementOffsetInBits(1),
3006 tunit, tunit));
3007 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3008 blockLayout->getElementOffsetInBits(2),
3009 tunit, tunit));
3010 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3011 blockLayout->getElementOffsetInBits(3),
3012 tunit, tunit));
3013 fields.push_back(createFieldType("__descriptor",
3014 C.getPointerType(block.NeedsCopyDispose ?
3015 C.getBlockDescriptorExtendedType() :
3016 C.getBlockDescriptorType()),
3017 0, loc, AS_public,
3018 blockLayout->getElementOffsetInBits(4),
3019 tunit, tunit));
3020
3021 // We want to sort the captures by offset, not because DWARF
3022 // requires this, but because we're paranoid about debuggers.
3023 SmallVector<BlockLayoutChunk, 8> chunks;
3024
3025 // 'this' capture.
3026 if (blockDecl->capturesCXXThis()) {
3027 BlockLayoutChunk chunk;
3028 chunk.OffsetInBits =
3029 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3030 chunk.Capture = 0;
3031 chunks.push_back(chunk);
3032 }
3033
3034 // Variable captures.
3035 for (BlockDecl::capture_const_iterator
3036 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3037 i != e; ++i) {
3038 const BlockDecl::Capture &capture = *i;
3039 const VarDecl *variable = capture.getVariable();
3040 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3041
3042 // Ignore constant captures.
3043 if (captureInfo.isConstant())
3044 continue;
3045
3046 BlockLayoutChunk chunk;
3047 chunk.OffsetInBits =
3048 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3049 chunk.Capture = &capture;
3050 chunks.push_back(chunk);
3051 }
3052
3053 // Sort by offset.
3054 llvm::array_pod_sort(chunks.begin(), chunks.end());
3055
3056 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3057 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3058 uint64_t offsetInBits = i->OffsetInBits;
3059 const BlockDecl::Capture *capture = i->Capture;
3060
3061 // If we have a null capture, this must be the C++ 'this' capture.
3062 if (!capture) {
3063 const CXXMethodDecl *method =
3064 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3065 QualType type = method->getThisType(C);
3066
3067 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3068 offsetInBits, tunit, tunit));
3069 continue;
3070 }
3071
3072 const VarDecl *variable = capture->getVariable();
3073 StringRef name = variable->getName();
3074
3075 llvm::DIType fieldType;
3076 if (capture->isByRef()) {
3077 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3078
3079 // FIXME: this creates a second copy of this type!
3080 uint64_t xoffset;
3081 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3082 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3083 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3084 ptrInfo.first, ptrInfo.second,
3085 offsetInBits, 0, fieldType);
3086 } else {
3087 fieldType = createFieldType(name, variable->getType(), 0,
3088 loc, AS_public, offsetInBits, tunit, tunit);
3089 }
3090 fields.push_back(fieldType);
3091 }
3092
3093 SmallString<36> typeName;
3094 llvm::raw_svector_ostream(typeName)
3095 << "__block_literal_" << CGM.getUniqueBlockCount();
3096
3097 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3098
3099 llvm::DIType type =
3100 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3101 CGM.getContext().toBits(block.BlockSize),
3102 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003103 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003104 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3105
3106 // Get overall information about the block.
3107 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3108 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003109
3110 // Create the descriptor for the parameter.
3111 llvm::DIVariable debugVar =
3112 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003113 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003114 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003115 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003116 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3117
Adrian Prantlbea407c2013-03-14 21:52:59 +00003118 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003119 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003120 llvm::Instruction *DbgVal =
3121 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003122 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003123 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3124 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003125
Adrian Prantlbea407c2013-03-14 21:52:59 +00003126 // Insert an llvm.dbg.declare into the current block.
3127 llvm::Instruction *DbgDecl =
3128 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3129 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003130}
3131
David Blaikie5434fc22013-08-20 01:28:15 +00003132/// If D is an out-of-class definition of a static data member of a class, find
3133/// its corresponding in-class declaration.
3134llvm::DIDerivedType
3135CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3136 if (!D->isStaticDataMember())
3137 return llvm::DIDerivedType();
3138 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3139 StaticDataMemberCache.find(D->getCanonicalDecl());
3140 if (MI != StaticDataMemberCache.end()) {
3141 assert(MI->second && "Static data member declaration should still exist");
3142 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003143 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003144
3145 // If the member wasn't found in the cache, lazily construct and add it to the
3146 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003147 llvm::DICompositeType Ctxt(
3148 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3149 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3150 Ctxt.addMember(T);
3151 return T;
3152}
3153
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003154/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003155void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003156 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003157 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003158 // Create global variable debug descriptor.
3159 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3160 unsigned LineNo = getLineNumber(D->getLocation());
3161
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003162 setLocation(D->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003163
3164 QualType T = D->getType();
3165 if (T->isIncompleteArrayType()) {
3166
3167 // CodeGen turns int[] into int[1] so we'll do the same here.
3168 llvm::APInt ConstVal(32, 1);
3169 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3170
3171 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3172 ArrayType::Normal, 0);
3173 }
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003174 StringRef DeclName = D->getName();
3175 StringRef LinkageName;
3176 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3177 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3178 LinkageName = Var->getName();
3179 if (LinkageName == DeclName)
3180 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003181 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003182 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003183 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3184 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003185 Var->hasInternalLinkage(), Var,
David Blaikie5434fc22013-08-20 01:28:15 +00003186 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003187 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003188}
3189
3190/// EmitGlobalVariable - Emit information about an objective-c interface.
3191void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3192 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003193 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003194 // Create global variable debug descriptor.
3195 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3196 unsigned LineNo = getLineNumber(ID->getLocation());
3197
3198 StringRef Name = ID->getName();
3199
3200 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3201 if (T->isIncompleteArrayType()) {
3202
3203 // CodeGen turns int[] into int[1] so we'll do the same here.
3204 llvm::APInt ConstVal(32, 1);
3205 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3206
3207 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3208 ArrayType::Normal, 0);
3209 }
3210
3211 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3212 getOrCreateType(T, Unit),
3213 Var->hasInternalLinkage(), Var);
3214}
3215
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003216/// EmitGlobalVariable - Emit global variable's debug info.
3217void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3218 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003219 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003220 // Create the descriptor for the variable.
3221 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3222 StringRef Name = VD->getName();
3223 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3224 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3225 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3226 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3227 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3228 }
3229 // Do not use DIGlobalVariable for enums.
3230 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3231 return;
3232 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3233 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3234 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3235 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikie9faebd22013-05-20 04:58:53 +00003236}
3237
3238llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3239 if (!LexicalBlockStack.empty())
3240 return llvm::DIScope(LexicalBlockStack.back());
3241 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003242}
3243
David Blaikie957dac52013-04-22 06:13:21 +00003244void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003245 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3246 return;
David Blaikie957dac52013-04-22 06:13:21 +00003247 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003248 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3249 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003250 getLineNumber(UD.getLocation()));
3251}
3252
David Blaikie9faebd22013-05-20 04:58:53 +00003253void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3254 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3255 return;
3256 assert(UD.shadow_size() &&
3257 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3258 // Emitting one decl is sufficient - debuggers can detect that this is an
3259 // overloaded name & provide lookup for all the overloads.
3260 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003261 if (llvm::DIDescriptor Target =
3262 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003263 DBuilder.createImportedDeclaration(
3264 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3265 getLineNumber(USD.getLocation()));
3266}
3267
David Blaikiefc46ebc2013-05-20 22:50:41 +00003268llvm::DIImportedEntity
3269CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3270 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3271 return llvm::DIImportedEntity(0);
3272 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3273 if (VH)
3274 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3275 llvm::DIImportedEntity R(0);
3276 if (const NamespaceAliasDecl *Underlying =
3277 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3278 // This could cache & dedup here rather than relying on metadata deduping.
3279 R = DBuilder.createImportedModule(
3280 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3281 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3282 NA.getName());
3283 else
3284 R = DBuilder.createImportedModule(
3285 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3286 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3287 getLineNumber(NA.getLocation()), NA.getName());
3288 VH = R;
3289 return R;
3290}
3291
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003292/// getOrCreateNamesSpace - Return namespace descriptor for the given
3293/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003294llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003295CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003296 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003297 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003298 NameSpaceCache.find(NSDecl);
3299 if (I != NameSpaceCache.end())
3300 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003301
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003302 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3303 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003304 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003305 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3306 llvm::DINameSpace NS =
3307 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3308 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3309 return NS;
3310}
3311
3312void CGDebugInfo::finalize() {
3313 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3314 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3315 llvm::DIType Ty, RepTy;
3316 // Verify that the debug info still exists.
3317 if (llvm::Value *V = VI->second)
3318 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003319
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003320 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3321 TypeCache.find(VI->first);
3322 if (it != TypeCache.end()) {
3323 // Verify that the debug info still exists.
3324 if (llvm::Value *V = it->second)
3325 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3326 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003327
Eric Christopherb2d13922013-07-18 00:52:50 +00003328 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003329 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003330 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003331
3332 // We keep our own list of retained types, because we need to look
3333 // up the final type in the type cache.
3334 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3335 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Ren18760452013-08-29 20:48:48 +00003336 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003337
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003338 DBuilder.finalize();
3339}