blob: e1a9ae1a9161791eb43908039af2c277284de4e3 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
Adrian Prantled6bbe42013-07-18 00:28:02 +000054
55NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
56 : DI(CGF.getDebugInfo()), Builder(B) {
57 if (DI) {
58 SavedLoc = DI->getLocation();
59 DI->CurLoc = SourceLocation();
60 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
61 }
62}
63
64NoLocation::~NoLocation() {
65 if (DI) {
66 assert(Builder.getCurrentDebugLocation().isUnknown());
67 DI->CurLoc = SavedLoc;
68 }
69}
70
Adrian Prantlb061ce22013-07-18 01:36:04 +000071ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantled6bbe42013-07-18 00:28:02 +000072 : DI(CGF.getDebugInfo()), Builder(B) {
73 if (DI) {
74 SavedLoc = DI->getLocation();
Adrian Prantlb6cdc962013-07-24 20:34:39 +000075 DI->CurLoc = SourceLocation();
76 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
77 }
78}
79
80void ArtificialLocation::Emit() {
81 if (DI) {
Adrian Prantled6bbe42013-07-18 00:28:02 +000082 // Sync the Builder.
83 DI->EmitLocation(Builder, SavedLoc);
84 DI->CurLoc = SourceLocation();
85 // Construct a location that has a valid scope, but no line info.
Adrian Prantlb6cdc962013-07-24 20:34:39 +000086 assert(!DI->LexicalBlockStack.empty());
87 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000088 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
89 }
90}
91
Adrian Prantlb061ce22013-07-18 01:36:04 +000092ArtificialLocation::~ArtificialLocation() {
Adrian Prantled6bbe42013-07-18 00:28:02 +000093 if (DI) {
94 assert(Builder.getCurrentDebugLocation().getLine() == 0);
95 DI->CurLoc = SavedLoc;
96 }
97}
98
Guy Benyei7f92f2d2012-12-18 14:30:41 +000099void CGDebugInfo::setLocation(SourceLocation Loc) {
100 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +0000101 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000102
103 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
104
105 // If we've changed files in the middle of a lexical scope go ahead
106 // and create a new lexical scope with file node if it's different
107 // from the one in the scope.
108 if (LexicalBlockStack.empty()) return;
109
110 SourceManager &SM = CGM.getContext().getSourceManager();
111 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
112 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
113
114 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
115 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
116 return;
117
118 llvm::MDNode *LB = LexicalBlockStack.back();
119 llvm::DIScope Scope = llvm::DIScope(LB);
120 if (Scope.isLexicalBlockFile()) {
121 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
122 llvm::DIDescriptor D
123 = DBuilder.createLexicalBlockFile(LBF.getScope(),
124 getOrCreateFile(CurLoc));
125 llvm::MDNode *N = D;
126 LexicalBlockStack.pop_back();
127 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000128 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000129 llvm::DIDescriptor D
130 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
131 llvm::MDNode *N = D;
132 LexicalBlockStack.pop_back();
133 LexicalBlockStack.push_back(N);
134 }
135}
136
137/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000138llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000139 if (!Context)
140 return TheCU;
141
142 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
143 I = RegionMap.find(Context);
144 if (I != RegionMap.end()) {
145 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000146 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000147 }
148
149 // Check namespace.
150 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000151 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000152
David Blaikiebb000792013-04-19 06:56:38 +0000153 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
154 if (!RDecl->isDependentType())
155 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000156 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000157 return TheCU;
158}
159
160/// getFunctionName - Get function name for the given FunctionDecl. If the
161/// name is constructred on demand (e.g. C++ destructor) then the name
162/// is stored on the side.
163StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
164 assert (FD && "Invalid FunctionDecl!");
165 IdentifierInfo *FII = FD->getIdentifier();
166 FunctionTemplateSpecializationInfo *Info
167 = FD->getTemplateSpecializationInfo();
168 if (!Info && FII)
169 return FII->getName();
170
171 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000172 SmallString<128> NS;
173 llvm::raw_svector_ostream OS(NS);
174 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000175
176 // Add any template specialization args.
177 if (Info) {
178 const TemplateArgumentList *TArgs = Info->TemplateArguments;
179 const TemplateArgument *Args = TArgs->data();
180 unsigned NumArgs = TArgs->size();
181 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000182 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
183 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000184 }
185
186 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000187 OS.flush();
188 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
189 memcpy(StrPtr, NS.data(), NS.size());
190 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000191}
192
193StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
194 SmallString<256> MethodName;
195 llvm::raw_svector_ostream OS(MethodName);
196 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
197 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000198 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCImplementationDecl>(DC)) {
200 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000201 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000202 dyn_cast<const ObjCInterfaceDecl>(DC)) {
203 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000204 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000205 dyn_cast<const ObjCCategoryImplDecl>(DC)){
206 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
207 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000208 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000209 // We can extract the type of the class from the self pointer.
210 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
211 QualType ClassTy =
212 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
213 ClassTy.print(OS, PrintingPolicy(LangOptions()));
214 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000215 }
216 OS << ' ' << OMD->getSelector().getAsString() << ']';
217
218 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
219 memcpy(StrPtr, MethodName.begin(), OS.tell());
220 return StringRef(StrPtr, OS.tell());
221}
222
223/// getSelectorName - Return selector name. This is used for debugging
224/// info.
225StringRef CGDebugInfo::getSelectorName(Selector S) {
226 const std::string &SName = S.getAsString();
227 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
228 memcpy(StrPtr, SName.data(), SName.size());
229 return StringRef(StrPtr, SName.size());
230}
231
232/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000233StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000234CGDebugInfo::getClassName(const RecordDecl *RD) {
235 const ClassTemplateSpecializationDecl *Spec
236 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
237 if (!Spec)
238 return RD->getName();
239
240 const TemplateArgument *Args;
241 unsigned NumArgs;
242 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
243 const TemplateSpecializationType *TST =
244 cast<TemplateSpecializationType>(TAW->getType());
245 Args = TST->getArgs();
246 NumArgs = TST->getNumArgs();
247 } else {
248 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
249 Args = TemplateArgs.data();
250 NumArgs = TemplateArgs.size();
251 }
252 StringRef Name = RD->getIdentifier()->getName();
253 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000254 SmallString<128> TemplateArgList;
255 {
256 llvm::raw_svector_ostream OS(TemplateArgList);
257 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
258 Policy);
259 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000260
261 // Copy this name on the side and use its reference.
262 size_t Length = Name.size() + TemplateArgList.size();
263 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
264 memcpy(StrPtr, Name.data(), Name.size());
265 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
266 return StringRef(StrPtr, Length);
267}
268
269/// getOrCreateFile - Get the file debug info descriptor for the input location.
270llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
271 if (!Loc.isValid())
272 // If Location is not valid then use main input file.
273 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
274
275 SourceManager &SM = CGM.getContext().getSourceManager();
276 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
277
278 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
279 // If the location is not valid then use main input file.
280 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
281
282 // Cache the results.
283 const char *fname = PLoc.getFilename();
284 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
285 DIFileCache.find(fname);
286
287 if (it != DIFileCache.end()) {
288 // Verify that the information still exists.
289 if (llvm::Value *V = it->second)
290 return llvm::DIFile(cast<llvm::MDNode>(V));
291 }
292
293 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
294
295 DIFileCache[fname] = F;
296 return F;
297}
298
299/// getOrCreateMainFile - Get the file info for main compile unit.
300llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
301 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
302}
303
304/// getLineNumber - Get line number for the location. If location is invalid
305/// then use current location.
306unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
307 if (Loc.isInvalid() && CurLoc.isInvalid())
308 return 0;
309 SourceManager &SM = CGM.getContext().getSourceManager();
310 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
311 return PLoc.isValid()? PLoc.getLine() : 0;
312}
313
314/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000315unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000316 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000317 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000318 return 0;
319
320 // If the location is invalid then use the current column.
321 if (Loc.isInvalid() && CurLoc.isInvalid())
322 return 0;
323 SourceManager &SM = CGM.getContext().getSourceManager();
324 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
325 return PLoc.isValid()? PLoc.getColumn() : 0;
326}
327
328StringRef CGDebugInfo::getCurrentDirname() {
329 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
330 return CGM.getCodeGenOpts().DebugCompilationDir;
331
332 if (!CWDName.empty())
333 return CWDName;
334 SmallString<256> CWD;
335 llvm::sys::fs::current_path(CWD);
336 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
337 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
338 return CWDName = StringRef(CompDirnamePtr, CWD.size());
339}
340
341/// CreateCompileUnit - Create new compile unit.
342void CGDebugInfo::CreateCompileUnit() {
343
344 // Get absolute path name.
345 SourceManager &SM = CGM.getContext().getSourceManager();
346 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
347 if (MainFileName.empty())
348 MainFileName = "<unknown>";
349
350 // The main file name provided via the "-main-file-name" option contains just
351 // the file name itself with no path information. This file name may have had
352 // a relative path, so we look into the actual file entry for the main
353 // file to determine the real absolute path for the file.
354 std::string MainFileDir;
355 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
356 MainFileDir = MainFile->getDir()->getName();
357 if (MainFileDir != ".")
358 MainFileName = MainFileDir + "/" + MainFileName;
359 }
360
361 // Save filename string.
362 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
363 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
364 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000365
366 // Save split dwarf file string.
367 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
368 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
369 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
370 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000371
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000372 unsigned LangTag;
373 const LangOptions &LO = CGM.getLangOpts();
374 if (LO.CPlusPlus) {
375 if (LO.ObjC1)
376 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
377 else
378 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
379 } else if (LO.ObjC1) {
380 LangTag = llvm::dwarf::DW_LANG_ObjC;
381 } else if (LO.C99) {
382 LangTag = llvm::dwarf::DW_LANG_C99;
383 } else {
384 LangTag = llvm::dwarf::DW_LANG_C89;
385 }
386
387 std::string Producer = getClangFullVersion();
388
389 // Figure out which version of the ObjC runtime we have.
390 unsigned RuntimeVers = 0;
391 if (LO.ObjC1)
392 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
393
394 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000395 // FIXME - Eliminate TheCU.
Eric Christopher8fed3f42013-07-19 00:51:58 +0000396 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
397 Producer, LO.Optimize,
398 CGM.getCodeGenOpts().DwarfDebugFlags,
399 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000400}
401
402/// CreateType - Get the Basic type from the cache or create a new
403/// one if necessary.
404llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
405 unsigned Encoding = 0;
406 StringRef BTName;
407 switch (BT->getKind()) {
408#define BUILTIN_TYPE(Id, SingletonId)
409#define PLACEHOLDER_TYPE(Id, SingletonId) \
410 case BuiltinType::Id:
411#include "clang/AST/BuiltinTypes.def"
412 case BuiltinType::Dependent:
413 llvm_unreachable("Unexpected builtin type");
414 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000415 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000416 case BuiltinType::Void:
417 return llvm::DIType();
418 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000419 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000420 return ClassTy;
421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
422 "objc_class", TheCU,
423 getOrCreateMainFile(), 0);
424 return ClassTy;
425 case BuiltinType::ObjCId: {
426 // typedef struct objc_class *Class;
427 // typedef struct objc_object {
428 // Class isa;
429 // } *id;
430
Eric Christopherb2d13922013-07-18 00:52:50 +0000431 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000432 return ObjTy;
433
Eric Christopherb2d13922013-07-18 00:52:50 +0000434 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000435 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
436 "objc_class", TheCU,
437 getOrCreateMainFile(), 0);
438
439 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000440
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000441 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
442
Eric Christopherf068c922013-04-02 22:59:11 +0000443 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000444 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
445 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000446
Eric Christopherf068c922013-04-02 22:59:11 +0000447 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
448 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000449 return ObjTy;
450 }
451 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000452 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000453 return SelTy;
454 SelTy =
455 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
456 "objc_selector", TheCU, getOrCreateMainFile(),
457 0);
458 return SelTy;
459 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000460
461 case BuiltinType::OCLImage1d:
462 return getOrCreateStructPtrType("opencl_image1d_t",
463 OCLImage1dDITy);
464 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000465 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000466 OCLImage1dArrayDITy);
467 case BuiltinType::OCLImage1dBuffer:
468 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
469 OCLImage1dBufferDITy);
470 case BuiltinType::OCLImage2d:
471 return getOrCreateStructPtrType("opencl_image2d_t",
472 OCLImage2dDITy);
473 case BuiltinType::OCLImage2dArray:
474 return getOrCreateStructPtrType("opencl_image2d_array_t",
475 OCLImage2dArrayDITy);
476 case BuiltinType::OCLImage3d:
477 return getOrCreateStructPtrType("opencl_image3d_t",
478 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000479 case BuiltinType::OCLSampler:
480 return DBuilder.createBasicType("opencl_sampler_t",
481 CGM.getContext().getTypeSize(BT),
482 CGM.getContext().getTypeAlign(BT),
483 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000484 case BuiltinType::OCLEvent:
485 return getOrCreateStructPtrType("opencl_event_t",
486 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000487
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000488 case BuiltinType::UChar:
489 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
490 case BuiltinType::Char_S:
491 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
492 case BuiltinType::Char16:
493 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
494 case BuiltinType::UShort:
495 case BuiltinType::UInt:
496 case BuiltinType::UInt128:
497 case BuiltinType::ULong:
498 case BuiltinType::WChar_U:
499 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
500 case BuiltinType::Short:
501 case BuiltinType::Int:
502 case BuiltinType::Int128:
503 case BuiltinType::Long:
504 case BuiltinType::WChar_S:
505 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
506 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
507 case BuiltinType::Half:
508 case BuiltinType::Float:
509 case BuiltinType::LongDouble:
510 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
511 }
512
513 switch (BT->getKind()) {
514 case BuiltinType::Long: BTName = "long int"; break;
515 case BuiltinType::LongLong: BTName = "long long int"; break;
516 case BuiltinType::ULong: BTName = "long unsigned int"; break;
517 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
518 default:
519 BTName = BT->getName(CGM.getLangOpts());
520 break;
521 }
522 // Bit size, align and offset of the type.
523 uint64_t Size = CGM.getContext().getTypeSize(BT);
524 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000525 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000526 DBuilder.createBasicType(BTName, Size, Align, Encoding);
527 return DbgTy;
528}
529
530llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
531 // Bit size, align and offset of the type.
532 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
533 if (Ty->isComplexIntegerType())
534 Encoding = llvm::dwarf::DW_ATE_lo_user;
535
536 uint64_t Size = CGM.getContext().getTypeSize(Ty);
537 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000538 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000539 DBuilder.createBasicType("complex", Size, Align, Encoding);
540
541 return DbgTy;
542}
543
544/// CreateCVRType - Get the qualified type from the cache or create
545/// a new one if necessary.
David Blaikie47251962013-08-22 13:36:01 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000547 QualifierCollector Qc;
548 const Type *T = Qc.strip(Ty);
549
550 // Ignore these qualifiers for now.
551 Qc.removeObjCGCAttr();
552 Qc.removeAddressSpace();
553 Qc.removeObjCLifetime();
554
555 // We will create one Derived type for one qualifier and recurse to handle any
556 // additional ones.
557 unsigned Tag;
558 if (Qc.hasConst()) {
559 Tag = llvm::dwarf::DW_TAG_const_type;
560 Qc.removeConst();
561 } else if (Qc.hasVolatile()) {
562 Tag = llvm::dwarf::DW_TAG_volatile_type;
563 Qc.removeVolatile();
564 } else if (Qc.hasRestrict()) {
565 Tag = llvm::dwarf::DW_TAG_restrict_type;
566 Qc.removeRestrict();
567 } else {
568 assert(Qc.empty() && "Unknown type qualifier for debug info");
569 return getOrCreateType(QualType(T, 0), Unit);
570 }
571
David Blaikie47251962013-08-22 13:36:01 +0000572 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000573
574 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
575 // CVR derived types.
576 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000577
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000578 return DbgTy;
579}
580
581llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
582 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000583
584 // The frontend treats 'id' as a typedef to an ObjCObjectType,
585 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
586 // debug info, we want to emit 'id' in both cases.
587 if (Ty->isObjCQualifiedIdType())
588 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
589
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000590 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000591 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000592 Ty->getPointeeType(), Unit);
593 return DbgTy;
594}
595
596llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
597 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000598 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000599 Ty->getPointeeType(), Unit);
600}
601
602// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000603llvm::DICompositeType
604CGDebugInfo::getOrCreateRecordFwdDecl(const RecordDecl *RD,
605 llvm::DIDescriptor Ctx) {
David Blaikiec5cd1a72013-08-15 20:17:25 +0000606 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000607 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000608 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
609 unsigned Line = getLineNumber(RD->getLocation());
610 StringRef RDName = getClassName(RD);
611
612 unsigned Tag = 0;
613 if (RD->isStruct() || RD->isInterface())
614 Tag = llvm::dwarf::DW_TAG_structure_type;
615 else if (RD->isUnion())
616 Tag = llvm::dwarf::DW_TAG_union_type;
617 else {
618 assert(RD->isClass());
619 Tag = llvm::dwarf::DW_TAG_class_type;
620 }
621
622 // Create the type.
623 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
624}
625
626// Walk up the context chain and create forward decls for record decls,
627// and normal descriptors for namespaces.
628llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
629 if (!Context)
630 return TheCU;
631
632 // See if we already have the parent.
633 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
634 I = RegionMap.find(Context);
635 if (I != RegionMap.end()) {
636 llvm::Value *V = I->second;
637 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
638 }
Eric Christopher6537f082013-05-16 00:45:12 +0000639
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000640 // Check namespace.
641 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
642 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
643
David Blaikieeaacc882013-08-20 21:03:29 +0000644 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context))
645 if (!RD->isDependentType())
646 return getOrCreateLimitedType(
David Blaikie5434fc22013-08-20 01:28:15 +0000647 CGM.getContext().getRecordType(RD)->castAs<RecordType>(),
David Blaikieeaacc882013-08-20 21:03:29 +0000648 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000649 return TheCU;
650}
651
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000652llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000653 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000654 QualType PointeeTy,
655 llvm::DIFile Unit) {
656 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
657 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie47251962013-08-22 13:36:01 +0000658 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000659
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000660 // Bit size, align and offset of the type.
661 // Size is always the size of a pointer. We can't use getTypeSize here
662 // because that does not return the correct value for references.
663 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000664 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000665 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
666
David Blaikie47251962013-08-22 13:36:01 +0000667 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
668 Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000669}
670
Eric Christopherf0890c42013-05-16 00:52:20 +0000671llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
672 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000673 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000674 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000675 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
676 TheCU, getOrCreateMainFile(), 0);
677 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
678 Cache = DBuilder.createPointerType(Cache, Size);
679 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000680}
681
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000682llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
683 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000684 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000685 return BlockLiteralGeneric;
686
687 SmallVector<llvm::Value *, 8> EltTys;
688 llvm::DIType FieldTy;
689 QualType FType;
690 uint64_t FieldSize, FieldOffset;
691 unsigned FieldAlign;
692 llvm::DIArray Elements;
693 llvm::DIType EltTy, DescTy;
694
695 FieldOffset = 0;
696 FType = CGM.getContext().UnsignedLongTy;
697 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
698 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
699
700 Elements = DBuilder.getOrCreateArray(EltTys);
701 EltTys.clear();
702
703 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
704 unsigned LineNo = getLineNumber(CurLoc);
705
706 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
707 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000708 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000709
710 // Bit size, align and offset of the type.
711 uint64_t Size = CGM.getContext().getTypeSize(Ty);
712
713 DescTy = DBuilder.createPointerType(EltTy, Size);
714
715 FieldOffset = 0;
716 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
717 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
718 FType = CGM.getContext().IntTy;
719 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
720 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
721 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
722 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
723
724 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
725 FieldTy = DescTy;
726 FieldSize = CGM.getContext().getTypeSize(Ty);
727 FieldAlign = CGM.getContext().getTypeAlign(Ty);
728 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
729 LineNo, FieldSize, FieldAlign,
730 FieldOffset, 0, FieldTy);
731 EltTys.push_back(FieldTy);
732
733 FieldOffset += FieldSize;
734 Elements = DBuilder.getOrCreateArray(EltTys);
735
736 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
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
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000740 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
741 return BlockLiteralGeneric;
742}
743
David Blaikie47251962013-08-22 13:36:01 +0000744llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000745 // Typedefs are derived from some other type. If we have a typedef of a
746 // typedef, make sure to emit the whole chain.
David Blaikie47251962013-08-22 13:36:01 +0000747 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherb2d13922013-07-18 00:52:50 +0000748 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000749 return llvm::DIType();
750 // We don't set size information, but do specify where the typedef was
751 // declared.
752 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
753 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000754
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000755 llvm::DIDescriptor TypedefContext =
756 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000757
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000758 return
759 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
760}
761
762llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
763 llvm::DIFile Unit) {
764 SmallVector<llvm::Value *, 16> EltTys;
765
766 // Add the result type at least.
David Blaikie47251962013-08-22 13:36:01 +0000767 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000768
769 // Set up remainder of arguments if there is a prototype.
770 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
771 if (isa<FunctionNoProtoType>(Ty))
772 EltTys.push_back(DBuilder.createUnspecifiedParameter());
773 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
774 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie47251962013-08-22 13:36:01 +0000775 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000776 }
777
778 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
779 return DBuilder.createSubroutineType(Unit, EltTypeArray);
780}
781
782
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000783llvm::DIType CGDebugInfo::createFieldType(StringRef name,
784 QualType type,
785 uint64_t sizeInBitsOverride,
786 SourceLocation loc,
787 AccessSpecifier AS,
788 uint64_t offsetInBits,
789 llvm::DIFile tunit,
790 llvm::DIDescriptor scope) {
791 llvm::DIType debugType = getOrCreateType(type, tunit);
792
793 // Get the location for the field.
794 llvm::DIFile file = getOrCreateFile(loc);
795 unsigned line = getLineNumber(loc);
796
797 uint64_t sizeInBits = 0;
798 unsigned alignInBits = 0;
799 if (!type->isIncompleteArrayType()) {
800 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
801
802 if (sizeInBitsOverride)
803 sizeInBits = sizeInBitsOverride;
804 }
805
806 unsigned flags = 0;
807 if (AS == clang::AS_private)
808 flags |= llvm::DIDescriptor::FlagPrivate;
809 else if (AS == clang::AS_protected)
810 flags |= llvm::DIDescriptor::FlagProtected;
811
812 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
813 alignInBits, offsetInBits, flags, debugType);
814}
815
Eric Christopher0395de32013-01-16 01:22:32 +0000816/// CollectRecordLambdaFields - Helper for CollectRecordFields.
817void CGDebugInfo::
818CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
819 SmallVectorImpl<llvm::Value *> &elements,
820 llvm::DIType RecordTy) {
821 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
822 // has the name and the location of the variable so we should iterate over
823 // both concurrently.
824 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
825 RecordDecl::field_iterator Field = CXXDecl->field_begin();
826 unsigned fieldno = 0;
827 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
828 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
829 const LambdaExpr::Capture C = *I;
830 if (C.capturesVariable()) {
831 VarDecl *V = C.getCapturedVar();
832 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
833 StringRef VName = V->getName();
834 uint64_t SizeInBitsOverride = 0;
835 if (Field->isBitField()) {
836 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
837 assert(SizeInBitsOverride && "found named 0-width bitfield");
838 }
839 llvm::DIType fieldType
840 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
841 C.getLocation(), Field->getAccess(),
842 layout.getFieldOffset(fieldno), VUnit, RecordTy);
843 elements.push_back(fieldType);
844 } else {
845 // TODO: Need to handle 'this' in some way by probably renaming the
846 // this of the lambda class and having a field member of 'this' or
847 // by using AT_object_pointer for the function and having that be
848 // used as 'this' for semantic references.
849 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
850 FieldDecl *f = *Field;
851 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
852 QualType type = f->getType();
853 llvm::DIType fieldType
854 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
855 layout.getFieldOffset(fieldno), VUnit, RecordTy);
856
857 elements.push_back(fieldType);
858 }
859 }
860}
861
David Blaikie5434fc22013-08-20 01:28:15 +0000862/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000863llvm::DIDerivedType
864CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
865 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000866 // Create the descriptor for the static variable, with or without
867 // constant initializers.
868 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
869 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
870
Eric Christopher0395de32013-01-16 01:22:32 +0000871 unsigned LineNumber = getLineNumber(Var->getLocation());
872 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000873 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000874 if (Var->getInit()) {
875 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000876 if (Value) {
877 if (Value->isInt())
878 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
879 if (Value->isFloat())
880 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
881 }
Eric Christopher0395de32013-01-16 01:22:32 +0000882 }
883
884 unsigned Flags = 0;
885 AccessSpecifier Access = Var->getAccess();
886 if (Access == clang::AS_private)
887 Flags |= llvm::DIDescriptor::FlagPrivate;
888 else if (Access == clang::AS_protected)
889 Flags |= llvm::DIDescriptor::FlagProtected;
890
David Blaikiecbcb0302013-08-15 22:50:29 +0000891 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
892 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000893 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000894 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000895}
896
897/// CollectRecordNormalField - Helper for CollectRecordFields.
898void CGDebugInfo::
899CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
900 llvm::DIFile tunit,
901 SmallVectorImpl<llvm::Value *> &elements,
902 llvm::DIType RecordTy) {
903 StringRef name = field->getName();
904 QualType type = field->getType();
905
906 // Ignore unnamed fields unless they're anonymous structs/unions.
907 if (name.empty() && !type->isRecordType())
908 return;
909
910 uint64_t SizeInBitsOverride = 0;
911 if (field->isBitField()) {
912 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
913 assert(SizeInBitsOverride && "found named 0-width bitfield");
914 }
915
916 llvm::DIType fieldType
917 = createFieldType(name, type, SizeInBitsOverride,
918 field->getLocation(), field->getAccess(),
919 OffsetInBits, tunit, RecordTy);
920
921 elements.push_back(fieldType);
922}
923
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000924/// CollectRecordFields - A helper function to collect debug info for
925/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000926void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
927 llvm::DIFile tunit,
928 SmallVectorImpl<llvm::Value *> &elements,
929 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000930 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
931
Eric Christopher0395de32013-01-16 01:22:32 +0000932 if (CXXDecl && CXXDecl->isLambda())
933 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
934 else {
935 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000936
Eric Christopher0395de32013-01-16 01:22:32 +0000937 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000938 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000939
Eric Christopher0395de32013-01-16 01:22:32 +0000940 // Static and non-static members should appear in the same order as
941 // the corresponding declarations in the source program.
942 for (RecordDecl::decl_iterator I = record->decls_begin(),
943 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000944 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
945 // Reuse the existing static member declaration if one exists
946 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
947 StaticDataMemberCache.find(V->getCanonicalDecl());
948 if (MI != StaticDataMemberCache.end()) {
949 assert(MI->second &&
950 "Static data member declaration should still exist");
951 elements.push_back(
952 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
953 } else
954 elements.push_back(CreateRecordStaticField(V, RecordTy));
955 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000956 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
957 tunit, elements, RecordTy);
958
959 // Bump field number for next field.
960 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000961 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000962 }
963}
964
965/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
966/// function type is not updated to include implicit "this" pointer. Use this
967/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000968llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000969CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
970 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000971 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000972 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000973 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000974 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
975 Func, Unit);
976}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000977
David Blaikie9a845292013-05-22 23:22:42 +0000978llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000980 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000981 llvm::DIArray Args = llvm::DICompositeType(
982 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000983 assert (Args.getNumElements() && "Invalid number of arguments!");
984
985 SmallVector<llvm::Value *, 16> Elts;
986
987 // First element is always return type. For 'void' functions it is NULL.
988 Elts.push_back(Args.getElement(0));
989
David Blaikie67f8b5e2013-01-07 22:24:59 +0000990 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000991 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000992 if (isa<ClassTemplateSpecializationDecl>(RD)) {
993 // Create pointer type directly in this case.
994 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
995 QualType PointeeTy = ThisPtrTy->getPointeeType();
996 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000997 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000998 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
999 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001000 llvm::DIType ThisPtrType =
1001 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001002 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1003 // TODO: This and the artificial type below are misleading, the
1004 // types aren't artificial the argument is, but the current
1005 // metadata doesn't represent that.
1006 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1007 Elts.push_back(ThisPtrType);
1008 } else {
1009 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1010 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1011 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1012 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001013 }
1014
1015 // Copy rest of the arguments.
1016 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1017 Elts.push_back(Args.getElement(i));
1018
1019 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1020
1021 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1022}
1023
Eric Christopher6537f082013-05-16 00:45:12 +00001024/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001025/// inside a function.
1026static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1027 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1028 return isFunctionLocalClass(NRD);
1029 if (isa<FunctionDecl>(RD->getDeclContext()))
1030 return true;
1031 return false;
1032}
1033
1034/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1035/// a single member function GlobalDecl.
1036llvm::DISubprogram
1037CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1038 llvm::DIFile Unit,
1039 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001040 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001042
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001043 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001044 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001045
1046 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1047 // make sense to give a single ctor/dtor a linkage name.
1048 StringRef MethodLinkageName;
1049 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1050 MethodLinkageName = CGM.getMangledName(Method);
1051
1052 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001053 llvm::DIFile MethodDefUnit;
1054 unsigned MethodLine = 0;
1055 if (!Method->isImplicit()) {
1056 MethodDefUnit = getOrCreateFile(Method->getLocation());
1057 MethodLine = getLineNumber(Method->getLocation());
1058 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001059
1060 // Collect virtual method info.
1061 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001062 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001063 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001065 if (Method->isVirtual()) {
1066 if (Method->isPure())
1067 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1068 else
1069 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001070
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001071 // It doesn't make sense to give a virtual destructor a vtable index,
1072 // since a single destructor has two entries in the vtable.
1073 if (!isa<CXXDestructorDecl>(Method))
1074 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1075 ContainingType = RecordTy;
1076 }
1077
1078 unsigned Flags = 0;
1079 if (Method->isImplicit())
1080 Flags |= llvm::DIDescriptor::FlagArtificial;
1081 AccessSpecifier Access = Method->getAccess();
1082 if (Access == clang::AS_private)
1083 Flags |= llvm::DIDescriptor::FlagPrivate;
1084 else if (Access == clang::AS_protected)
1085 Flags |= llvm::DIDescriptor::FlagProtected;
1086 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1087 if (CXXC->isExplicit())
1088 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001089 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001090 dyn_cast<CXXConversionDecl>(Method)) {
1091 if (CXXC->isExplicit())
1092 Flags |= llvm::DIDescriptor::FlagExplicit;
1093 }
1094 if (Method->hasPrototype())
1095 Flags |= llvm::DIDescriptor::FlagPrototyped;
1096
1097 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1098 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001099 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001100 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001101 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001102 /* isDefinition=*/ false,
1103 Virtuality, VIndex, ContainingType,
1104 Flags, CGM.getLangOpts().Optimize, NULL,
1105 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001106
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001107 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1108
1109 return SP;
1110}
1111
1112/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001113/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001114/// a Record.
1115void CGDebugInfo::
1116CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1117 SmallVectorImpl<llvm::Value *> &EltTys,
1118 llvm::DIType RecordTy) {
1119
1120 // Since we want more than just the individual member decls if we
1121 // have templated functions iterate over every declaration to gather
1122 // the functions.
1123 for(DeclContext::decl_iterator I = RD->decls_begin(),
1124 E = RD->decls_end(); I != E; ++I) {
David Blaikiec5761272013-08-28 17:27:13 +00001125 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001126 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001127 // It may be associated with the declaration of the type & should be
1128 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001129 //
1130 // This situation can arise in the vtable-based debug info reduction where
1131 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001132 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1133 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001134 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001135 // If the member is implicit, lazily create it when we see the
1136 // definition, not before. (an ODR-used implicit default ctor that's
1137 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001138 if (!Method->isImplicit())
1139 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1140 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001141 EltTys.push_back(MI->second);
1142 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001143 }
Eric Christopher6537f082013-05-16 00:45:12 +00001144}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145
1146/// CollectCXXFriends - A helper function to collect debug info for
1147/// C++ base classes. This is used while creating debug info entry for
1148/// a Record.
1149void CGDebugInfo::
1150CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1151 SmallVectorImpl<llvm::Value *> &EltTys,
1152 llvm::DIType RecordTy) {
1153 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1154 BE = RD->friend_end(); BI != BE; ++BI) {
1155 if ((*BI)->isUnsupportedFriend())
1156 continue;
1157 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001158 EltTys.push_back(DBuilder.createFriend(
David Blaikie47251962013-08-22 13:36:01 +00001159 RecordTy, getOrCreateType(TInfo->getType(), Unit)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001160 }
1161}
1162
1163/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001164/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001165/// a Record.
1166void CGDebugInfo::
1167CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1168 SmallVectorImpl<llvm::Value *> &EltTys,
1169 llvm::DIType RecordTy) {
1170
1171 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1172 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1173 BE = RD->bases_end(); BI != BE; ++BI) {
1174 unsigned BFlags = 0;
1175 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001176
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001177 const CXXRecordDecl *Base =
1178 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001179
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 if (BI->isVirtual()) {
1181 // virtual base offset offset is -ve. The code generator emits dwarf
1182 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001183 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001184 0 - CGM.getVTableContext()
1185 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1186 BFlags = llvm::DIDescriptor::FlagVirtual;
1187 } else
1188 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1189 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1190 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001191
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001192 AccessSpecifier Access = BI->getAccessSpecifier();
1193 if (Access == clang::AS_private)
1194 BFlags |= llvm::DIDescriptor::FlagPrivate;
1195 else if (Access == clang::AS_protected)
1196 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001197
1198 llvm::DIType DTy =
1199 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001200 getOrCreateType(BI->getType(), Unit),
1201 BaseOffset, BFlags);
1202 EltTys.push_back(DTy);
1203 }
1204}
1205
1206/// CollectTemplateParams - A helper function to collect template parameters.
1207llvm::DIArray CGDebugInfo::
1208CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001209 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001210 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001211 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001212 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1213 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001214 StringRef Name;
1215 if (TPList)
1216 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001217 switch (TA.getKind()) {
1218 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001219 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1220 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001221 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001222 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001223 } break;
1224 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001225 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1226 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001227 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001228 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001229 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1230 TemplateParams.push_back(TVP);
1231 } break;
1232 case TemplateArgument::Declaration: {
1233 const ValueDecl *D = TA.getAsDecl();
1234 bool InstanceMember = D->isCXXInstanceMember();
1235 QualType T = InstanceMember
1236 ? CGM.getContext().getMemberPointerType(
1237 D->getType(), cast<RecordDecl>(D->getDeclContext())
1238 ->getTypeForDecl())
1239 : CGM.getContext().getPointerType(D->getType());
1240 llvm::DIType TTy = getOrCreateType(T, Unit);
1241 llvm::Value *V = 0;
1242 // Variable pointer template parameters have a value that is the address
1243 // of the variable.
1244 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1245 V = CGM.GetAddrOfGlobalVar(VD);
1246 // Member function pointers have special support for building them, though
1247 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001248 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001249 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1250 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001251 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1252 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001253 // Member data pointers have special handling too to compute the fixed
1254 // offset within the object.
1255 if (isa<FieldDecl>(D)) {
1256 // These five lines (& possibly the above member function pointer
1257 // handling) might be able to be refactored to use similar code in
1258 // CodeGenModule::getMemberPointerConstant
1259 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1260 CharUnits chars =
1261 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1262 V = CGM.getCXXABI().EmitMemberDataPointer(
1263 cast<MemberPointerType>(T.getTypePtr()), chars);
1264 }
1265 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001266 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1267 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001268 TemplateParams.push_back(TVP);
1269 } break;
1270 case TemplateArgument::NullPtr: {
1271 QualType T = TA.getNullPtrType();
1272 llvm::DIType TTy = getOrCreateType(T, Unit);
1273 llvm::Value *V = 0;
1274 // Special case member data pointer null values since they're actually -1
1275 // instead of zero.
1276 if (const MemberPointerType *MPT =
1277 dyn_cast<MemberPointerType>(T.getTypePtr()))
1278 // But treat member function pointers as simple zero integers because
1279 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1280 // CodeGen grows handling for values of non-null member function
1281 // pointers then perhaps we could remove this special case and rely on
1282 // EmitNullMemberPointer for member function pointers.
1283 if (MPT->isMemberDataPointer())
1284 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1285 if (!V)
1286 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1287 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001288 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001289 TemplateParams.push_back(TVP);
1290 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001291 case TemplateArgument::Template: {
1292 llvm::DITemplateValueParameter TVP =
1293 DBuilder.createTemplateTemplateParameter(
1294 TheCU, Name, llvm::DIType(),
1295 TA.getAsTemplate().getAsTemplateDecl()
1296 ->getQualifiedNameAsString());
1297 TemplateParams.push_back(TVP);
1298 } break;
1299 case TemplateArgument::Pack: {
1300 llvm::DITemplateValueParameter TVP =
1301 DBuilder.createTemplateParameterPack(
1302 TheCU, Name, llvm::DIType(),
1303 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1304 TemplateParams.push_back(TVP);
1305 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001306 case TemplateArgument::Expression: {
1307 const Expr *E = TA.getAsExpr();
1308 QualType T = E->getType();
1309 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1310 assert(V && "Expression in template argument isn't constant");
1311 llvm::DIType TTy = getOrCreateType(T, Unit);
1312 llvm::DITemplateValueParameter TVP =
1313 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1314 V->stripPointerCasts());
1315 TemplateParams.push_back(TVP);
1316 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001317 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001318 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001319 case TemplateArgument::Null:
1320 llvm_unreachable(
1321 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001322 }
1323 }
1324 return DBuilder.getOrCreateArray(TemplateParams);
1325}
1326
1327/// CollectFunctionTemplateParams - A helper function to collect debug
1328/// info for function template parameters.
1329llvm::DIArray CGDebugInfo::
1330CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1331 if (FD->getTemplatedKind() ==
1332 FunctionDecl::TK_FunctionTemplateSpecialization) {
1333 const TemplateParameterList *TList =
1334 FD->getTemplateSpecializationInfo()->getTemplate()
1335 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001336 return CollectTemplateParams(
1337 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001338 }
1339 return llvm::DIArray();
1340}
1341
1342/// CollectCXXTemplateParams - A helper function to collect debug info for
1343/// template parameters.
1344llvm::DIArray CGDebugInfo::
1345CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1346 llvm::DIFile Unit) {
1347 llvm::PointerUnion<ClassTemplateDecl *,
1348 ClassTemplatePartialSpecializationDecl *>
1349 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001350
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001351 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1352 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1353 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1354 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001355 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001356}
1357
1358/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1359llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1360 if (VTablePtrType.isValid())
1361 return VTablePtrType;
1362
1363 ASTContext &Context = CGM.getContext();
1364
1365 /* Function type */
1366 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1367 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1368 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1369 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1370 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1371 "__vtbl_ptr_type");
1372 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1373 return VTablePtrType;
1374}
1375
1376/// getVTableName - Get vtable name for the given Class.
1377StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1378 // Construct gdb compatible name name.
1379 std::string Name = "_vptr$" + RD->getNameAsString();
1380
1381 // Copy this name on the side and use its reference.
1382 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1383 memcpy(StrPtr, Name.data(), Name.length());
1384 return StringRef(StrPtr, Name.length());
1385}
1386
1387
1388/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1389/// debug info entry in EltTys vector.
1390void CGDebugInfo::
1391CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1392 SmallVectorImpl<llvm::Value *> &EltTys) {
1393 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1394
1395 // If there is a primary base then it will hold vtable info.
1396 if (RL.getPrimaryBase())
1397 return;
1398
1399 // If this class is not dynamic then there is not any vtable info to collect.
1400 if (!RD->isDynamicClass())
1401 return;
1402
1403 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1404 llvm::DIType VPTR
1405 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001406 0, Size, 0, 0,
1407 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001408 getOrCreateVTablePtrType(Unit));
1409 EltTys.push_back(VPTR);
1410}
1411
Eric Christopher6537f082013-05-16 00:45:12 +00001412/// getOrCreateRecordType - Emit record type's standalone debug info.
1413llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001414 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001415 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1417 return T;
1418}
1419
1420/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1421/// debug info.
1422llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001423 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001424 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001425 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001426 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001427 return T;
1428}
1429
David Blaikie27804892013-08-15 20:49:17 +00001430void CGDebugInfo::completeType(const RecordDecl *RD) {
1431 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1432 !CGM.getLangOpts().CPlusPlus)
1433 completeRequiredType(RD);
1434}
1435
1436void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001437 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1438 if (CXXDecl->isDynamicClass())
1439 return;
1440
David Blaikie27804892013-08-15 20:49:17 +00001441 QualType Ty = CGM.getContext().getRecordType(RD);
1442 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001443 if (T && T.isForwardDecl())
1444 completeClassData(RD);
1445}
1446
1447void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1448 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001449 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001450 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001451 void* TyPtr = Ty.getAsOpaquePtr();
1452 if (CompletedTypeCache.count(TyPtr))
1453 return;
1454 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1455 assert(!Res.isForwardDecl());
1456 CompletedTypeCache[TyPtr] = Res;
1457 TypeCache[TyPtr] = Res;
1458}
1459
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001460/// CreateType - get structure or union type.
David Blaikie47251962013-08-22 13:36:01 +00001461llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001462 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001463 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie47251962013-08-22 13:36:01 +00001464 // Always emit declarations for types that aren't required to be complete when
1465 // in limit-debug-info mode. If the type is later found to be required to be
1466 // complete this declaration will be upgraded to a definition by
1467 // `completeRequiredType`.
1468 // If the type is dynamic, only emit the definition in TUs that require class
1469 // data. This is handled by `completeClassData`.
1470 if ((DebugKind <= CodeGenOptions::LimitedDebugInfo &&
David Blaikie5434fc22013-08-20 01:28:15 +00001471 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1472 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001473 llvm::DIDescriptor FDContext =
1474 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie951094b2013-08-15 18:59:40 +00001475 llvm::DIType RetTy = getOrCreateRecordFwdDecl(RD, FDContext);
David Blaikie5434fc22013-08-20 01:28:15 +00001476 // FIXME: This is conservatively correct. If we return a non-forward decl
1477 // that's not a full definition (such as those created by
1478 // createContextChain) then getOrCreateType will record is as a complete
1479 // type and we'll never record all its members. But this means we're
1480 // emitting full debug info in TUs where GCC successfully emits a partial
1481 // definition of the type.
1482 if (RetTy.isForwardDecl())
1483 return RetTy;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001484 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001485
David Blaikie27804892013-08-15 20:49:17 +00001486 return CreateTypeDefinition(Ty);
1487}
1488
1489llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1490 RecordDecl *RD = Ty->getDecl();
1491
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001492 // Get overall information about the record type for the debug info.
1493 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1494
1495 // Records and classes and unions can all be recursive. To handle them, we
1496 // first generate a debug descriptor for the struct as a forward declaration.
1497 // Then (if it is a definition) we go through and get debug info for all of
1498 // its members. Finally, we create a descriptor for the complete type (which
1499 // may refer to the forward decl if the struct is recursive) and replace all
1500 // uses of the forward declaration with the final definition.
1501
David Blaikie4a077162013-08-12 22:24:20 +00001502 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001503 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001504 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001505
1506 if (FwdDecl.isForwardDecl())
1507 return FwdDecl;
1508
David Blaikie498298d2013-08-18 16:55:33 +00001509 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1510 CollectContainingType(CXXDecl, FwdDecl);
1511
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001512 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001513 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001514 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1515
Adrian Prantl4919de62013-03-06 22:03:30 +00001516 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001517 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1518
1519 // Convert all the elements.
1520 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001521 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001522
1523 // Note: The split of CXXDecl information here is intentional, the
1524 // gdb tests will depend on a certain ordering at printout. The debug
1525 // information offsets are still correct if we merge them all together
1526 // though.
1527 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1528 if (CXXDecl) {
1529 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1530 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1531 }
1532
Eric Christopher0395de32013-01-16 01:22:32 +00001533 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001534 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001535 if (CXXDecl) {
1536 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1537 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001538 }
1539
1540 LexicalBlockStack.pop_back();
1541 RegionMap.erase(Ty->getDecl());
1542
1543 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001544 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001545
Eric Christopherf068c922013-04-02 22:59:11 +00001546 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1547 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001548}
1549
1550/// CreateType - get objective-c object type.
1551llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1552 llvm::DIFile Unit) {
1553 // Ignore protocols.
1554 return getOrCreateType(Ty->getBaseType(), Unit);
1555}
1556
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001557
1558/// \return true if Getter has the default name for the property PD.
1559static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1560 const ObjCMethodDecl *Getter) {
1561 assert(PD);
1562 if (!Getter)
1563 return true;
1564
1565 assert(Getter->getDeclName().isObjCZeroArgSelector());
1566 return PD->getName() ==
1567 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1568}
1569
1570/// \return true if Setter has the default name for the property PD.
1571static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1572 const ObjCMethodDecl *Setter) {
1573 assert(PD);
1574 if (!Setter)
1575 return true;
1576
1577 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001578 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001579 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1580}
1581
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001582/// CreateType - get objective-c interface type.
1583llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1584 llvm::DIFile Unit) {
1585 ObjCInterfaceDecl *ID = Ty->getDecl();
1586 if (!ID)
1587 return llvm::DIType();
1588
1589 // Get overall information about the record type for the debug info.
1590 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1591 unsigned Line = getLineNumber(ID->getLocation());
1592 unsigned RuntimeLang = TheCU.getLanguage();
1593
1594 // If this is just a forward declaration return a special forward-declaration
1595 // debug type since we won't be able to lay out the entire type.
1596 ObjCInterfaceDecl *Def = ID->getDefinition();
1597 if (!Def) {
1598 llvm::DIType FwdDecl =
1599 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001600 ID->getName(), TheCU, DefUnit, Line,
1601 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001602 return FwdDecl;
1603 }
1604
1605 ID = Def;
1606
1607 // Bit size, align and offset of the type.
1608 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1609 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1610
1611 unsigned Flags = 0;
1612 if (ID->getImplementation())
1613 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1614
Eric Christopherf068c922013-04-02 22:59:11 +00001615 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001616 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1617 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001618 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001619
1620 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1621 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001622 QualType QualTy = QualType(Ty, 0);
1623 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001624
Eric Christopherd3003dc2013-07-14 21:00:07 +00001625 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001626 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001627 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1628
1629 // Convert all the elements.
1630 SmallVector<llvm::Value *, 16> EltTys;
1631
1632 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1633 if (SClass) {
1634 llvm::DIType SClassTy =
1635 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1636 if (!SClassTy.isValid())
1637 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001638
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639 llvm::DIType InhTag =
1640 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1641 EltTys.push_back(InhTag);
1642 }
1643
Eric Christopherd3003dc2013-07-14 21:00:07 +00001644 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001645 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1646 E = ID->prop_end(); I != E; ++I) {
1647 const ObjCPropertyDecl *PD = *I;
1648 SourceLocation Loc = PD->getLocation();
1649 llvm::DIFile PUnit = getOrCreateFile(Loc);
1650 unsigned PLine = getLineNumber(Loc);
1651 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1652 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1653 llvm::MDNode *PropertyNode =
1654 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001655 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001656 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001657 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001658 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001659 getSelectorName(PD->getSetterName()),
1660 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001661 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001662 EltTys.push_back(PropertyNode);
1663 }
1664
1665 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1666 unsigned FieldNo = 0;
1667 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1668 Field = Field->getNextIvar(), ++FieldNo) {
1669 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1670 if (!FieldTy.isValid())
1671 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001672
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001673 StringRef FieldName = Field->getName();
1674
1675 // Ignore unnamed fields.
1676 if (FieldName.empty())
1677 continue;
1678
1679 // Get the location for the field.
1680 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1681 unsigned FieldLine = getLineNumber(Field->getLocation());
1682 QualType FType = Field->getType();
1683 uint64_t FieldSize = 0;
1684 unsigned FieldAlign = 0;
1685
1686 if (!FType->isIncompleteArrayType()) {
1687
1688 // Bit size, align and offset of the type.
1689 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001690 ? Field->getBitWidthValue(CGM.getContext())
1691 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001692 FieldAlign = CGM.getContext().getTypeAlign(FType);
1693 }
1694
1695 uint64_t FieldOffset;
1696 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1697 // We don't know the runtime offset of an ivar if we're using the
1698 // non-fragile ABI. For bitfields, use the bit offset into the first
1699 // byte of storage of the bitfield. For other fields, use zero.
1700 if (Field->isBitField()) {
1701 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1702 CGM, ID, Field);
1703 FieldOffset %= CGM.getContext().getCharWidth();
1704 } else {
1705 FieldOffset = 0;
1706 }
1707 } else {
1708 FieldOffset = RL.getFieldOffset(FieldNo);
1709 }
1710
1711 unsigned Flags = 0;
1712 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1713 Flags = llvm::DIDescriptor::FlagProtected;
1714 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1715 Flags = llvm::DIDescriptor::FlagPrivate;
1716
1717 llvm::MDNode *PropertyNode = NULL;
1718 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001719 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001720 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1721 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001722 SourceLocation Loc = PD->getLocation();
1723 llvm::DIFile PUnit = getOrCreateFile(Loc);
1724 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001725 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1726 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1727 PropertyNode =
1728 DBuilder.createObjCProperty(PD->getName(),
1729 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001730 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001731 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001732 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001733 getSelectorName(PD->getSetterName()),
1734 PD->getPropertyAttributes(),
1735 getOrCreateType(PD->getType(), PUnit));
1736 }
1737 }
1738 }
1739 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1740 FieldLine, FieldSize, FieldAlign,
1741 FieldOffset, Flags, FieldTy,
1742 PropertyNode);
1743 EltTys.push_back(FieldTy);
1744 }
1745
1746 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001747 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001748
1749 // If the implementation is not yet set, we do not want to mark it
1750 // as complete. An implementation may declare additional
1751 // private ivars that we would miss otherwise.
1752 if (ID->getImplementation() == 0)
1753 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001754
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001755 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001756 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001757}
1758
1759llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1760 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1761 int64_t Count = Ty->getNumElements();
1762 if (Count == 0)
1763 // If number of elements are not known then this is an unbounded array.
1764 // Use Count == -1 to express such arrays.
1765 Count = -1;
1766
1767 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1768 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1769
1770 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1771 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1772
1773 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1774}
1775
1776llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1777 llvm::DIFile Unit) {
1778 uint64_t Size;
1779 uint64_t Align;
1780
1781 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1782 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1783 Size = 0;
1784 Align =
1785 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1786 } else if (Ty->isIncompleteArrayType()) {
1787 Size = 0;
1788 if (Ty->getElementType()->isIncompleteType())
1789 Align = 0;
1790 else
1791 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001792 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001793 Size = 0;
1794 Align = 0;
1795 } else {
1796 // Size and align of the whole array, not the element type.
1797 Size = CGM.getContext().getTypeSize(Ty);
1798 Align = CGM.getContext().getTypeAlign(Ty);
1799 }
1800
1801 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1802 // interior arrays, do we care? Why aren't nested arrays represented the
1803 // obvious/recursive way?
1804 SmallVector<llvm::Value *, 8> Subscripts;
1805 QualType EltTy(Ty, 0);
1806 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1807 // If the number of elements is known, then count is that number. Otherwise,
1808 // it's -1. This allows us to represent a subrange with an array of 0
1809 // elements, like this:
1810 //
1811 // struct foo {
1812 // int x[0];
1813 // };
1814 int64_t Count = -1; // Count == -1 is an unbounded array.
1815 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1816 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001817
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001818 // FIXME: Verify this is right for VLAs.
1819 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1820 EltTy = Ty->getElementType();
1821 }
1822
1823 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1824
Eric Christopher6537f082013-05-16 00:45:12 +00001825 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001826 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1827 SubscriptArray);
1828 return DbgTy;
1829}
1830
Eric Christopher6537f082013-05-16 00:45:12 +00001831llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001833 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 Ty, Ty->getPointeeType(), Unit);
1835}
1836
Eric Christopher6537f082013-05-16 00:45:12 +00001837llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001838 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001839 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001840 Ty, Ty->getPointeeType(), Unit);
1841}
1842
Eric Christopher6537f082013-05-16 00:45:12 +00001843llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001844 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001845 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1846 if (!Ty->getPointeeType()->isFunctionType())
1847 return DBuilder.createMemberPointerType(
David Blaikie47251962013-08-22 13:36:01 +00001848 getOrCreateType(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001849 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1850 CGM.getContext().getPointerType(
1851 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1852 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1853 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001854}
1855
Eric Christopher6537f082013-05-16 00:45:12 +00001856llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001857 llvm::DIFile U) {
1858 // Ignore the atomic wrapping
1859 // FIXME: What is the correct representation?
1860 return getOrCreateType(Ty->getValueType(), U);
1861}
1862
1863/// CreateEnumType - get enumeration type.
1864llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1865 uint64_t Size = 0;
1866 uint64_t Align = 0;
1867 if (!ED->getTypeForDecl()->isIncompleteType()) {
1868 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1869 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1870 }
1871
1872 // If this is just a forward declaration, construct an appropriately
1873 // marked node and just return it.
1874 if (!ED->getDefinition()) {
1875 llvm::DIDescriptor EDContext;
1876 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1877 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1878 unsigned Line = getLineNumber(ED->getLocation());
1879 StringRef EDName = ED->getName();
1880 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1881 EDName, EDContext, DefUnit, Line, 0,
1882 Size, Align);
1883 }
1884
1885 // Create DIEnumerator elements for each enumerator.
1886 SmallVector<llvm::Value *, 16> Enumerators;
1887 ED = ED->getDefinition();
1888 for (EnumDecl::enumerator_iterator
1889 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1890 Enum != EnumEnd; ++Enum) {
1891 Enumerators.push_back(
1892 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001893 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001894 }
1895
1896 // Return a CompositeType for the enum itself.
1897 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1898
1899 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1900 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001901 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001903 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001904 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001905 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001906 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1907 Size, Align, EltArray,
1908 ClassTy);
1909 return DbgTy;
1910}
1911
David Blaikie4b12be62013-01-21 04:37:12 +00001912static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1913 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001914 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001915 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001916 QualType LastT = T;
1917 switch (T->getTypeClass()) {
1918 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001919 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001920 case Type::TemplateSpecialization:
1921 T = cast<TemplateSpecializationType>(T)->desugar();
1922 break;
1923 case Type::TypeOfExpr:
1924 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1925 break;
1926 case Type::TypeOf:
1927 T = cast<TypeOfType>(T)->getUnderlyingType();
1928 break;
1929 case Type::Decltype:
1930 T = cast<DecltypeType>(T)->getUnderlyingType();
1931 break;
1932 case Type::UnaryTransform:
1933 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1934 break;
1935 case Type::Attributed:
1936 T = cast<AttributedType>(T)->getEquivalentType();
1937 break;
1938 case Type::Elaborated:
1939 T = cast<ElaboratedType>(T)->getNamedType();
1940 break;
1941 case Type::Paren:
1942 T = cast<ParenType>(T)->getInnerType();
1943 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001944 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001945 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001946 break;
1947 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001948 QualType DT = cast<AutoType>(T)->getDeducedType();
1949 if (DT.isNull())
1950 return T;
1951 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001952 break;
1953 }
Eric Christopher6537f082013-05-16 00:45:12 +00001954
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001955 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001956 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001957 } while (true);
1958}
1959
Eric Christopherf0890c42013-05-16 00:52:20 +00001960/// getType - Get the type from the cache or return null type if it doesn't
1961/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001962llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1963
1964 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001965 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001966
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001968 if (Ty->getTypeClass() == Type::ObjCInterface) {
1969 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1970 if (V)
1971 return llvm::DIType(cast<llvm::MDNode>(V));
1972 else return llvm::DIType();
1973 }
1974
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001975 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1976 TypeCache.find(Ty.getAsOpaquePtr());
1977 if (it != TypeCache.end()) {
1978 // Verify that the debug info still exists.
1979 if (llvm::Value *V = it->second)
1980 return llvm::DIType(cast<llvm::MDNode>(V));
1981 }
1982
1983 return llvm::DIType();
1984}
1985
1986/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1987/// doesn't exist.
1988llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1989
1990 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001991 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001992
1993 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001994 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001995 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1996 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001997 if (it != CompletedTypeCache.end())
1998 V = it->second;
1999 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002000 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002001 }
2002
Adrian Prantl4919de62013-03-06 22:03:30 +00002003 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00002004 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002005}
2006
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002007/// getCachedInterfaceTypeOrNull - Get the type from the interface
2008/// cache, unless it needs to regenerated. Otherwise return null.
2009llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2010 // Is there a cached interface that hasn't changed?
2011 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2012 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2013
2014 if (it1 != ObjCInterfaceCache.end())
2015 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2016 if (Checksum(Decl) == it1->second.second)
2017 // Return cached forward declaration.
2018 return it1->second.first;
2019
2020 return 0;
2021}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002022
2023/// getOrCreateType - Get the type from the cache or create a new
2024/// one if necessary.
David Blaikie47251962013-08-22 13:36:01 +00002025llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002026 if (Ty.isNull())
2027 return llvm::DIType();
2028
2029 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002030 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002031
David Blaikie47251962013-08-22 13:36:01 +00002032 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002033 return T;
2034
2035 // Otherwise create the type.
David Blaikie47251962013-08-22 13:36:01 +00002036 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002037 void* TyPtr = Ty.getAsOpaquePtr();
2038
2039 // And update the type cache.
2040 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002041
David Blaikie492b1022013-08-15 21:21:19 +00002042 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2043 // into the cache - but getTypeOrNull has a special case for cached interface
2044 // types. We should probably just pull that out as a special case for the
2045 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002046 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002047 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002048 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2049 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2050 // Interface types may have elements added to them by a
2051 // subsequent implementation or extension, so we keep them in
2052 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002053 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002054 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002055 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2056 if (V.first)
2057 return llvm::DIType(cast<llvm::MDNode>(V.first));
2058 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2059 Decl->getName(), TheCU, Unit,
2060 getLineNumber(Decl->getLocation()),
2061 TheCU.getLanguage());
2062 // Store the forward declaration in the cache.
2063 V.first = TC;
2064 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002065
David Blaikiee2eb89a2013-05-21 18:29:40 +00002066 // Register the type for replacement in finalize().
2067 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2068
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002069 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002070 }
2071
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002072 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002073 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002074
2075 return Res;
2076}
2077
Adrian Prantlb5a50072013-06-07 01:10:41 +00002078/// Currently the checksum of an interface includes the number of
2079/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002080unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002081 // The assumption is that the number of ivars can only increase
2082 // monotonically, so it is safe to just use their current number as
2083 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002084 unsigned Sum = 0;
2085 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2086 Ivar != 0; Ivar = Ivar->getNextIvar())
2087 ++Sum;
2088
2089 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002090}
2091
2092ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2093 switch (Ty->getTypeClass()) {
2094 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002095 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2096 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002097 case Type::ObjCInterface:
2098 return cast<ObjCInterfaceType>(Ty)->getDecl();
2099 default:
2100 return 0;
2101 }
2102}
2103
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002104/// CreateTypeNode - Create a new debug type node.
David Blaikie47251962013-08-22 13:36:01 +00002105llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002106 // Handle qualifiers, which recursively handles what they refer to.
2107 if (Ty.hasLocalQualifiers())
David Blaikie47251962013-08-22 13:36:01 +00002108 return CreateQualifiedType(Ty, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002109
2110 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002111
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002112 // Work out details of type.
2113 switch (Ty->getTypeClass()) {
2114#define TYPE(Class, Base)
2115#define ABSTRACT_TYPE(Class, Base)
2116#define NON_CANONICAL_TYPE(Class, Base)
2117#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2118#include "clang/AST/TypeNodes.def"
2119 llvm_unreachable("Dependent types cannot show up in debug information");
2120
2121 case Type::ExtVector:
2122 case Type::Vector:
2123 return CreateType(cast<VectorType>(Ty), Unit);
2124 case Type::ObjCObjectPointer:
2125 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2126 case Type::ObjCObject:
2127 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2128 case Type::ObjCInterface:
2129 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2130 case Type::Builtin:
2131 return CreateType(cast<BuiltinType>(Ty));
2132 case Type::Complex:
2133 return CreateType(cast<ComplexType>(Ty));
2134 case Type::Pointer:
2135 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002136 case Type::Decayed:
2137 // Decayed types are just pointers in LLVM and DWARF.
2138 return CreateType(
2139 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002140 case Type::BlockPointer:
2141 return CreateType(cast<BlockPointerType>(Ty), Unit);
2142 case Type::Typedef:
David Blaikie47251962013-08-22 13:36:01 +00002143 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002144 case Type::Record:
David Blaikie47251962013-08-22 13:36:01 +00002145 return CreateType(cast<RecordType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002146 case Type::Enum:
2147 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2148 case Type::FunctionProto:
2149 case Type::FunctionNoProto:
2150 return CreateType(cast<FunctionType>(Ty), Unit);
2151 case Type::ConstantArray:
2152 case Type::VariableArray:
2153 case Type::IncompleteArray:
2154 return CreateType(cast<ArrayType>(Ty), Unit);
2155
2156 case Type::LValueReference:
2157 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2158 case Type::RValueReference:
2159 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2160
2161 case Type::MemberPointer:
2162 return CreateType(cast<MemberPointerType>(Ty), Unit);
2163
2164 case Type::Atomic:
2165 return CreateType(cast<AtomicType>(Ty), Unit);
2166
2167 case Type::Attributed:
2168 case Type::TemplateSpecialization:
2169 case Type::Elaborated:
2170 case Type::Paren:
2171 case Type::SubstTemplateTypeParm:
2172 case Type::TypeOfExpr:
2173 case Type::TypeOf:
2174 case Type::Decltype:
2175 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002176 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002177 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002178 case Type::Auto:
2179 Diag = "auto";
2180 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002181 }
Eric Christopher6537f082013-05-16 00:45:12 +00002182
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002183 assert(Diag && "Fall through without a diagnostic?");
2184 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2185 "debug information for %0 is not yet supported");
2186 CGM.getDiags().Report(DiagID)
2187 << Diag;
2188 return llvm::DIType();
2189}
2190
2191/// getOrCreateLimitedType - Get the type from the cache or create a new
2192/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002193llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002194 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002195 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002196
David Blaikieeaacc882013-08-20 21:03:29 +00002197 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002198
2199 // We may have cached a forward decl when we could have created
2200 // a non-forward decl. Go ahead and create a non-forward decl
2201 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002202 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002203
2204 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002205 llvm::DICompositeType Res = CreateLimitedType(Ty);
2206
2207 // Propagate members from the declaration to the definition
2208 // CreateType(const RecordType*) will overwrite this with the members in the
2209 // correct order if the full type is needed.
2210 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002211
Eric Christopherb2d13922013-07-18 00:52:50 +00002212 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002213 ReplaceMap.push_back(
2214 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002215
2216 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002217 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002218 return Res;
2219}
2220
2221// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002222llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002223 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002224
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002225 // Get overall information about the record type for the debug info.
2226 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2227 unsigned Line = getLineNumber(RD->getLocation());
2228 StringRef RDName = getClassName(RD);
2229
2230 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002231 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002232 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2233 else
2234 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2235
David Blaikiec138ff52013-08-18 17:36:19 +00002236 // If we ended up creating the type during the context chain construction,
2237 // just return that.
2238 // FIXME: this could be dealt with better if the type was recorded as
2239 // completed before we started this (see the CompletedTypeCache usage in
2240 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2241 // be pushed to before context creation, but after it was known to be
2242 // destined for completion (might still have an issue if this caller only
2243 // required a declaration but the context construction ended up creating a
2244 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002245 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2246 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002247 return T;
2248
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002249 // If this is just a forward declaration, construct an appropriately
2250 // marked node and just return it.
2251 if (!RD->getDefinition())
David Blaikie951094b2013-08-15 18:59:40 +00002252 return getOrCreateRecordFwdDecl(RD, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002253
2254 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2255 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002256 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002257
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002258 if (RD->isUnion())
2259 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002260 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002261 else if (RD->isClass()) {
2262 // FIXME: This could be a struct type giving a default visibility different
2263 // than C++ class type, but needs llvm metadata changes first.
2264 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002265 Size, Align, 0, 0, llvm::DIType(),
2266 llvm::DIArray(), llvm::DIType(),
2267 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002268 } else
2269 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002270 Size, Align, 0, llvm::DIType(),
2271 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002272
2273 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002274 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002275
David Blaikie498298d2013-08-18 16:55:33 +00002276 if (const ClassTemplateSpecializationDecl *TSpecial =
2277 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2278 RealDecl.setTypeArray(llvm::DIArray(),
2279 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002280 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002281}
2282
David Blaikie498298d2013-08-18 16:55:33 +00002283void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2284 llvm::DICompositeType RealDecl) {
2285 // A class's primary base or the class itself contains the vtable.
2286 llvm::DICompositeType ContainingType;
2287 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2288 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2289 // Seek non virtual primary base root.
2290 while (1) {
2291 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2292 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2293 if (PBT && !BRL.isPrimaryBaseVirtual())
2294 PBase = PBT;
2295 else
2296 break;
2297 }
2298 ContainingType = llvm::DICompositeType(
2299 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2300 getOrCreateFile(RD->getLocation())));
2301 } else if (RD->isDynamicClass())
2302 ContainingType = RealDecl;
2303
2304 RealDecl.setContainingType(ContainingType);
2305}
2306
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002307/// CreateMemberType - Create new member and increase Offset by FType's size.
2308llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2309 StringRef Name,
2310 uint64_t *Offset) {
2311 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2312 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2313 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2314 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2315 FieldSize, FieldAlign,
2316 *Offset, 0, FieldTy);
2317 *Offset += FieldSize;
2318 return Ty;
2319}
2320
David Blaikie9faebd22013-05-20 04:58:53 +00002321llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2322 // We only need a declaration (not a definition) of the type - so use whatever
2323 // we would otherwise do to get a type for a pointee. (forward declarations in
2324 // limited debug info, full definitions (if the type definition is available)
2325 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002326 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2327 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie47251962013-08-22 13:36:01 +00002328 getOrCreateFile(TD->getLocation()));
David Blaikie9faebd22013-05-20 04:58:53 +00002329 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2330 // This doesn't handle providing declarations (for functions or variables) for
2331 // entities without definitions in this TU, nor when the definition proceeds
2332 // the call to this function.
2333 // FIXME: This should be split out into more specific maps with support for
2334 // emitting forward declarations and merging definitions with declarations,
2335 // the same way as we do for types.
2336 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2337 DeclCache.find(D->getCanonicalDecl());
2338 if (I == DeclCache.end())
2339 return llvm::DIDescriptor();
2340 llvm::Value *V = I->second;
2341 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2342}
2343
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002344/// getFunctionDeclaration - Return debug info descriptor to describe method
2345/// declaration for the given method definition.
2346llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002347 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2348 return llvm::DISubprogram();
2349
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002350 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2351 if (!FD) return llvm::DISubprogram();
2352
2353 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002354 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002355
2356 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2357 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002358 if (MI == SPCache.end()) {
David Blaikie5434fc22013-08-20 01:28:15 +00002359 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002360 llvm::DICompositeType T(S);
2361 llvm::DISubprogram SP = CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2362 T.addMember(SP);
2363 return SP;
2364 }
2365 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002366 if (MI != SPCache.end()) {
2367 llvm::Value *V = MI->second;
2368 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002369 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002370 return SP;
2371 }
2372
2373 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2374 E = FD->redecls_end(); I != E; ++I) {
2375 const FunctionDecl *NextFD = *I;
2376 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2377 MI = SPCache.find(NextFD->getCanonicalDecl());
2378 if (MI != SPCache.end()) {
2379 llvm::Value *V = MI->second;
2380 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002381 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002382 return SP;
2383 }
2384 }
2385 return llvm::DISubprogram();
2386}
2387
2388// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2389// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002390llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2391 QualType FnType,
2392 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002393 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2394 // Create fake but valid subroutine type. Otherwise
2395 // llvm::DISubprogram::Verify() would return false, and
2396 // subprogram DIE will miss DW_AT_decl_file and
2397 // DW_AT_decl_line fields.
2398 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002399
2400 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2401 return getOrCreateMethodType(Method, F);
2402 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2403 // Add "self" and "_cmd"
2404 SmallVector<llvm::Value *, 16> Elts;
2405
2406 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002407 QualType ResultTy = OMethod->getResultType();
2408
2409 // Replace the instancetype keyword with the actual type.
2410 if (ResultTy == CGM.getContext().getObjCInstanceType())
2411 ResultTy = CGM.getContext().getPointerType(
2412 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2413
Adrian Prantl566a9c32013-05-10 21:08:31 +00002414 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002415 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002416 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2417 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2418 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002419 // "_cmd" pointer is always second argument.
2420 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2421 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2422 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002423 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002424 PE = OMethod->param_end(); PI != PE; ++PI)
2425 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2426
2427 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2428 return DBuilder.createSubroutineType(F, EltTypeArray);
2429 }
David Blaikie9a845292013-05-22 23:22:42 +00002430 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002431}
2432
2433/// EmitFunctionStart - Constructs the debug code for entering a function.
2434void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2435 llvm::Function *Fn,
2436 CGBuilderTy &Builder) {
2437
2438 StringRef Name;
2439 StringRef LinkageName;
2440
2441 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2442
2443 const Decl *D = GD.getDecl();
2444 // Function may lack declaration in source code if it is created by Clang
2445 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2446 bool HasDecl = (D != 0);
2447 // Use the location of the declaration.
2448 SourceLocation Loc;
2449 if (HasDecl)
2450 Loc = D->getLocation();
2451
2452 unsigned Flags = 0;
2453 llvm::DIFile Unit = getOrCreateFile(Loc);
2454 llvm::DIDescriptor FDContext(Unit);
2455 llvm::DIArray TParamsArray;
2456 if (!HasDecl) {
2457 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002458 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002459 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2460 // If there is a DISubprogram for this function available then use it.
2461 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2462 FI = SPCache.find(FD->getCanonicalDecl());
2463 if (FI != SPCache.end()) {
2464 llvm::Value *V = FI->second;
2465 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2466 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2467 llvm::MDNode *SPN = SP;
2468 LexicalBlockStack.push_back(SPN);
2469 RegionMap[D] = llvm::WeakVH(SP);
2470 return;
2471 }
2472 }
2473 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002474 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002475 if (FD->hasPrototype()) {
2476 LinkageName = CGM.getMangledName(GD);
2477 Flags |= llvm::DIDescriptor::FlagPrototyped;
2478 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002479 // No need to replicate the linkage name if it isn't different from the
2480 // subprogram name, no need to have it at all unless coverage is enabled or
2481 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002482 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002483 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2484 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002485 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002486 LinkageName = StringRef();
2487
Eric Christopher13c97672013-05-16 00:45:23 +00002488 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002489 if (const NamespaceDecl *NSDecl =
2490 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2491 FDContext = getOrCreateNameSpace(NSDecl);
2492 else if (const RecordDecl *RDecl =
2493 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2494 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2495
2496 // Collect template parameters.
2497 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2498 }
2499 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2500 Name = getObjCMethodName(OMD);
2501 Flags |= llvm::DIDescriptor::FlagPrototyped;
2502 } else {
2503 // Use llvm function name.
2504 Name = Fn->getName();
2505 Flags |= llvm::DIDescriptor::FlagPrototyped;
2506 }
2507 if (!Name.empty() && Name[0] == '\01')
2508 Name = Name.substr(1);
2509
2510 unsigned LineNo = getLineNumber(Loc);
2511 if (!HasDecl || D->isImplicit())
2512 Flags |= llvm::DIDescriptor::FlagArtificial;
2513
David Blaikie23e66db2013-06-22 00:09:36 +00002514 llvm::DISubprogram SP = DBuilder.createFunction(
2515 FDContext, Name, LinkageName, Unit, LineNo,
2516 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2517 true /*definition*/, getLineNumber(CurLoc), Flags,
2518 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002519 if (HasDecl)
2520 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002521
2522 // Push function on region stack.
2523 llvm::MDNode *SPN = SP;
2524 LexicalBlockStack.push_back(SPN);
2525 if (HasDecl)
2526 RegionMap[D] = llvm::WeakVH(SP);
2527}
2528
2529/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002530/// information in the source file. If the location is invalid, the
2531/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002532void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2533 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002534 // Update our current location
2535 setLocation(Loc);
2536
2537 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2538
2539 // Don't bother if things are the same as last time.
2540 SourceManager &SM = CGM.getContext().getSourceManager();
2541 if (CurLoc == PrevLoc ||
2542 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2543 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002544 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2545 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2546 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002547 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002548
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002549 // Update last state.
2550 PrevLoc = CurLoc;
2551
2552 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002553 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2554 (getLineNumber(CurLoc),
2555 getColumnNumber(CurLoc, ForceColumnInfo),
2556 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002557}
2558
2559/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2560/// the stack.
2561void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2562 llvm::DIDescriptor D =
2563 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2564 llvm::DIDescriptor() :
2565 llvm::DIDescriptor(LexicalBlockStack.back()),
2566 getOrCreateFile(CurLoc),
2567 getLineNumber(CurLoc),
2568 getColumnNumber(CurLoc));
2569 llvm::MDNode *DN = D;
2570 LexicalBlockStack.push_back(DN);
2571}
2572
2573/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2574/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002575void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2576 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002577 // Set our current location.
2578 setLocation(Loc);
2579
2580 // Create a new lexical block and push it on the stack.
2581 CreateLexicalBlock(Loc);
2582
2583 // Emit a line table change for the current location inside the new scope.
2584 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2585 getColumnNumber(Loc),
2586 LexicalBlockStack.back()));
2587}
2588
2589/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2590/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002591void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2592 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002593 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2594
2595 // Provide an entry in the line table for the end of the block.
2596 EmitLocation(Builder, Loc);
2597
2598 LexicalBlockStack.pop_back();
2599}
2600
2601/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2602void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2603 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2604 unsigned RCount = FnBeginRegionCount.back();
2605 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2606
2607 // Pop all regions for this function.
2608 while (LexicalBlockStack.size() != RCount)
2609 EmitLexicalBlockEnd(Builder, CurLoc);
2610 FnBeginRegionCount.pop_back();
2611}
2612
Eric Christopher6537f082013-05-16 00:45:12 +00002613// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002614// See BuildByRefType.
2615llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2616 uint64_t *XOffset) {
2617
2618 SmallVector<llvm::Value *, 5> EltTys;
2619 QualType FType;
2620 uint64_t FieldSize, FieldOffset;
2621 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002622
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002623 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002624 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002625
2626 FieldOffset = 0;
2627 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2628 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2629 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2630 FType = CGM.getContext().IntTy;
2631 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2632 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2633
2634 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2635 if (HasCopyAndDispose) {
2636 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2637 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2638 &FieldOffset));
2639 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2640 &FieldOffset));
2641 }
2642 bool HasByrefExtendedLayout;
2643 Qualifiers::ObjCLifetime Lifetime;
2644 if (CGM.getContext().getByrefLifetime(Type,
2645 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002646 && HasByrefExtendedLayout) {
2647 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002648 EltTys.push_back(CreateMemberType(Unit, FType,
2649 "__byref_variable_layout",
2650 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002651 }
Eric Christopher6537f082013-05-16 00:45:12 +00002652
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002653 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2654 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002655 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002656 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002657 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2658 CharUnits AlignedOffsetInBytes
2659 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2660 CharUnits NumPaddingBytes
2661 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002662
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002663 if (NumPaddingBytes.isPositive()) {
2664 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2665 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2666 pad, ArrayType::Normal, 0);
2667 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2668 }
2669 }
Eric Christopher6537f082013-05-16 00:45:12 +00002670
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002671 FType = Type;
2672 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2673 FieldSize = CGM.getContext().getTypeSize(FType);
2674 FieldAlign = CGM.getContext().toBits(Align);
2675
Eric Christopher6537f082013-05-16 00:45:12 +00002676 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002677 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2678 0, FieldSize, FieldAlign,
2679 FieldOffset, 0, FieldTy);
2680 EltTys.push_back(FieldTy);
2681 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002682
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002684
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002685 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002686
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002687 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002688 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002689}
2690
2691/// EmitDeclare - Emit local variable declaration debug info.
2692void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002693 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002694 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002695 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2697
David Blaikiefc946272013-08-19 03:37:48 +00002698 bool Unwritten =
2699 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2700 cast<Decl>(VD->getDeclContext())->isImplicit());
2701 llvm::DIFile Unit;
2702 if (!Unwritten)
2703 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 llvm::DIType Ty;
2705 uint64_t XOffset = 0;
2706 if (VD->hasAttr<BlocksAttr>())
2707 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002708 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002709 Ty = getOrCreateType(VD->getType(), Unit);
2710
2711 // If there is no debug info for this type then do not emit debug info
2712 // for this variable.
2713 if (!Ty)
2714 return;
2715
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002716 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002717 unsigned Line = 0;
2718 unsigned Column = 0;
2719 if (!Unwritten) {
2720 Line = getLineNumber(VD->getLocation());
2721 Column = getColumnNumber(VD->getLocation());
2722 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002723 unsigned Flags = 0;
2724 if (VD->isImplicit())
2725 Flags |= llvm::DIDescriptor::FlagArtificial;
2726 // If this is the first argument and it is implicit then
2727 // give it an object pointer flag.
2728 // FIXME: There has to be a better way to do this, but for static
2729 // functions there won't be an implicit param at arg1 and
2730 // otherwise it is 'self' or 'this'.
2731 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2732 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002733 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002734 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2735 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002736 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002737
2738 llvm::MDNode *Scope = LexicalBlockStack.back();
2739
2740 StringRef Name = VD->getName();
2741 if (!Name.empty()) {
2742 if (VD->hasAttr<BlocksAttr>()) {
2743 CharUnits offset = CharUnits::fromQuantity(32);
2744 SmallVector<llvm::Value *, 9> addr;
2745 llvm::Type *Int64Ty = CGM.Int64Ty;
2746 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2747 // offset of __forwarding field
2748 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002749 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002750 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2751 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2752 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2753 // offset of x field
2754 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2755 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2756
2757 // Create the descriptor for the variable.
2758 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002759 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002760 llvm::DIDescriptor(Scope),
2761 VD->getName(), Unit, Line, Ty,
2762 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002763
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002764 // Insert an llvm.dbg.declare into the current block.
2765 llvm::Instruction *Call =
2766 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2767 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2768 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002769 }
David Blaikie436653b2013-01-05 05:58:35 +00002770 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2771 // If VD is an anonymous union then Storage represents value for
2772 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002773 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002774 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002775 for (RecordDecl::field_iterator I = RD->field_begin(),
2776 E = RD->field_end();
2777 I != E; ++I) {
2778 FieldDecl *Field = *I;
2779 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2780 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002781
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002782 // Ignore unnamed fields. Do not ignore unnamed records.
2783 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2784 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002785
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 // Use VarDecl's Tag, Scope and Line number.
2787 llvm::DIVariable D =
2788 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002789 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002790 CGM.getLangOpts().Optimize, Flags,
2791 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002792
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002793 // Insert an llvm.dbg.declare into the current block.
2794 llvm::Instruction *Call =
2795 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2796 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2797 }
David Blaikied8180cf2013-01-05 20:03:07 +00002798 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 }
2800 }
David Blaikie436653b2013-01-05 05:58:35 +00002801
2802 // Create the descriptor for the variable.
2803 llvm::DIVariable D =
2804 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2805 Name, Unit, Line, Ty,
2806 CGM.getLangOpts().Optimize, Flags, ArgNo);
2807
2808 // Insert an llvm.dbg.declare into the current block.
2809 llvm::Instruction *Call =
2810 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2811 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002812}
2813
2814void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2815 llvm::Value *Storage,
2816 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002817 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002818 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2819}
2820
Adrian Prantle86fcc42013-03-29 19:20:29 +00002821/// Look up the completed type for a self pointer in the TypeCache and
2822/// create a copy of it with the ObjectPointer and Artificial flags
2823/// set. If the type is not cached, a new one is created. This should
2824/// never happen though, since creating a type for the implicit self
2825/// argument implies that we already parsed the interface definition
2826/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002827llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2828 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002829 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002830 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002831 else DEBUG(llvm::dbgs() << "No cached type for self.");
2832 return DBuilder.createObjectPointerType(Ty);
2833}
2834
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002835void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2836 llvm::Value *Storage,
2837 CGBuilderTy &Builder,
2838 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002839 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002840 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002841
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002842 if (Builder.GetInsertBlock() == 0)
2843 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002844
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002845 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002846
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002847 uint64_t XOffset = 0;
2848 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2849 llvm::DIType Ty;
2850 if (isByRef)
2851 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002852 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002853 Ty = getOrCreateType(VD->getType(), Unit);
2854
2855 // Self is passed along as an implicit non-arg variable in a
2856 // block. Mark it as the object pointer.
2857 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002858 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002859
2860 // Get location information.
2861 unsigned Line = getLineNumber(VD->getLocation());
2862 unsigned Column = getColumnNumber(VD->getLocation());
2863
2864 const llvm::DataLayout &target = CGM.getDataLayout();
2865
2866 CharUnits offset = CharUnits::fromQuantity(
2867 target.getStructLayout(blockInfo.StructureType)
2868 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2869
2870 SmallVector<llvm::Value *, 9> addr;
2871 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002872 if (isa<llvm::AllocaInst>(Storage))
2873 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002874 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2875 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2876 if (isByRef) {
2877 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2878 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2879 // offset of __forwarding field
2880 offset = CGM.getContext()
2881 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2882 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2883 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2884 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2885 // offset of x field
2886 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2887 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2888 }
2889
2890 // Create the descriptor for the variable.
2891 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002892 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002893 llvm::DIDescriptor(LexicalBlockStack.back()),
2894 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002895
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002896 // Insert an llvm.dbg.declare into the current block.
2897 llvm::Instruction *Call =
2898 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2899 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2900 LexicalBlockStack.back()));
2901}
2902
2903/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2904/// variable declaration.
2905void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2906 unsigned ArgNo,
2907 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002908 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002909 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2910}
2911
2912namespace {
2913 struct BlockLayoutChunk {
2914 uint64_t OffsetInBits;
2915 const BlockDecl::Capture *Capture;
2916 };
2917 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2918 return l.OffsetInBits < r.OffsetInBits;
2919 }
2920}
2921
2922void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002923 llvm::Value *Arg,
2924 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002925 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002926 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002927 ASTContext &C = CGM.getContext();
2928 const BlockDecl *blockDecl = block.getBlockDecl();
2929
2930 // Collect some general information about the block's location.
2931 SourceLocation loc = blockDecl->getCaretLocation();
2932 llvm::DIFile tunit = getOrCreateFile(loc);
2933 unsigned line = getLineNumber(loc);
2934 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002935
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002936 // Build the debug-info type for the block literal.
2937 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2938
2939 const llvm::StructLayout *blockLayout =
2940 CGM.getDataLayout().getStructLayout(block.StructureType);
2941
2942 SmallVector<llvm::Value*, 16> fields;
2943 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2944 blockLayout->getElementOffsetInBits(0),
2945 tunit, tunit));
2946 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2947 blockLayout->getElementOffsetInBits(1),
2948 tunit, tunit));
2949 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2950 blockLayout->getElementOffsetInBits(2),
2951 tunit, tunit));
2952 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2953 blockLayout->getElementOffsetInBits(3),
2954 tunit, tunit));
2955 fields.push_back(createFieldType("__descriptor",
2956 C.getPointerType(block.NeedsCopyDispose ?
2957 C.getBlockDescriptorExtendedType() :
2958 C.getBlockDescriptorType()),
2959 0, loc, AS_public,
2960 blockLayout->getElementOffsetInBits(4),
2961 tunit, tunit));
2962
2963 // We want to sort the captures by offset, not because DWARF
2964 // requires this, but because we're paranoid about debuggers.
2965 SmallVector<BlockLayoutChunk, 8> chunks;
2966
2967 // 'this' capture.
2968 if (blockDecl->capturesCXXThis()) {
2969 BlockLayoutChunk chunk;
2970 chunk.OffsetInBits =
2971 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2972 chunk.Capture = 0;
2973 chunks.push_back(chunk);
2974 }
2975
2976 // Variable captures.
2977 for (BlockDecl::capture_const_iterator
2978 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2979 i != e; ++i) {
2980 const BlockDecl::Capture &capture = *i;
2981 const VarDecl *variable = capture.getVariable();
2982 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2983
2984 // Ignore constant captures.
2985 if (captureInfo.isConstant())
2986 continue;
2987
2988 BlockLayoutChunk chunk;
2989 chunk.OffsetInBits =
2990 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2991 chunk.Capture = &capture;
2992 chunks.push_back(chunk);
2993 }
2994
2995 // Sort by offset.
2996 llvm::array_pod_sort(chunks.begin(), chunks.end());
2997
2998 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2999 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3000 uint64_t offsetInBits = i->OffsetInBits;
3001 const BlockDecl::Capture *capture = i->Capture;
3002
3003 // If we have a null capture, this must be the C++ 'this' capture.
3004 if (!capture) {
3005 const CXXMethodDecl *method =
3006 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3007 QualType type = method->getThisType(C);
3008
3009 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3010 offsetInBits, tunit, tunit));
3011 continue;
3012 }
3013
3014 const VarDecl *variable = capture->getVariable();
3015 StringRef name = variable->getName();
3016
3017 llvm::DIType fieldType;
3018 if (capture->isByRef()) {
3019 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3020
3021 // FIXME: this creates a second copy of this type!
3022 uint64_t xoffset;
3023 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3024 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3025 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3026 ptrInfo.first, ptrInfo.second,
3027 offsetInBits, 0, fieldType);
3028 } else {
3029 fieldType = createFieldType(name, variable->getType(), 0,
3030 loc, AS_public, offsetInBits, tunit, tunit);
3031 }
3032 fields.push_back(fieldType);
3033 }
3034
3035 SmallString<36> typeName;
3036 llvm::raw_svector_ostream(typeName)
3037 << "__block_literal_" << CGM.getUniqueBlockCount();
3038
3039 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3040
3041 llvm::DIType type =
3042 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3043 CGM.getContext().toBits(block.BlockSize),
3044 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003045 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003046 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3047
3048 // Get overall information about the block.
3049 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3050 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003051
3052 // Create the descriptor for the parameter.
3053 llvm::DIVariable debugVar =
3054 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003055 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003056 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003057 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003058 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3059
Adrian Prantlbea407c2013-03-14 21:52:59 +00003060 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003061 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003062 llvm::Instruction *DbgVal =
3063 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003064 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003065 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3066 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003067
Adrian Prantlbea407c2013-03-14 21:52:59 +00003068 // Insert an llvm.dbg.declare into the current block.
3069 llvm::Instruction *DbgDecl =
3070 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3071 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003072}
3073
David Blaikie5434fc22013-08-20 01:28:15 +00003074/// If D is an out-of-class definition of a static data member of a class, find
3075/// its corresponding in-class declaration.
3076llvm::DIDerivedType
3077CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3078 if (!D->isStaticDataMember())
3079 return llvm::DIDerivedType();
3080 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3081 StaticDataMemberCache.find(D->getCanonicalDecl());
3082 if (MI != StaticDataMemberCache.end()) {
3083 assert(MI->second && "Static data member declaration should still exist");
3084 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003085 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003086
3087 // If the member wasn't found in the cache, lazily construct and add it to the
3088 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003089 llvm::DICompositeType Ctxt(
3090 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3091 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3092 Ctxt.addMember(T);
3093 return T;
3094}
3095
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003096/// EmitGlobalVariable - Emit information about a global variable.
3097void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3098 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003099 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003100 // Create global variable debug descriptor.
3101 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3102 unsigned LineNo = getLineNumber(D->getLocation());
3103
3104 setLocation(D->getLocation());
3105
3106 QualType T = D->getType();
3107 if (T->isIncompleteArrayType()) {
3108
3109 // CodeGen turns int[] into int[1] so we'll do the same here.
3110 llvm::APInt ConstVal(32, 1);
3111 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3112
3113 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3114 ArrayType::Normal, 0);
3115 }
3116 StringRef DeclName = D->getName();
3117 StringRef LinkageName;
3118 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3119 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3120 LinkageName = Var->getName();
3121 if (LinkageName == DeclName)
3122 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003123 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003124 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003125 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3126 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3127 Var->hasInternalLinkage(), Var,
3128 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003129 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003130}
3131
3132/// EmitGlobalVariable - Emit information about an objective-c interface.
3133void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3134 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003135 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003136 // Create global variable debug descriptor.
3137 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3138 unsigned LineNo = getLineNumber(ID->getLocation());
3139
3140 StringRef Name = ID->getName();
3141
3142 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3143 if (T->isIncompleteArrayType()) {
3144
3145 // CodeGen turns int[] into int[1] so we'll do the same here.
3146 llvm::APInt ConstVal(32, 1);
3147 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3148
3149 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3150 ArrayType::Normal, 0);
3151 }
3152
3153 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3154 getOrCreateType(T, Unit),
3155 Var->hasInternalLinkage(), Var);
3156}
3157
3158/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003159void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003160 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003161 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003162 // Create the descriptor for the variable.
3163 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3164 StringRef Name = VD->getName();
3165 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3166 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3167 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3168 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3169 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3170 }
3171 // Do not use DIGlobalVariable for enums.
3172 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3173 return;
David Blaikie27ab0362013-08-15 21:42:43 +00003174 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3175 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
David Blaikie5434fc22013-08-20 01:28:15 +00003176 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikie9faebd22013-05-20 04:58:53 +00003177 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3178}
3179
3180llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3181 if (!LexicalBlockStack.empty())
3182 return llvm::DIScope(LexicalBlockStack.back());
3183 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003184}
3185
David Blaikie957dac52013-04-22 06:13:21 +00003186void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003187 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3188 return;
David Blaikie957dac52013-04-22 06:13:21 +00003189 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003190 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3191 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003192 getLineNumber(UD.getLocation()));
3193}
3194
David Blaikie9faebd22013-05-20 04:58:53 +00003195void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3196 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3197 return;
3198 assert(UD.shadow_size() &&
3199 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3200 // Emitting one decl is sufficient - debuggers can detect that this is an
3201 // overloaded name & provide lookup for all the overloads.
3202 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003203 if (llvm::DIDescriptor Target =
3204 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003205 DBuilder.createImportedDeclaration(
3206 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3207 getLineNumber(USD.getLocation()));
3208}
3209
David Blaikiefc46ebc2013-05-20 22:50:41 +00003210llvm::DIImportedEntity
3211CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3212 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3213 return llvm::DIImportedEntity(0);
3214 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3215 if (VH)
3216 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3217 llvm::DIImportedEntity R(0);
3218 if (const NamespaceAliasDecl *Underlying =
3219 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3220 // This could cache & dedup here rather than relying on metadata deduping.
3221 R = DBuilder.createImportedModule(
3222 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3223 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3224 NA.getName());
3225 else
3226 R = DBuilder.createImportedModule(
3227 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3228 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3229 getLineNumber(NA.getLocation()), NA.getName());
3230 VH = R;
3231 return R;
3232}
3233
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003234/// getOrCreateNamesSpace - Return namespace descriptor for the given
3235/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003236llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003237CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003238 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003239 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003240 NameSpaceCache.find(NSDecl);
3241 if (I != NameSpaceCache.end())
3242 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003243
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003244 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3245 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003246 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003247 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3248 llvm::DINameSpace NS =
3249 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3250 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3251 return NS;
3252}
3253
3254void CGDebugInfo::finalize() {
3255 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3256 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3257 llvm::DIType Ty, RepTy;
3258 // Verify that the debug info still exists.
3259 if (llvm::Value *V = VI->second)
3260 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003261
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003262 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3263 TypeCache.find(VI->first);
3264 if (it != TypeCache.end()) {
3265 // Verify that the debug info still exists.
3266 if (llvm::Value *V = it->second)
3267 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3268 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003269
Eric Christopherb2d13922013-07-18 00:52:50 +00003270 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003271 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003272 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003273
3274 // We keep our own list of retained types, because we need to look
3275 // up the final type in the type cache.
3276 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3277 RE = RetainedTypes.end(); RI != RE; ++RI)
3278 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3279
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003280 DBuilder.finalize();
3281}