blob: 9b131fd10e93e245c8d7fe5f579ae64febf3e9ab [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"
Yaron Keren921ac4d2013-10-21 20:07:37 +000040#include "llvm/Support/Path.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Adrian Prantled6bbe42013-07-18 00:28:02 +000055
56NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
58 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
61 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
62 }
63}
64
65NoLocation::~NoLocation() {
66 if (DI) {
67 assert(Builder.getCurrentDebugLocation().isUnknown());
68 DI->CurLoc = SavedLoc;
69 }
70}
71
Adrian Prantlb061ce22013-07-18 01:36:04 +000072ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantled6bbe42013-07-18 00:28:02 +000073 : DI(CGF.getDebugInfo()), Builder(B) {
74 if (DI) {
75 SavedLoc = DI->getLocation();
Adrian Prantlb6cdc962013-07-24 20:34:39 +000076 DI->CurLoc = SourceLocation();
77 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
78 }
79}
80
81void ArtificialLocation::Emit() {
82 if (DI) {
Adrian Prantled6bbe42013-07-18 00:28:02 +000083 // Sync the Builder.
84 DI->EmitLocation(Builder, SavedLoc);
85 DI->CurLoc = SourceLocation();
86 // Construct a location that has a valid scope, but no line info.
Adrian Prantlb6cdc962013-07-24 20:34:39 +000087 assert(!DI->LexicalBlockStack.empty());
88 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000089 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
90 }
91}
92
Adrian Prantlb061ce22013-07-18 01:36:04 +000093ArtificialLocation::~ArtificialLocation() {
Adrian Prantled6bbe42013-07-18 00:28:02 +000094 if (DI) {
95 assert(Builder.getCurrentDebugLocation().getLine() == 0);
96 DI->CurLoc = SavedLoc;
97 }
98}
99
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000100void CGDebugInfo::setLocation(SourceLocation Loc) {
101 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +0000102 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000103
104 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
105
106 // If we've changed files in the middle of a lexical scope go ahead
107 // and create a new lexical scope with file node if it's different
108 // from the one in the scope.
109 if (LexicalBlockStack.empty()) return;
110
111 SourceManager &SM = CGM.getContext().getSourceManager();
112 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
113 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
114
115 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
116 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
117 return;
118
119 llvm::MDNode *LB = LexicalBlockStack.back();
120 llvm::DIScope Scope = llvm::DIScope(LB);
121 if (Scope.isLexicalBlockFile()) {
122 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
123 llvm::DIDescriptor D
124 = DBuilder.createLexicalBlockFile(LBF.getScope(),
125 getOrCreateFile(CurLoc));
126 llvm::MDNode *N = D;
127 LexicalBlockStack.pop_back();
128 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000129 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000130 llvm::DIDescriptor D
131 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
132 llvm::MDNode *N = D;
133 LexicalBlockStack.pop_back();
134 LexicalBlockStack.push_back(N);
135 }
136}
137
138/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000139llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000140 if (!Context)
141 return TheCU;
142
143 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
144 I = RegionMap.find(Context);
145 if (I != RegionMap.end()) {
146 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000147 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000148 }
149
150 // Check namespace.
151 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000152 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000153
David Blaikiebb000792013-04-19 06:56:38 +0000154 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
155 if (!RDecl->isDependentType())
156 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000157 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000158 return TheCU;
159}
160
161/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramere5753592013-09-09 14:48:42 +0000162/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000163/// is stored on the side.
164StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
165 assert (FD && "Invalid FunctionDecl!");
166 IdentifierInfo *FII = FD->getIdentifier();
167 FunctionTemplateSpecializationInfo *Info
168 = FD->getTemplateSpecializationInfo();
169 if (!Info && FII)
170 return FII->getName();
171
172 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000173 SmallString<128> NS;
174 llvm::raw_svector_ostream OS(NS);
175 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000176
177 // Add any template specialization args.
178 if (Info) {
179 const TemplateArgumentList *TArgs = Info->TemplateArguments;
180 const TemplateArgument *Args = TArgs->data();
181 unsigned NumArgs = TArgs->size();
182 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000183 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
184 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000185 }
186
187 // Copy this name on the side and use its reference.
Benjamin Kramer84953792013-09-09 16:39:06 +0000188 return internString(OS.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000189}
190
191StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
192 SmallString<256> MethodName;
193 llvm::raw_svector_ostream OS(MethodName);
194 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
195 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000196 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000197 dyn_cast<const ObjCImplementationDecl>(DC)) {
198 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000199 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCInterfaceDecl>(DC)) {
201 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000202 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCCategoryImplDecl>(DC)){
204 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
205 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000206 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000207 // We can extract the type of the class from the self pointer.
208 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
209 QualType ClassTy =
210 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
211 ClassTy.print(OS, PrintingPolicy(LangOptions()));
212 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000213 }
214 OS << ' ' << OMD->getSelector().getAsString() << ']';
215
Benjamin Kramer84953792013-09-09 16:39:06 +0000216 return internString(OS.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000217}
218
219/// getSelectorName - Return selector name. This is used for debugging
220/// info.
221StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer84953792013-09-09 16:39:06 +0000222 return internString(S.getAsString());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000223}
224
225/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000226StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000227CGDebugInfo::getClassName(const RecordDecl *RD) {
228 const ClassTemplateSpecializationDecl *Spec
229 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
230 if (!Spec)
231 return RD->getName();
232
233 const TemplateArgument *Args;
234 unsigned NumArgs;
235 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
236 const TemplateSpecializationType *TST =
237 cast<TemplateSpecializationType>(TAW->getType());
238 Args = TST->getArgs();
239 NumArgs = TST->getNumArgs();
240 } else {
241 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
242 Args = TemplateArgs.data();
243 NumArgs = TemplateArgs.size();
244 }
245 StringRef Name = RD->getIdentifier()->getName();
246 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000247 SmallString<128> TemplateArgList;
248 {
249 llvm::raw_svector_ostream OS(TemplateArgList);
250 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
251 Policy);
252 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000253
254 // Copy this name on the side and use its reference.
Benjamin Kramer84953792013-09-09 16:39:06 +0000255 return internString(Name, TemplateArgList);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000256}
257
258/// getOrCreateFile - Get the file debug info descriptor for the input location.
259llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
260 if (!Loc.isValid())
261 // If Location is not valid then use main input file.
262 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
263
264 SourceManager &SM = CGM.getContext().getSourceManager();
265 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
266
267 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
268 // If the location is not valid then use main input file.
269 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
270
271 // Cache the results.
272 const char *fname = PLoc.getFilename();
273 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
274 DIFileCache.find(fname);
275
276 if (it != DIFileCache.end()) {
277 // Verify that the information still exists.
278 if (llvm::Value *V = it->second)
279 return llvm::DIFile(cast<llvm::MDNode>(V));
280 }
281
282 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
283
284 DIFileCache[fname] = F;
285 return F;
286}
287
288/// getOrCreateMainFile - Get the file info for main compile unit.
289llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
290 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
291}
292
293/// getLineNumber - Get line number for the location. If location is invalid
294/// then use current location.
295unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
296 if (Loc.isInvalid() && CurLoc.isInvalid())
297 return 0;
298 SourceManager &SM = CGM.getContext().getSourceManager();
299 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
300 return PLoc.isValid()? PLoc.getLine() : 0;
301}
302
303/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000304unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000305 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000306 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000307 return 0;
308
309 // If the location is invalid then use the current column.
310 if (Loc.isInvalid() && CurLoc.isInvalid())
311 return 0;
312 SourceManager &SM = CGM.getContext().getSourceManager();
313 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
314 return PLoc.isValid()? PLoc.getColumn() : 0;
315}
316
317StringRef CGDebugInfo::getCurrentDirname() {
318 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
319 return CGM.getCodeGenOpts().DebugCompilationDir;
320
321 if (!CWDName.empty())
322 return CWDName;
323 SmallString<256> CWD;
324 llvm::sys::fs::current_path(CWD);
Benjamin Kramer84953792013-09-09 16:39:06 +0000325 return CWDName = internString(CWD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000326}
327
328/// CreateCompileUnit - Create new compile unit.
329void CGDebugInfo::CreateCompileUnit() {
330
331 // Get absolute path name.
332 SourceManager &SM = CGM.getContext().getSourceManager();
333 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
334 if (MainFileName.empty())
335 MainFileName = "<unknown>";
336
337 // The main file name provided via the "-main-file-name" option contains just
338 // the file name itself with no path information. This file name may have had
339 // a relative path, so we look into the actual file entry for the main
340 // file to determine the real absolute path for the file.
341 std::string MainFileDir;
342 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
343 MainFileDir = MainFile->getDir()->getName();
Yaron Keren921ac4d2013-10-21 20:07:37 +0000344 if (MainFileDir != ".") {
345 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
346 llvm::sys::path::append(MainFileDirSS, MainFileName);
347 MainFileName = MainFileDirSS.str();
348 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000349 }
350
351 // Save filename string.
Benjamin Kramer84953792013-09-09 16:39:06 +0000352 StringRef Filename = internString(MainFileName);
Eric Christopherff971d72013-02-22 23:50:16 +0000353
354 // Save split dwarf file string.
355 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer84953792013-09-09 16:39:06 +0000356 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopher6537f082013-05-16 00:45:12 +0000357
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000358 unsigned LangTag;
359 const LangOptions &LO = CGM.getLangOpts();
360 if (LO.CPlusPlus) {
361 if (LO.ObjC1)
362 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
363 else
364 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
365 } else if (LO.ObjC1) {
366 LangTag = llvm::dwarf::DW_LANG_ObjC;
367 } else if (LO.C99) {
368 LangTag = llvm::dwarf::DW_LANG_C99;
369 } else {
370 LangTag = llvm::dwarf::DW_LANG_C89;
371 }
372
373 std::string Producer = getClangFullVersion();
374
375 // Figure out which version of the ObjC runtime we have.
376 unsigned RuntimeVers = 0;
377 if (LO.ObjC1)
378 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
379
380 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000381 // FIXME - Eliminate TheCU.
Eric Christopher8fed3f42013-07-19 00:51:58 +0000382 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
383 Producer, LO.Optimize,
384 CGM.getCodeGenOpts().DwarfDebugFlags,
385 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000386}
387
388/// CreateType - Get the Basic type from the cache or create a new
389/// one if necessary.
390llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
391 unsigned Encoding = 0;
392 StringRef BTName;
393 switch (BT->getKind()) {
394#define BUILTIN_TYPE(Id, SingletonId)
395#define PLACEHOLDER_TYPE(Id, SingletonId) \
396 case BuiltinType::Id:
397#include "clang/AST/BuiltinTypes.def"
398 case BuiltinType::Dependent:
399 llvm_unreachable("Unexpected builtin type");
400 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000401 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000402 case BuiltinType::Void:
403 return llvm::DIType();
404 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000405 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000406 return ClassTy;
407 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
408 "objc_class", TheCU,
409 getOrCreateMainFile(), 0);
410 return ClassTy;
411 case BuiltinType::ObjCId: {
412 // typedef struct objc_class *Class;
413 // typedef struct objc_object {
414 // Class isa;
415 // } *id;
416
Eric Christopherb2d13922013-07-18 00:52:50 +0000417 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000418 return ObjTy;
419
Eric Christopherb2d13922013-07-18 00:52:50 +0000420 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
422 "objc_class", TheCU,
423 getOrCreateMainFile(), 0);
424
425 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000426
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000427 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
428
Eric Christopherf068c922013-04-02 22:59:11 +0000429 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000430 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
431 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000432
Eric Christopherf068c922013-04-02 22:59:11 +0000433 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
434 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000435 return ObjTy;
436 }
437 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000438 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000439 return SelTy;
440 SelTy =
441 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
442 "objc_selector", TheCU, getOrCreateMainFile(),
443 0);
444 return SelTy;
445 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000446
447 case BuiltinType::OCLImage1d:
448 return getOrCreateStructPtrType("opencl_image1d_t",
449 OCLImage1dDITy);
450 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000451 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000452 OCLImage1dArrayDITy);
453 case BuiltinType::OCLImage1dBuffer:
454 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
455 OCLImage1dBufferDITy);
456 case BuiltinType::OCLImage2d:
457 return getOrCreateStructPtrType("opencl_image2d_t",
458 OCLImage2dDITy);
459 case BuiltinType::OCLImage2dArray:
460 return getOrCreateStructPtrType("opencl_image2d_array_t",
461 OCLImage2dArrayDITy);
462 case BuiltinType::OCLImage3d:
463 return getOrCreateStructPtrType("opencl_image3d_t",
464 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000465 case BuiltinType::OCLSampler:
466 return DBuilder.createBasicType("opencl_sampler_t",
467 CGM.getContext().getTypeSize(BT),
468 CGM.getContext().getTypeAlign(BT),
469 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000470 case BuiltinType::OCLEvent:
471 return getOrCreateStructPtrType("opencl_event_t",
472 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000473
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000474 case BuiltinType::UChar:
475 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
476 case BuiltinType::Char_S:
477 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
478 case BuiltinType::Char16:
479 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
480 case BuiltinType::UShort:
481 case BuiltinType::UInt:
482 case BuiltinType::UInt128:
483 case BuiltinType::ULong:
484 case BuiltinType::WChar_U:
485 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
486 case BuiltinType::Short:
487 case BuiltinType::Int:
488 case BuiltinType::Int128:
489 case BuiltinType::Long:
490 case BuiltinType::WChar_S:
491 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
492 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
493 case BuiltinType::Half:
494 case BuiltinType::Float:
495 case BuiltinType::LongDouble:
496 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
497 }
498
499 switch (BT->getKind()) {
500 case BuiltinType::Long: BTName = "long int"; break;
501 case BuiltinType::LongLong: BTName = "long long int"; break;
502 case BuiltinType::ULong: BTName = "long unsigned int"; break;
503 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
504 default:
505 BTName = BT->getName(CGM.getLangOpts());
506 break;
507 }
508 // Bit size, align and offset of the type.
509 uint64_t Size = CGM.getContext().getTypeSize(BT);
510 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000511 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000512 DBuilder.createBasicType(BTName, Size, Align, Encoding);
513 return DbgTy;
514}
515
516llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
517 // Bit size, align and offset of the type.
518 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
519 if (Ty->isComplexIntegerType())
520 Encoding = llvm::dwarf::DW_ATE_lo_user;
521
522 uint64_t Size = CGM.getContext().getTypeSize(Ty);
523 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000524 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000525 DBuilder.createBasicType("complex", Size, Align, Encoding);
526
527 return DbgTy;
528}
529
530/// CreateCVRType - Get the qualified type from the cache or create
531/// a new one if necessary.
David Blaikie29b8b682013-09-04 22:03:57 +0000532llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000533 QualifierCollector Qc;
534 const Type *T = Qc.strip(Ty);
535
536 // Ignore these qualifiers for now.
537 Qc.removeObjCGCAttr();
538 Qc.removeAddressSpace();
539 Qc.removeObjCLifetime();
540
541 // We will create one Derived type for one qualifier and recurse to handle any
542 // additional ones.
543 unsigned Tag;
544 if (Qc.hasConst()) {
545 Tag = llvm::dwarf::DW_TAG_const_type;
546 Qc.removeConst();
547 } else if (Qc.hasVolatile()) {
548 Tag = llvm::dwarf::DW_TAG_volatile_type;
549 Qc.removeVolatile();
550 } else if (Qc.hasRestrict()) {
551 Tag = llvm::dwarf::DW_TAG_restrict_type;
552 Qc.removeRestrict();
553 } else {
554 assert(Qc.empty() && "Unknown type qualifier for debug info");
555 return getOrCreateType(QualType(T, 0), Unit);
556 }
557
David Blaikie29b8b682013-09-04 22:03:57 +0000558 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000559
560 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
561 // CVR derived types.
562 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000563
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000564 return DbgTy;
565}
566
567llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
568 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000569
570 // The frontend treats 'id' as a typedef to an ObjCObjectType,
571 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
572 // debug info, we want to emit 'id' in both cases.
573 if (Ty->isObjCQualifiedIdType())
574 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
575
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000576 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000577 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000578 Ty->getPointeeType(), Unit);
579 return DbgTy;
580}
581
582llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
583 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000584 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000585 Ty->getPointeeType(), Unit);
586}
587
Manman Ren83369bf2013-08-29 23:19:58 +0000588/// In C++ mode, types have linkage, so we can rely on the ODR and
589/// on their mangled names, if they're external.
590static SmallString<256>
591getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
592 llvm::DICompileUnit TheCU) {
593 SmallString<256> FullName;
594 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
595 // For now, only apply ODR with C++.
596 const TagDecl *TD = Ty->getDecl();
597 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
598 !TD->isExternallyVisible())
599 return FullName;
600 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
601 if (CGM.getTarget().getCXXABI().isMicrosoft())
602 return FullName;
603
604 // TODO: This is using the RTTI name. Is there a better way to get
605 // a unique string for a type?
606 llvm::raw_svector_ostream Out(FullName);
607 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
608 Out.flush();
609 return FullName;
610}
611
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000612// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000613llvm::DICompositeType
Manman Renf3327332013-08-28 21:20:28 +0000614CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikieeaacc882013-08-20 21:03:29 +0000615 llvm::DIDescriptor Ctx) {
Manman Renf3327332013-08-28 21:20:28 +0000616 const RecordDecl *RD = Ty->getDecl();
David Blaikiec5cd1a72013-08-15 20:17:25 +0000617 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000618 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000619 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
620 unsigned Line = getLineNumber(RD->getLocation());
621 StringRef RDName = getClassName(RD);
622
623 unsigned Tag = 0;
624 if (RD->isStruct() || RD->isInterface())
625 Tag = llvm::dwarf::DW_TAG_structure_type;
626 else if (RD->isUnion())
627 Tag = llvm::dwarf::DW_TAG_union_type;
628 else {
629 assert(RD->isClass());
630 Tag = llvm::dwarf::DW_TAG_class_type;
631 }
632
633 // Create the type.
Manman Ren83369bf2013-08-29 23:19:58 +0000634 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
635 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
636 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000637}
638
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000639llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000640 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000641 QualType PointeeTy,
642 llvm::DIFile Unit) {
643 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie29b8b682013-09-04 22:03:57 +0000645 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000646
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000647 // Bit size, align and offset of the type.
648 // Size is always the size of a pointer. We can't use getTypeSize here
649 // because that does not return the correct value for references.
650 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000651 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000652 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
653
David Blaikie29b8b682013-09-04 22:03:57 +0000654 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
655 Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000656}
657
Eric Christopherf0890c42013-05-16 00:52:20 +0000658llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
659 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000660 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000661 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000662 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
663 TheCU, getOrCreateMainFile(), 0);
664 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
665 Cache = DBuilder.createPointerType(Cache, Size);
666 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000667}
668
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000669llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
670 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000671 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000672 return BlockLiteralGeneric;
673
674 SmallVector<llvm::Value *, 8> EltTys;
675 llvm::DIType FieldTy;
676 QualType FType;
677 uint64_t FieldSize, FieldOffset;
678 unsigned FieldAlign;
679 llvm::DIArray Elements;
680 llvm::DIType EltTy, DescTy;
681
682 FieldOffset = 0;
683 FType = CGM.getContext().UnsignedLongTy;
684 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
685 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
686
687 Elements = DBuilder.getOrCreateArray(EltTys);
688 EltTys.clear();
689
690 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
691 unsigned LineNo = getLineNumber(CurLoc);
692
693 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
694 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000695 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000696
697 // Bit size, align and offset of the type.
698 uint64_t Size = CGM.getContext().getTypeSize(Ty);
699
700 DescTy = DBuilder.createPointerType(EltTy, Size);
701
702 FieldOffset = 0;
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
705 FType = CGM.getContext().IntTy;
706 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
707 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
710
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
712 FieldTy = DescTy;
713 FieldSize = CGM.getContext().getTypeSize(Ty);
714 FieldAlign = CGM.getContext().getTypeAlign(Ty);
715 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
716 LineNo, FieldSize, FieldAlign,
717 FieldOffset, 0, FieldTy);
718 EltTys.push_back(FieldTy);
719
720 FieldOffset += FieldSize;
721 Elements = DBuilder.getOrCreateArray(EltTys);
722
723 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
724 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000725 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000726
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000727 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
728 return BlockLiteralGeneric;
729}
730
David Blaikie29b8b682013-09-04 22:03:57 +0000731llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000732 // Typedefs are derived from some other type. If we have a typedef of a
733 // typedef, make sure to emit the whole chain.
David Blaikie29b8b682013-09-04 22:03:57 +0000734 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherb2d13922013-07-18 00:52:50 +0000735 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000736 return llvm::DIType();
737 // We don't set size information, but do specify where the typedef was
738 // declared.
739 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
740 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000741
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000742 llvm::DIDescriptor TypedefContext =
743 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000744
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000745 return
746 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
747}
748
749llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
750 llvm::DIFile Unit) {
751 SmallVector<llvm::Value *, 16> EltTys;
752
753 // Add the result type at least.
David Blaikie29b8b682013-09-04 22:03:57 +0000754 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000755
756 // Set up remainder of arguments if there is a prototype.
757 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
758 if (isa<FunctionNoProtoType>(Ty))
759 EltTys.push_back(DBuilder.createUnspecifiedParameter());
760 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
761 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie29b8b682013-09-04 22:03:57 +0000762 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000763 }
764
765 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
766 return DBuilder.createSubroutineType(Unit, EltTypeArray);
767}
768
769
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000770llvm::DIType CGDebugInfo::createFieldType(StringRef name,
771 QualType type,
772 uint64_t sizeInBitsOverride,
773 SourceLocation loc,
774 AccessSpecifier AS,
775 uint64_t offsetInBits,
776 llvm::DIFile tunit,
Manman Renc23b1db2013-09-08 03:45:05 +0000777 llvm::DIScope scope) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000778 llvm::DIType debugType = getOrCreateType(type, tunit);
779
780 // Get the location for the field.
781 llvm::DIFile file = getOrCreateFile(loc);
782 unsigned line = getLineNumber(loc);
783
784 uint64_t sizeInBits = 0;
785 unsigned alignInBits = 0;
786 if (!type->isIncompleteArrayType()) {
787 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
788
789 if (sizeInBitsOverride)
790 sizeInBits = sizeInBitsOverride;
791 }
792
793 unsigned flags = 0;
794 if (AS == clang::AS_private)
795 flags |= llvm::DIDescriptor::FlagPrivate;
796 else if (AS == clang::AS_protected)
797 flags |= llvm::DIDescriptor::FlagProtected;
798
799 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
800 alignInBits, offsetInBits, flags, debugType);
801}
802
Eric Christopher0395de32013-01-16 01:22:32 +0000803/// CollectRecordLambdaFields - Helper for CollectRecordFields.
804void CGDebugInfo::
805CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
806 SmallVectorImpl<llvm::Value *> &elements,
807 llvm::DIType RecordTy) {
808 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
809 // has the name and the location of the variable so we should iterate over
810 // both concurrently.
811 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
812 RecordDecl::field_iterator Field = CXXDecl->field_begin();
813 unsigned fieldno = 0;
814 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
815 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
816 const LambdaExpr::Capture C = *I;
817 if (C.capturesVariable()) {
818 VarDecl *V = C.getCapturedVar();
819 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
820 StringRef VName = V->getName();
821 uint64_t SizeInBitsOverride = 0;
822 if (Field->isBitField()) {
823 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
824 assert(SizeInBitsOverride && "found named 0-width bitfield");
825 }
826 llvm::DIType fieldType
827 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
828 C.getLocation(), Field->getAccess(),
829 layout.getFieldOffset(fieldno), VUnit, RecordTy);
830 elements.push_back(fieldType);
831 } else {
832 // TODO: Need to handle 'this' in some way by probably renaming the
833 // this of the lambda class and having a field member of 'this' or
834 // by using AT_object_pointer for the function and having that be
835 // used as 'this' for semantic references.
836 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
837 FieldDecl *f = *Field;
838 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
839 QualType type = f->getType();
840 llvm::DIType fieldType
841 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
842 layout.getFieldOffset(fieldno), VUnit, RecordTy);
843
844 elements.push_back(fieldType);
845 }
846 }
847}
848
David Blaikie5434fc22013-08-20 01:28:15 +0000849/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000850llvm::DIDerivedType
851CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
852 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000853 // Create the descriptor for the static variable, with or without
854 // constant initializers.
855 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
856 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
857
Eric Christopher0395de32013-01-16 01:22:32 +0000858 unsigned LineNumber = getLineNumber(Var->getLocation());
859 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000860 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000861 if (Var->getInit()) {
862 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000863 if (Value) {
864 if (Value->isInt())
865 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
866 if (Value->isFloat())
867 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
868 }
Eric Christopher0395de32013-01-16 01:22:32 +0000869 }
870
871 unsigned Flags = 0;
872 AccessSpecifier Access = Var->getAccess();
873 if (Access == clang::AS_private)
874 Flags |= llvm::DIDescriptor::FlagPrivate;
875 else if (Access == clang::AS_protected)
876 Flags |= llvm::DIDescriptor::FlagProtected;
877
David Blaikiecbcb0302013-08-15 22:50:29 +0000878 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
879 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000880 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000881 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000882}
883
884/// CollectRecordNormalField - Helper for CollectRecordFields.
885void CGDebugInfo::
886CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
887 llvm::DIFile tunit,
888 SmallVectorImpl<llvm::Value *> &elements,
889 llvm::DIType RecordTy) {
890 StringRef name = field->getName();
891 QualType type = field->getType();
892
893 // Ignore unnamed fields unless they're anonymous structs/unions.
894 if (name.empty() && !type->isRecordType())
895 return;
896
897 uint64_t SizeInBitsOverride = 0;
898 if (field->isBitField()) {
899 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
900 assert(SizeInBitsOverride && "found named 0-width bitfield");
901 }
902
903 llvm::DIType fieldType
904 = createFieldType(name, type, SizeInBitsOverride,
905 field->getLocation(), field->getAccess(),
906 OffsetInBits, tunit, RecordTy);
907
908 elements.push_back(fieldType);
909}
910
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000911/// CollectRecordFields - A helper function to collect debug info for
912/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000913void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
914 llvm::DIFile tunit,
915 SmallVectorImpl<llvm::Value *> &elements,
916 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000917 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
918
Eric Christopher0395de32013-01-16 01:22:32 +0000919 if (CXXDecl && CXXDecl->isLambda())
920 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
921 else {
922 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000923
Eric Christopher0395de32013-01-16 01:22:32 +0000924 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000925 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000926
Eric Christopher0395de32013-01-16 01:22:32 +0000927 // Static and non-static members should appear in the same order as
928 // the corresponding declarations in the source program.
929 for (RecordDecl::decl_iterator I = record->decls_begin(),
930 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000931 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
932 // Reuse the existing static member declaration if one exists
933 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
934 StaticDataMemberCache.find(V->getCanonicalDecl());
935 if (MI != StaticDataMemberCache.end()) {
936 assert(MI->second &&
937 "Static data member declaration should still exist");
938 elements.push_back(
939 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
940 } else
941 elements.push_back(CreateRecordStaticField(V, RecordTy));
942 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000943 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
944 tunit, elements, RecordTy);
945
946 // Bump field number for next field.
947 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000948 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949 }
950}
951
952/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
953/// function type is not updated to include implicit "this" pointer. Use this
954/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000955llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000956CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
957 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000958 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000959 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000960 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000961 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
962 Func, Unit);
963}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000964
David Blaikie9a845292013-05-22 23:22:42 +0000965llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000966 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000967 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000968 llvm::DIArray Args = llvm::DICompositeType(
969 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000970 assert (Args.getNumElements() && "Invalid number of arguments!");
971
972 SmallVector<llvm::Value *, 16> Elts;
973
974 // First element is always return type. For 'void' functions it is NULL.
975 Elts.push_back(Args.getElement(0));
976
David Blaikie67f8b5e2013-01-07 22:24:59 +0000977 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000978 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000979 if (isa<ClassTemplateSpecializationDecl>(RD)) {
980 // Create pointer type directly in this case.
981 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
982 QualType PointeeTy = ThisPtrTy->getPointeeType();
983 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000984 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000985 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
986 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000987 llvm::DIType ThisPtrType =
988 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000989 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
990 // TODO: This and the artificial type below are misleading, the
991 // types aren't artificial the argument is, but the current
992 // metadata doesn't represent that.
993 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
994 Elts.push_back(ThisPtrType);
995 } else {
996 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
997 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
999 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001000 }
1001
1002 // Copy rest of the arguments.
1003 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1004 Elts.push_back(Args.getElement(i));
1005
1006 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1007
1008 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1009}
1010
Eric Christopher6537f082013-05-16 00:45:12 +00001011/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001012/// inside a function.
1013static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1014 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1015 return isFunctionLocalClass(NRD);
1016 if (isa<FunctionDecl>(RD->getDeclContext()))
1017 return true;
1018 return false;
1019}
1020
1021/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1022/// a single member function GlobalDecl.
1023llvm::DISubprogram
1024CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1025 llvm::DIFile Unit,
1026 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001027 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001028 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001029
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001030 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001031 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001032
1033 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1034 // make sense to give a single ctor/dtor a linkage name.
1035 StringRef MethodLinkageName;
1036 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1037 MethodLinkageName = CGM.getMangledName(Method);
1038
1039 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001040 llvm::DIFile MethodDefUnit;
1041 unsigned MethodLine = 0;
1042 if (!Method->isImplicit()) {
1043 MethodDefUnit = getOrCreateFile(Method->getLocation());
1044 MethodLine = getLineNumber(Method->getLocation());
1045 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001046
1047 // Collect virtual method info.
1048 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001049 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001050 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001051
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001052 if (Method->isVirtual()) {
1053 if (Method->isPure())
1054 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1055 else
1056 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001057
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001058 // It doesn't make sense to give a virtual destructor a vtable index,
1059 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001060 // FIXME: Add proper support for debug info for virtual calls in
1061 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1062 // lookup if we have multiple or virtual inheritance.
1063 if (!isa<CXXDestructorDecl>(Method) &&
1064 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +00001065 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001066 ContainingType = RecordTy;
1067 }
1068
1069 unsigned Flags = 0;
1070 if (Method->isImplicit())
1071 Flags |= llvm::DIDescriptor::FlagArtificial;
1072 AccessSpecifier Access = Method->getAccess();
1073 if (Access == clang::AS_private)
1074 Flags |= llvm::DIDescriptor::FlagPrivate;
1075 else if (Access == clang::AS_protected)
1076 Flags |= llvm::DIDescriptor::FlagProtected;
1077 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1078 if (CXXC->isExplicit())
1079 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001080 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001081 dyn_cast<CXXConversionDecl>(Method)) {
1082 if (CXXC->isExplicit())
1083 Flags |= llvm::DIDescriptor::FlagExplicit;
1084 }
1085 if (Method->hasPrototype())
1086 Flags |= llvm::DIDescriptor::FlagPrototyped;
1087
1088 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1089 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001090 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001091 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001092 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001093 /* isDefinition=*/ false,
1094 Virtuality, VIndex, ContainingType,
1095 Flags, CGM.getLangOpts().Optimize, NULL,
1096 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001097
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001098 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1099
1100 return SP;
1101}
1102
1103/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001104/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001105/// a Record.
1106void CGDebugInfo::
1107CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1108 SmallVectorImpl<llvm::Value *> &EltTys,
1109 llvm::DIType RecordTy) {
1110
1111 // Since we want more than just the individual member decls if we
1112 // have templated functions iterate over every declaration to gather
1113 // the functions.
1114 for(DeclContext::decl_iterator I = RD->decls_begin(),
1115 E = RD->decls_end(); I != E; ++I) {
David Blaikiec5761272013-08-28 17:27:13 +00001116 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001117 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001118 // It may be associated with the declaration of the type & should be
1119 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001120 //
1121 // This situation can arise in the vtable-based debug info reduction where
1122 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001123 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1124 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001125 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001126 // If the member is implicit, lazily create it when we see the
1127 // definition, not before. (an ODR-used implicit default ctor that's
1128 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001129 if (!Method->isImplicit())
1130 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1131 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001132 EltTys.push_back(MI->second);
Eric Christopherac7c25f2013-08-28 23:12:10 +00001133 } else if (const FunctionTemplateDecl *FTD =
1134 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikie11fa7512013-08-28 23:06:52 +00001135 // Add any template specializations that have already been seen. Like
1136 // implicit member functions, these may have been added to a declaration
1137 // in the case of vtable-based debug info reduction.
Eric Christopherac7c25f2013-08-28 23:12:10 +00001138 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1139 SE = FTD->spec_end();
1140 SI != SE; ++SI) {
David Blaikie11fa7512013-08-28 23:06:52 +00001141 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1142 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1143 if (MI != SPCache.end())
1144 EltTys.push_back(MI->second);
1145 }
David Blaikie5434fc22013-08-20 01:28:15 +00001146 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001147 }
Eric Christopher6537f082013-05-16 00:45:12 +00001148}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001149
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001150/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001151/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001152/// a Record.
1153void CGDebugInfo::
1154CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1155 SmallVectorImpl<llvm::Value *> &EltTys,
1156 llvm::DIType RecordTy) {
1157
1158 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1159 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1160 BE = RD->bases_end(); BI != BE; ++BI) {
1161 unsigned BFlags = 0;
1162 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001163
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001164 const CXXRecordDecl *Base =
1165 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001166
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001167 if (BI->isVirtual()) {
1168 // virtual base offset offset is -ve. The code generator emits dwarf
1169 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001170 BaseOffset =
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +00001171 0 - CGM.getItaniumVTableContext()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001172 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1173 BFlags = llvm::DIDescriptor::FlagVirtual;
1174 } else
1175 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1176 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1177 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001178
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001179 AccessSpecifier Access = BI->getAccessSpecifier();
1180 if (Access == clang::AS_private)
1181 BFlags |= llvm::DIDescriptor::FlagPrivate;
1182 else if (Access == clang::AS_protected)
1183 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001184
1185 llvm::DIType DTy =
1186 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 getOrCreateType(BI->getType(), Unit),
1188 BaseOffset, BFlags);
1189 EltTys.push_back(DTy);
1190 }
1191}
1192
1193/// CollectTemplateParams - A helper function to collect template parameters.
1194llvm::DIArray CGDebugInfo::
1195CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001196 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001197 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001198 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001199 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1200 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001201 StringRef Name;
1202 if (TPList)
1203 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001204 switch (TA.getKind()) {
1205 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001206 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1207 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001208 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001209 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001210 } break;
1211 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001212 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1213 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001214 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001215 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001216 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1217 TemplateParams.push_back(TVP);
1218 } break;
1219 case TemplateArgument::Declaration: {
1220 const ValueDecl *D = TA.getAsDecl();
1221 bool InstanceMember = D->isCXXInstanceMember();
1222 QualType T = InstanceMember
1223 ? CGM.getContext().getMemberPointerType(
1224 D->getType(), cast<RecordDecl>(D->getDeclContext())
1225 ->getTypeForDecl())
1226 : CGM.getContext().getPointerType(D->getType());
1227 llvm::DIType TTy = getOrCreateType(T, Unit);
1228 llvm::Value *V = 0;
1229 // Variable pointer template parameters have a value that is the address
1230 // of the variable.
1231 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1232 V = CGM.GetAddrOfGlobalVar(VD);
1233 // Member function pointers have special support for building them, though
1234 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001235 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001236 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1237 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001238 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1239 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001240 // Member data pointers have special handling too to compute the fixed
1241 // offset within the object.
1242 if (isa<FieldDecl>(D)) {
1243 // These five lines (& possibly the above member function pointer
1244 // handling) might be able to be refactored to use similar code in
1245 // CodeGenModule::getMemberPointerConstant
1246 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1247 CharUnits chars =
1248 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1249 V = CGM.getCXXABI().EmitMemberDataPointer(
1250 cast<MemberPointerType>(T.getTypePtr()), chars);
1251 }
1252 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001253 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1254 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001255 TemplateParams.push_back(TVP);
1256 } break;
1257 case TemplateArgument::NullPtr: {
1258 QualType T = TA.getNullPtrType();
1259 llvm::DIType TTy = getOrCreateType(T, Unit);
1260 llvm::Value *V = 0;
1261 // Special case member data pointer null values since they're actually -1
1262 // instead of zero.
1263 if (const MemberPointerType *MPT =
1264 dyn_cast<MemberPointerType>(T.getTypePtr()))
1265 // But treat member function pointers as simple zero integers because
1266 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1267 // CodeGen grows handling for values of non-null member function
1268 // pointers then perhaps we could remove this special case and rely on
1269 // EmitNullMemberPointer for member function pointers.
1270 if (MPT->isMemberDataPointer())
1271 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1272 if (!V)
1273 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1274 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001275 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001276 TemplateParams.push_back(TVP);
1277 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001278 case TemplateArgument::Template: {
1279 llvm::DITemplateValueParameter TVP =
1280 DBuilder.createTemplateTemplateParameter(
1281 TheCU, Name, llvm::DIType(),
1282 TA.getAsTemplate().getAsTemplateDecl()
1283 ->getQualifiedNameAsString());
1284 TemplateParams.push_back(TVP);
1285 } break;
1286 case TemplateArgument::Pack: {
1287 llvm::DITemplateValueParameter TVP =
1288 DBuilder.createTemplateParameterPack(
1289 TheCU, Name, llvm::DIType(),
1290 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1291 TemplateParams.push_back(TVP);
1292 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001293 case TemplateArgument::Expression: {
1294 const Expr *E = TA.getAsExpr();
1295 QualType T = E->getType();
1296 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1297 assert(V && "Expression in template argument isn't constant");
1298 llvm::DIType TTy = getOrCreateType(T, Unit);
1299 llvm::DITemplateValueParameter TVP =
1300 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1301 V->stripPointerCasts());
1302 TemplateParams.push_back(TVP);
1303 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001304 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001305 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001306 case TemplateArgument::Null:
1307 llvm_unreachable(
1308 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001309 }
1310 }
1311 return DBuilder.getOrCreateArray(TemplateParams);
1312}
1313
1314/// CollectFunctionTemplateParams - A helper function to collect debug
1315/// info for function template parameters.
1316llvm::DIArray CGDebugInfo::
1317CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1318 if (FD->getTemplatedKind() ==
1319 FunctionDecl::TK_FunctionTemplateSpecialization) {
1320 const TemplateParameterList *TList =
1321 FD->getTemplateSpecializationInfo()->getTemplate()
1322 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001323 return CollectTemplateParams(
1324 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001325 }
1326 return llvm::DIArray();
1327}
1328
1329/// CollectCXXTemplateParams - A helper function to collect debug info for
1330/// template parameters.
1331llvm::DIArray CGDebugInfo::
1332CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1333 llvm::DIFile Unit) {
1334 llvm::PointerUnion<ClassTemplateDecl *,
1335 ClassTemplatePartialSpecializationDecl *>
1336 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001337
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001338 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1339 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1340 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1341 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001342 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001343}
1344
1345/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1346llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1347 if (VTablePtrType.isValid())
1348 return VTablePtrType;
1349
1350 ASTContext &Context = CGM.getContext();
1351
1352 /* Function type */
1353 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1354 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1355 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1356 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1357 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1358 "__vtbl_ptr_type");
1359 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1360 return VTablePtrType;
1361}
1362
1363/// getVTableName - Get vtable name for the given Class.
1364StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer84953792013-09-09 16:39:06 +00001365 // Copy the gdb compatible name on the side and use its reference.
1366 return internString("_vptr$", RD->getNameAsString());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001367}
1368
1369
1370/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1371/// debug info entry in EltTys vector.
1372void CGDebugInfo::
1373CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1374 SmallVectorImpl<llvm::Value *> &EltTys) {
1375 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1376
1377 // If there is a primary base then it will hold vtable info.
1378 if (RL.getPrimaryBase())
1379 return;
1380
1381 // If this class is not dynamic then there is not any vtable info to collect.
1382 if (!RD->isDynamicClass())
1383 return;
1384
1385 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1386 llvm::DIType VPTR
1387 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001388 0, Size, 0, 0,
1389 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001390 getOrCreateVTablePtrType(Unit));
1391 EltTys.push_back(VPTR);
1392}
1393
Eric Christopher6537f082013-05-16 00:45:12 +00001394/// getOrCreateRecordType - Emit record type's standalone debug info.
1395llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001396 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001397 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001398 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1399 return T;
1400}
1401
1402/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1403/// debug info.
1404llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001405 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001406 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001408 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001409 return T;
1410}
1411
David Blaikie27804892013-08-15 20:49:17 +00001412void CGDebugInfo::completeType(const RecordDecl *RD) {
1413 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1414 !CGM.getLangOpts().CPlusPlus)
1415 completeRequiredType(RD);
1416}
1417
1418void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001419 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1420 if (CXXDecl->isDynamicClass())
1421 return;
1422
David Blaikie27804892013-08-15 20:49:17 +00001423 QualType Ty = CGM.getContext().getRecordType(RD);
1424 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001425 if (T && T.isForwardDecl())
1426 completeClassData(RD);
1427}
1428
1429void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1430 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001431 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001432 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001433 void* TyPtr = Ty.getAsOpaquePtr();
1434 if (CompletedTypeCache.count(TyPtr))
1435 return;
1436 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1437 assert(!Res.isForwardDecl());
1438 CompletedTypeCache[TyPtr] = Res;
1439 TypeCache[TyPtr] = Res;
1440}
1441
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001442/// CreateType - get structure or union type.
David Blaikie29b8b682013-09-04 22:03:57 +00001443llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001444 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001445 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie29b8b682013-09-04 22:03:57 +00001446 // Always emit declarations for types that aren't required to be complete when
1447 // in limit-debug-info mode. If the type is later found to be required to be
1448 // complete this declaration will be upgraded to a definition by
1449 // `completeRequiredType`.
1450 // If the type is dynamic, only emit the definition in TUs that require class
1451 // data. This is handled by `completeClassData`.
David Blaikie74341d82013-09-06 06:45:04 +00001452 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1453 // If we've already emitted the type, just use that, even if it's only a
1454 // declaration. The completeType, completeRequiredType, and completeClassData
1455 // callbacks will handle promoting the declaration to a definition.
1456 if (T ||
1457 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1458 // Under -flimit-debug-info, emit only a declaration unless the type is
1459 // required to be complete.
David Blaikie5434fc22013-08-20 01:28:15 +00001460 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
David Blaikie74341d82013-09-06 06:45:04 +00001461 // If the class is dynamic, only emit a declaration. A definition will be
1462 // emitted whenever the vtable is emitted.
1463 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) || T) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001464 llvm::DIDescriptor FDContext =
1465 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie74341d82013-09-06 06:45:04 +00001466 if (!T)
1467 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1468 return T;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001469 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001470
David Blaikie27804892013-08-15 20:49:17 +00001471 return CreateTypeDefinition(Ty);
1472}
1473
1474llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1475 RecordDecl *RD = Ty->getDecl();
1476
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001477 // Get overall information about the record type for the debug info.
1478 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1479
1480 // Records and classes and unions can all be recursive. To handle them, we
1481 // first generate a debug descriptor for the struct as a forward declaration.
1482 // Then (if it is a definition) we go through and get debug info for all of
1483 // its members. Finally, we create a descriptor for the complete type (which
1484 // may refer to the forward decl if the struct is recursive) and replace all
1485 // uses of the forward declaration with the final definition.
1486
David Blaikie4a077162013-08-12 22:24:20 +00001487 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001488 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001489 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001490
1491 if (FwdDecl.isForwardDecl())
1492 return FwdDecl;
1493
David Blaikie498298d2013-08-18 16:55:33 +00001494 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1495 CollectContainingType(CXXDecl, FwdDecl);
1496
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001497 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001498 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1500
Adrian Prantl4919de62013-03-06 22:03:30 +00001501 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001502 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1503
1504 // Convert all the elements.
1505 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001506 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001507
1508 // Note: The split of CXXDecl information here is intentional, the
1509 // gdb tests will depend on a certain ordering at printout. The debug
1510 // information offsets are still correct if we merge them all together
1511 // though.
1512 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1513 if (CXXDecl) {
1514 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1515 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1516 }
1517
Eric Christopher0395de32013-01-16 01:22:32 +00001518 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001519 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopherd6b52972013-10-11 18:16:51 +00001520 if (CXXDecl)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001521 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001522
1523 LexicalBlockStack.pop_back();
1524 RegionMap.erase(Ty->getDecl());
1525
1526 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001527 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528
Eric Christopherf068c922013-04-02 22:59:11 +00001529 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1530 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001531}
1532
1533/// CreateType - get objective-c object type.
1534llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1535 llvm::DIFile Unit) {
1536 // Ignore protocols.
1537 return getOrCreateType(Ty->getBaseType(), Unit);
1538}
1539
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001540
1541/// \return true if Getter has the default name for the property PD.
1542static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1543 const ObjCMethodDecl *Getter) {
1544 assert(PD);
1545 if (!Getter)
1546 return true;
1547
1548 assert(Getter->getDeclName().isObjCZeroArgSelector());
1549 return PD->getName() ==
1550 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1551}
1552
1553/// \return true if Setter has the default name for the property PD.
1554static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1555 const ObjCMethodDecl *Setter) {
1556 assert(PD);
1557 if (!Setter)
1558 return true;
1559
1560 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001561 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001562 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1563}
1564
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001565/// CreateType - get objective-c interface type.
1566llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1567 llvm::DIFile Unit) {
1568 ObjCInterfaceDecl *ID = Ty->getDecl();
1569 if (!ID)
1570 return llvm::DIType();
1571
1572 // Get overall information about the record type for the debug info.
1573 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1574 unsigned Line = getLineNumber(ID->getLocation());
1575 unsigned RuntimeLang = TheCU.getLanguage();
1576
1577 // If this is just a forward declaration return a special forward-declaration
1578 // debug type since we won't be able to lay out the entire type.
1579 ObjCInterfaceDecl *Def = ID->getDefinition();
1580 if (!Def) {
1581 llvm::DIType FwdDecl =
1582 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001583 ID->getName(), TheCU, DefUnit, Line,
1584 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001585 return FwdDecl;
1586 }
1587
1588 ID = Def;
1589
1590 // Bit size, align and offset of the type.
1591 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1592 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1593
1594 unsigned Flags = 0;
1595 if (ID->getImplementation())
1596 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1597
Eric Christopherf068c922013-04-02 22:59:11 +00001598 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001599 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1600 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001601 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001602
1603 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1604 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001605 QualType QualTy = QualType(Ty, 0);
1606 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001607
Eric Christopherd3003dc2013-07-14 21:00:07 +00001608 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001609 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001610 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1611
1612 // Convert all the elements.
1613 SmallVector<llvm::Value *, 16> EltTys;
1614
1615 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1616 if (SClass) {
1617 llvm::DIType SClassTy =
1618 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1619 if (!SClassTy.isValid())
1620 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001621
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001622 llvm::DIType InhTag =
1623 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1624 EltTys.push_back(InhTag);
1625 }
1626
Eric Christopherd3003dc2013-07-14 21:00:07 +00001627 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001628 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1629 E = ID->prop_end(); I != E; ++I) {
1630 const ObjCPropertyDecl *PD = *I;
1631 SourceLocation Loc = PD->getLocation();
1632 llvm::DIFile PUnit = getOrCreateFile(Loc);
1633 unsigned PLine = getLineNumber(Loc);
1634 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1635 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1636 llvm::MDNode *PropertyNode =
1637 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001638 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001639 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001640 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001641 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001642 getSelectorName(PD->getSetterName()),
1643 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001644 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001645 EltTys.push_back(PropertyNode);
1646 }
1647
1648 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1649 unsigned FieldNo = 0;
1650 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1651 Field = Field->getNextIvar(), ++FieldNo) {
1652 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1653 if (!FieldTy.isValid())
1654 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001655
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001656 StringRef FieldName = Field->getName();
1657
1658 // Ignore unnamed fields.
1659 if (FieldName.empty())
1660 continue;
1661
1662 // Get the location for the field.
1663 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1664 unsigned FieldLine = getLineNumber(Field->getLocation());
1665 QualType FType = Field->getType();
1666 uint64_t FieldSize = 0;
1667 unsigned FieldAlign = 0;
1668
1669 if (!FType->isIncompleteArrayType()) {
1670
1671 // Bit size, align and offset of the type.
1672 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001673 ? Field->getBitWidthValue(CGM.getContext())
1674 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001675 FieldAlign = CGM.getContext().getTypeAlign(FType);
1676 }
1677
1678 uint64_t FieldOffset;
1679 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1680 // We don't know the runtime offset of an ivar if we're using the
1681 // non-fragile ABI. For bitfields, use the bit offset into the first
1682 // byte of storage of the bitfield. For other fields, use zero.
1683 if (Field->isBitField()) {
1684 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1685 CGM, ID, Field);
1686 FieldOffset %= CGM.getContext().getCharWidth();
1687 } else {
1688 FieldOffset = 0;
1689 }
1690 } else {
1691 FieldOffset = RL.getFieldOffset(FieldNo);
1692 }
1693
1694 unsigned Flags = 0;
1695 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1696 Flags = llvm::DIDescriptor::FlagProtected;
1697 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1698 Flags = llvm::DIDescriptor::FlagPrivate;
1699
1700 llvm::MDNode *PropertyNode = NULL;
1701 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001702 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001703 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1704 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001705 SourceLocation Loc = PD->getLocation();
1706 llvm::DIFile PUnit = getOrCreateFile(Loc);
1707 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001708 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1709 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1710 PropertyNode =
1711 DBuilder.createObjCProperty(PD->getName(),
1712 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001713 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001715 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001716 getSelectorName(PD->getSetterName()),
1717 PD->getPropertyAttributes(),
1718 getOrCreateType(PD->getType(), PUnit));
1719 }
1720 }
1721 }
1722 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1723 FieldLine, FieldSize, FieldAlign,
1724 FieldOffset, Flags, FieldTy,
1725 PropertyNode);
1726 EltTys.push_back(FieldTy);
1727 }
1728
1729 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001730 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001731
1732 // If the implementation is not yet set, we do not want to mark it
1733 // as complete. An implementation may declare additional
1734 // private ivars that we would miss otherwise.
1735 if (ID->getImplementation() == 0)
1736 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001737
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001738 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001739 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001740}
1741
1742llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1743 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1744 int64_t Count = Ty->getNumElements();
1745 if (Count == 0)
1746 // If number of elements are not known then this is an unbounded array.
1747 // Use Count == -1 to express such arrays.
1748 Count = -1;
1749
1750 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1751 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1752
1753 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1754 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1755
1756 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1757}
1758
1759llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1760 llvm::DIFile Unit) {
1761 uint64_t Size;
1762 uint64_t Align;
1763
1764 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1765 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1766 Size = 0;
1767 Align =
1768 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1769 } else if (Ty->isIncompleteArrayType()) {
1770 Size = 0;
1771 if (Ty->getElementType()->isIncompleteType())
1772 Align = 0;
1773 else
1774 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001775 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001776 Size = 0;
1777 Align = 0;
1778 } else {
1779 // Size and align of the whole array, not the element type.
1780 Size = CGM.getContext().getTypeSize(Ty);
1781 Align = CGM.getContext().getTypeAlign(Ty);
1782 }
1783
1784 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1785 // interior arrays, do we care? Why aren't nested arrays represented the
1786 // obvious/recursive way?
1787 SmallVector<llvm::Value *, 8> Subscripts;
1788 QualType EltTy(Ty, 0);
1789 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1790 // If the number of elements is known, then count is that number. Otherwise,
1791 // it's -1. This allows us to represent a subrange with an array of 0
1792 // elements, like this:
1793 //
1794 // struct foo {
1795 // int x[0];
1796 // };
1797 int64_t Count = -1; // Count == -1 is an unbounded array.
1798 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1799 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001800
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001801 // FIXME: Verify this is right for VLAs.
1802 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1803 EltTy = Ty->getElementType();
1804 }
1805
1806 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1807
Eric Christopher6537f082013-05-16 00:45:12 +00001808 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001809 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1810 SubscriptArray);
1811 return DbgTy;
1812}
1813
Eric Christopher6537f082013-05-16 00:45:12 +00001814llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001815 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001816 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 Ty, Ty->getPointeeType(), Unit);
1818}
1819
Eric Christopher6537f082013-05-16 00:45:12 +00001820llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001821 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001822 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001823 Ty, Ty->getPointeeType(), Unit);
1824}
1825
Eric Christopher6537f082013-05-16 00:45:12 +00001826llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001827 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001828 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1829 if (!Ty->getPointeeType()->isFunctionType())
1830 return DBuilder.createMemberPointerType(
David Blaikie29b8b682013-09-04 22:03:57 +00001831 getOrCreateType(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001832 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1833 CGM.getContext().getPointerType(
1834 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1835 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1836 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001837}
1838
Eric Christopher6537f082013-05-16 00:45:12 +00001839llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001840 llvm::DIFile U) {
1841 // Ignore the atomic wrapping
1842 // FIXME: What is the correct representation?
1843 return getOrCreateType(Ty->getValueType(), U);
1844}
1845
1846/// CreateEnumType - get enumeration type.
Manman Ren0a0be742013-08-28 21:46:36 +00001847llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Renf3327332013-08-28 21:20:28 +00001848 const EnumDecl *ED = Ty->getDecl();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001849 uint64_t Size = 0;
1850 uint64_t Align = 0;
1851 if (!ED->getTypeForDecl()->isIncompleteType()) {
1852 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1853 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1854 }
1855
Manman Ren83369bf2013-08-29 23:19:58 +00001856 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1857
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 // If this is just a forward declaration, construct an appropriately
1859 // marked node and just return it.
1860 if (!ED->getDefinition()) {
1861 llvm::DIDescriptor EDContext;
1862 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1863 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1864 unsigned Line = getLineNumber(ED->getLocation());
1865 StringRef EDName = ED->getName();
1866 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1867 EDName, EDContext, DefUnit, Line, 0,
Manman Ren83369bf2013-08-29 23:19:58 +00001868 Size, Align, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001869 }
1870
1871 // Create DIEnumerator elements for each enumerator.
1872 SmallVector<llvm::Value *, 16> Enumerators;
1873 ED = ED->getDefinition();
1874 for (EnumDecl::enumerator_iterator
1875 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1876 Enum != EnumEnd; ++Enum) {
1877 Enumerators.push_back(
1878 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001879 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 }
1881
1882 // Return a CompositeType for the enum itself.
1883 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1884
1885 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1886 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001887 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001888 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001889 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001890 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001891 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1893 Size, Align, EltArray,
Manman Ren83369bf2013-08-29 23:19:58 +00001894 ClassTy, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001895 return DbgTy;
1896}
1897
David Blaikie4b12be62013-01-21 04:37:12 +00001898static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1899 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001900 do {
Adrian Prantl35969ea2013-09-26 21:35:50 +00001901 Qualifiers InnerQuals = T.getLocalQualifiers();
1902 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1903 // that is already there.
1904 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1905 Quals += InnerQuals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001906 QualType LastT = T;
1907 switch (T->getTypeClass()) {
1908 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001909 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001910 case Type::TemplateSpecialization:
1911 T = cast<TemplateSpecializationType>(T)->desugar();
1912 break;
1913 case Type::TypeOfExpr:
1914 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1915 break;
1916 case Type::TypeOf:
1917 T = cast<TypeOfType>(T)->getUnderlyingType();
1918 break;
1919 case Type::Decltype:
1920 T = cast<DecltypeType>(T)->getUnderlyingType();
1921 break;
1922 case Type::UnaryTransform:
1923 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1924 break;
1925 case Type::Attributed:
1926 T = cast<AttributedType>(T)->getEquivalentType();
1927 break;
1928 case Type::Elaborated:
1929 T = cast<ElaboratedType>(T)->getNamedType();
1930 break;
1931 case Type::Paren:
1932 T = cast<ParenType>(T)->getInnerType();
1933 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001934 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001935 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001936 break;
1937 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001938 QualType DT = cast<AutoType>(T)->getDeducedType();
1939 if (DT.isNull())
1940 return T;
1941 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001942 break;
1943 }
Eric Christopher6537f082013-05-16 00:45:12 +00001944
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001945 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001946 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001947 } while (true);
1948}
1949
Eric Christopherf0890c42013-05-16 00:52:20 +00001950/// getType - Get the type from the cache or return null type if it doesn't
1951/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001952llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1953
1954 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001955 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001956
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001957 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001958 if (Ty->getTypeClass() == Type::ObjCInterface) {
1959 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1960 if (V)
1961 return llvm::DIType(cast<llvm::MDNode>(V));
1962 else return llvm::DIType();
1963 }
1964
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001965 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1966 TypeCache.find(Ty.getAsOpaquePtr());
1967 if (it != TypeCache.end()) {
1968 // Verify that the debug info still exists.
1969 if (llvm::Value *V = it->second)
1970 return llvm::DIType(cast<llvm::MDNode>(V));
1971 }
1972
1973 return llvm::DIType();
1974}
1975
1976/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1977/// doesn't exist.
1978llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1979
1980 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001981 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001982
1983 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001984 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001985 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1986 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001987 if (it != CompletedTypeCache.end())
1988 V = it->second;
1989 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001990 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001991 }
1992
Adrian Prantl4919de62013-03-06 22:03:30 +00001993 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00001994 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001995}
1996
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001997/// getCachedInterfaceTypeOrNull - Get the type from the interface
1998/// cache, unless it needs to regenerated. Otherwise return null.
1999llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2000 // Is there a cached interface that hasn't changed?
2001 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2002 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2003
2004 if (it1 != ObjCInterfaceCache.end())
2005 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2006 if (Checksum(Decl) == it1->second.second)
2007 // Return cached forward declaration.
2008 return it1->second.first;
2009
2010 return 0;
2011}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002012
2013/// getOrCreateType - Get the type from the cache or create a new
2014/// one if necessary.
David Blaikie29b8b682013-09-04 22:03:57 +00002015llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002016 if (Ty.isNull())
2017 return llvm::DIType();
2018
2019 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002020 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002021
David Blaikie29b8b682013-09-04 22:03:57 +00002022 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002023 return T;
2024
2025 // Otherwise create the type.
David Blaikie29b8b682013-09-04 22:03:57 +00002026 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002027 void* TyPtr = Ty.getAsOpaquePtr();
2028
2029 // And update the type cache.
2030 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002031
David Blaikie492b1022013-08-15 21:21:19 +00002032 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2033 // into the cache - but getTypeOrNull has a special case for cached interface
2034 // types. We should probably just pull that out as a special case for the
2035 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002036 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002037 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002038 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2039 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2040 // Interface types may have elements added to them by a
2041 // subsequent implementation or extension, so we keep them in
2042 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002043 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002044 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002045 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2046 if (V.first)
2047 return llvm::DIType(cast<llvm::MDNode>(V.first));
2048 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2049 Decl->getName(), TheCU, Unit,
2050 getLineNumber(Decl->getLocation()),
2051 TheCU.getLanguage());
2052 // Store the forward declaration in the cache.
2053 V.first = TC;
2054 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002055
David Blaikiee2eb89a2013-05-21 18:29:40 +00002056 // Register the type for replacement in finalize().
2057 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2058
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002059 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002060 }
2061
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002062 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002063 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002064
2065 return Res;
2066}
2067
Adrian Prantlb5a50072013-06-07 01:10:41 +00002068/// Currently the checksum of an interface includes the number of
2069/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002070unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002071 // The assumption is that the number of ivars can only increase
2072 // monotonically, so it is safe to just use their current number as
2073 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002074 unsigned Sum = 0;
2075 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2076 Ivar != 0; Ivar = Ivar->getNextIvar())
2077 ++Sum;
2078
2079 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002080}
2081
2082ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2083 switch (Ty->getTypeClass()) {
2084 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002085 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2086 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002087 case Type::ObjCInterface:
2088 return cast<ObjCInterfaceType>(Ty)->getDecl();
2089 default:
2090 return 0;
2091 }
2092}
2093
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002094/// CreateTypeNode - Create a new debug type node.
David Blaikie29b8b682013-09-04 22:03:57 +00002095llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002096 // Handle qualifiers, which recursively handles what they refer to.
2097 if (Ty.hasLocalQualifiers())
David Blaikie29b8b682013-09-04 22:03:57 +00002098 return CreateQualifiedType(Ty, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002099
2100 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002101
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002102 // Work out details of type.
2103 switch (Ty->getTypeClass()) {
2104#define TYPE(Class, Base)
2105#define ABSTRACT_TYPE(Class, Base)
2106#define NON_CANONICAL_TYPE(Class, Base)
2107#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2108#include "clang/AST/TypeNodes.def"
2109 llvm_unreachable("Dependent types cannot show up in debug information");
2110
2111 case Type::ExtVector:
2112 case Type::Vector:
2113 return CreateType(cast<VectorType>(Ty), Unit);
2114 case Type::ObjCObjectPointer:
2115 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2116 case Type::ObjCObject:
2117 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2118 case Type::ObjCInterface:
2119 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2120 case Type::Builtin:
2121 return CreateType(cast<BuiltinType>(Ty));
2122 case Type::Complex:
2123 return CreateType(cast<ComplexType>(Ty));
2124 case Type::Pointer:
2125 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002126 case Type::Decayed:
2127 // Decayed types are just pointers in LLVM and DWARF.
2128 return CreateType(
2129 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002130 case Type::BlockPointer:
2131 return CreateType(cast<BlockPointerType>(Ty), Unit);
2132 case Type::Typedef:
David Blaikie29b8b682013-09-04 22:03:57 +00002133 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002134 case Type::Record:
David Blaikie29b8b682013-09-04 22:03:57 +00002135 return CreateType(cast<RecordType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136 case Type::Enum:
Manman Renf3327332013-08-28 21:20:28 +00002137 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002138 case Type::FunctionProto:
2139 case Type::FunctionNoProto:
2140 return CreateType(cast<FunctionType>(Ty), Unit);
2141 case Type::ConstantArray:
2142 case Type::VariableArray:
2143 case Type::IncompleteArray:
2144 return CreateType(cast<ArrayType>(Ty), Unit);
2145
2146 case Type::LValueReference:
2147 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2148 case Type::RValueReference:
2149 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2150
2151 case Type::MemberPointer:
2152 return CreateType(cast<MemberPointerType>(Ty), Unit);
2153
2154 case Type::Atomic:
2155 return CreateType(cast<AtomicType>(Ty), Unit);
2156
2157 case Type::Attributed:
2158 case Type::TemplateSpecialization:
2159 case Type::Elaborated:
2160 case Type::Paren:
2161 case Type::SubstTemplateTypeParm:
2162 case Type::TypeOfExpr:
2163 case Type::TypeOf:
2164 case Type::Decltype:
2165 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002166 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002167 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002168 case Type::Auto:
2169 Diag = "auto";
2170 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002171 }
Eric Christopher6537f082013-05-16 00:45:12 +00002172
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002173 assert(Diag && "Fall through without a diagnostic?");
2174 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2175 "debug information for %0 is not yet supported");
2176 CGM.getDiags().Report(DiagID)
2177 << Diag;
2178 return llvm::DIType();
2179}
2180
2181/// getOrCreateLimitedType - Get the type from the cache or create a new
2182/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002183llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002184 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002185 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002186
David Blaikieeaacc882013-08-20 21:03:29 +00002187 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002188
2189 // We may have cached a forward decl when we could have created
2190 // a non-forward decl. Go ahead and create a non-forward decl
2191 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002192 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002193
2194 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002195 llvm::DICompositeType Res = CreateLimitedType(Ty);
2196
2197 // Propagate members from the declaration to the definition
2198 // CreateType(const RecordType*) will overwrite this with the members in the
2199 // correct order if the full type is needed.
2200 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002201
Eric Christopherb2d13922013-07-18 00:52:50 +00002202 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002203 ReplaceMap.push_back(
2204 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002205
2206 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002207 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002208 return Res;
2209}
2210
2211// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002212llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002213 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002214
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002215 // Get overall information about the record type for the debug info.
2216 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2217 unsigned Line = getLineNumber(RD->getLocation());
2218 StringRef RDName = getClassName(RD);
2219
Eric Christopher89fecb52013-10-15 21:22:34 +00002220 llvm::DIDescriptor RDContext =
2221 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002222
David Blaikiec138ff52013-08-18 17:36:19 +00002223 // If we ended up creating the type during the context chain construction,
2224 // just return that.
2225 // FIXME: this could be dealt with better if the type was recorded as
2226 // completed before we started this (see the CompletedTypeCache usage in
2227 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2228 // be pushed to before context creation, but after it was known to be
2229 // destined for completion (might still have an issue if this caller only
2230 // required a declaration but the context construction ended up creating a
2231 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002232 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2233 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002234 return T;
2235
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002236 // If this is just a forward declaration, construct an appropriately
2237 // marked node and just return it.
2238 if (!RD->getDefinition())
Manman Renf3327332013-08-28 21:20:28 +00002239 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002240
2241 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2242 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002243 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002244
Manman Ren83369bf2013-08-29 23:19:58 +00002245 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2246
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002247 if (RD->isUnion())
2248 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Ren83369bf2013-08-29 23:19:58 +00002249 Size, Align, 0, llvm::DIArray(), 0,
2250 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002251 else if (RD->isClass()) {
2252 // FIXME: This could be a struct type giving a default visibility different
2253 // than C++ class type, but needs llvm metadata changes first.
2254 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002255 Size, Align, 0, 0, llvm::DIType(),
2256 llvm::DIArray(), llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002257 llvm::DIArray(), FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002258 } else
2259 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002260 Size, Align, 0, llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002261 llvm::DIArray(), 0, 0, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002262
2263 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002264 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002265
David Blaikie498298d2013-08-18 16:55:33 +00002266 if (const ClassTemplateSpecializationDecl *TSpecial =
2267 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2268 RealDecl.setTypeArray(llvm::DIArray(),
2269 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002270 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002271}
2272
David Blaikie498298d2013-08-18 16:55:33 +00002273void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2274 llvm::DICompositeType RealDecl) {
2275 // A class's primary base or the class itself contains the vtable.
2276 llvm::DICompositeType ContainingType;
2277 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2278 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2279 // Seek non virtual primary base root.
2280 while (1) {
2281 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2282 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2283 if (PBT && !BRL.isPrimaryBaseVirtual())
2284 PBase = PBT;
2285 else
2286 break;
2287 }
2288 ContainingType = llvm::DICompositeType(
2289 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2290 getOrCreateFile(RD->getLocation())));
2291 } else if (RD->isDynamicClass())
2292 ContainingType = RealDecl;
2293
2294 RealDecl.setContainingType(ContainingType);
2295}
2296
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002297/// CreateMemberType - Create new member and increase Offset by FType's size.
2298llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2299 StringRef Name,
2300 uint64_t *Offset) {
2301 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2302 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2303 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2304 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2305 FieldSize, FieldAlign,
2306 *Offset, 0, FieldTy);
2307 *Offset += FieldSize;
2308 return Ty;
2309}
2310
David Blaikie9faebd22013-05-20 04:58:53 +00002311llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2312 // We only need a declaration (not a definition) of the type - so use whatever
2313 // we would otherwise do to get a type for a pointee. (forward declarations in
2314 // limited debug info, full definitions (if the type definition is available)
2315 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002316 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2317 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie29b8b682013-09-04 22:03:57 +00002318 getOrCreateFile(TD->getLocation()));
David Blaikie9faebd22013-05-20 04:58:53 +00002319 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2320 // This doesn't handle providing declarations (for functions or variables) for
2321 // entities without definitions in this TU, nor when the definition proceeds
2322 // the call to this function.
2323 // FIXME: This should be split out into more specific maps with support for
2324 // emitting forward declarations and merging definitions with declarations,
2325 // the same way as we do for types.
2326 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2327 DeclCache.find(D->getCanonicalDecl());
2328 if (I == DeclCache.end())
2329 return llvm::DIDescriptor();
2330 llvm::Value *V = I->second;
2331 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2332}
2333
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002334/// getFunctionDeclaration - Return debug info descriptor to describe method
2335/// declaration for the given method definition.
2336llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002337 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2338 return llvm::DISubprogram();
2339
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002340 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2341 if (!FD) return llvm::DISubprogram();
2342
2343 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002344 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002345
2346 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2347 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002348 if (MI == SPCache.end()) {
Eric Christopherac7c25f2013-08-28 23:12:10 +00002349 if (const CXXMethodDecl *MD =
2350 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002351 llvm::DICompositeType T(S);
Eric Christopherac7c25f2013-08-28 23:12:10 +00002352 llvm::DISubprogram SP =
2353 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikied6d5d692013-08-09 17:20:05 +00002354 T.addMember(SP);
2355 return SP;
2356 }
2357 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002358 if (MI != SPCache.end()) {
2359 llvm::Value *V = MI->second;
2360 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002361 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002362 return SP;
2363 }
2364
2365 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2366 E = FD->redecls_end(); I != E; ++I) {
2367 const FunctionDecl *NextFD = *I;
2368 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2369 MI = SPCache.find(NextFD->getCanonicalDecl());
2370 if (MI != SPCache.end()) {
2371 llvm::Value *V = MI->second;
2372 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002373 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002374 return SP;
2375 }
2376 }
2377 return llvm::DISubprogram();
2378}
2379
2380// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2381// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002382llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2383 QualType FnType,
2384 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002385 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2386 // Create fake but valid subroutine type. Otherwise
2387 // llvm::DISubprogram::Verify() would return false, and
2388 // subprogram DIE will miss DW_AT_decl_file and
2389 // DW_AT_decl_line fields.
2390 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002391
2392 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2393 return getOrCreateMethodType(Method, F);
2394 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2395 // Add "self" and "_cmd"
2396 SmallVector<llvm::Value *, 16> Elts;
2397
2398 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002399 QualType ResultTy = OMethod->getResultType();
2400
2401 // Replace the instancetype keyword with the actual type.
2402 if (ResultTy == CGM.getContext().getObjCInstanceType())
2403 ResultTy = CGM.getContext().getPointerType(
2404 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2405
Adrian Prantl566a9c32013-05-10 21:08:31 +00002406 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002407 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002408 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2409 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2410 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002411 // "_cmd" pointer is always second argument.
2412 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2413 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2414 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002415 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002416 PE = OMethod->param_end(); PI != PE; ++PI)
2417 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2418
2419 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2420 return DBuilder.createSubroutineType(F, EltTypeArray);
2421 }
David Blaikie9a845292013-05-22 23:22:42 +00002422 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002423}
2424
2425/// EmitFunctionStart - Constructs the debug code for entering a function.
2426void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2427 llvm::Function *Fn,
2428 CGBuilderTy &Builder) {
2429
2430 StringRef Name;
2431 StringRef LinkageName;
2432
2433 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2434
2435 const Decl *D = GD.getDecl();
2436 // Function may lack declaration in source code if it is created by Clang
2437 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2438 bool HasDecl = (D != 0);
2439 // Use the location of the declaration.
2440 SourceLocation Loc;
2441 if (HasDecl)
2442 Loc = D->getLocation();
2443
2444 unsigned Flags = 0;
2445 llvm::DIFile Unit = getOrCreateFile(Loc);
2446 llvm::DIDescriptor FDContext(Unit);
2447 llvm::DIArray TParamsArray;
2448 if (!HasDecl) {
2449 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002450 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002451 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2452 // If there is a DISubprogram for this function available then use it.
2453 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2454 FI = SPCache.find(FD->getCanonicalDecl());
2455 if (FI != SPCache.end()) {
2456 llvm::Value *V = FI->second;
2457 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2458 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2459 llvm::MDNode *SPN = SP;
2460 LexicalBlockStack.push_back(SPN);
2461 RegionMap[D] = llvm::WeakVH(SP);
2462 return;
2463 }
2464 }
2465 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002466 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002467 if (FD->hasPrototype()) {
2468 LinkageName = CGM.getMangledName(GD);
2469 Flags |= llvm::DIDescriptor::FlagPrototyped;
2470 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002471 // No need to replicate the linkage name if it isn't different from the
2472 // subprogram name, no need to have it at all unless coverage is enabled or
2473 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002474 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002475 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2476 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002477 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002478 LinkageName = StringRef();
2479
Eric Christopher13c97672013-05-16 00:45:23 +00002480 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002481 if (const NamespaceDecl *NSDecl =
Eric Christopher2e3fd942013-10-17 01:31:21 +00002482 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002483 FDContext = getOrCreateNameSpace(NSDecl);
2484 else if (const RecordDecl *RDecl =
Eric Christopher2e3fd942013-10-17 01:31:21 +00002485 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2486 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002487
2488 // Collect template parameters.
2489 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2490 }
2491 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2492 Name = getObjCMethodName(OMD);
2493 Flags |= llvm::DIDescriptor::FlagPrototyped;
2494 } else {
2495 // Use llvm function name.
2496 Name = Fn->getName();
2497 Flags |= llvm::DIDescriptor::FlagPrototyped;
2498 }
2499 if (!Name.empty() && Name[0] == '\01')
2500 Name = Name.substr(1);
2501
2502 unsigned LineNo = getLineNumber(Loc);
2503 if (!HasDecl || D->isImplicit())
2504 Flags |= llvm::DIDescriptor::FlagArtificial;
2505
Eric Christopher2e3fd942013-10-17 01:31:21 +00002506 llvm::DISubprogram SP =
2507 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2508 getOrCreateFunctionType(D, FnType, Unit),
2509 Fn->hasInternalLinkage(), true /*definition*/,
2510 getLineNumber(CurLoc), Flags,
2511 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2512 getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002513 if (HasDecl)
2514 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002515
2516 // Push function on region stack.
2517 llvm::MDNode *SPN = SP;
2518 LexicalBlockStack.push_back(SPN);
2519 if (HasDecl)
2520 RegionMap[D] = llvm::WeakVH(SP);
2521}
2522
2523/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002524/// information in the source file. If the location is invalid, the
2525/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002526void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2527 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002528 // Update our current location
2529 setLocation(Loc);
2530
2531 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2532
2533 // Don't bother if things are the same as last time.
2534 SourceManager &SM = CGM.getContext().getSourceManager();
2535 if (CurLoc == PrevLoc ||
2536 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2537 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002538 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2539 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2540 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002541 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002542
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002543 // Update last state.
2544 PrevLoc = CurLoc;
2545
2546 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002547 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2548 (getLineNumber(CurLoc),
2549 getColumnNumber(CurLoc, ForceColumnInfo),
2550 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002551}
2552
2553/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2554/// the stack.
2555void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2556 llvm::DIDescriptor D =
2557 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2558 llvm::DIDescriptor() :
2559 llvm::DIDescriptor(LexicalBlockStack.back()),
2560 getOrCreateFile(CurLoc),
2561 getLineNumber(CurLoc),
2562 getColumnNumber(CurLoc));
2563 llvm::MDNode *DN = D;
2564 LexicalBlockStack.push_back(DN);
2565}
2566
2567/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2568/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002569void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2570 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002571 // Set our current location.
2572 setLocation(Loc);
2573
2574 // Create a new lexical block and push it on the stack.
2575 CreateLexicalBlock(Loc);
2576
2577 // Emit a line table change for the current location inside the new scope.
2578 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2579 getColumnNumber(Loc),
2580 LexicalBlockStack.back()));
2581}
2582
2583/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2584/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002585void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2586 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002587 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2588
2589 // Provide an entry in the line table for the end of the block.
2590 EmitLocation(Builder, Loc);
2591
2592 LexicalBlockStack.pop_back();
2593}
2594
2595/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2596void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2597 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2598 unsigned RCount = FnBeginRegionCount.back();
2599 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2600
2601 // Pop all regions for this function.
2602 while (LexicalBlockStack.size() != RCount)
2603 EmitLexicalBlockEnd(Builder, CurLoc);
2604 FnBeginRegionCount.pop_back();
2605}
2606
Eric Christopher6537f082013-05-16 00:45:12 +00002607// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002608// See BuildByRefType.
2609llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2610 uint64_t *XOffset) {
2611
2612 SmallVector<llvm::Value *, 5> EltTys;
2613 QualType FType;
2614 uint64_t FieldSize, FieldOffset;
2615 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002616
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002618 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619
2620 FieldOffset = 0;
2621 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2622 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2623 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2624 FType = CGM.getContext().IntTy;
2625 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2626 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2627
2628 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2629 if (HasCopyAndDispose) {
2630 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2631 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2632 &FieldOffset));
2633 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2634 &FieldOffset));
2635 }
2636 bool HasByrefExtendedLayout;
2637 Qualifiers::ObjCLifetime Lifetime;
2638 if (CGM.getContext().getByrefLifetime(Type,
2639 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002640 && HasByrefExtendedLayout) {
2641 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642 EltTys.push_back(CreateMemberType(Unit, FType,
2643 "__byref_variable_layout",
2644 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002645 }
Eric Christopher6537f082013-05-16 00:45:12 +00002646
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002647 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2648 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002649 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002650 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002651 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2652 CharUnits AlignedOffsetInBytes
2653 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2654 CharUnits NumPaddingBytes
2655 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002656
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002657 if (NumPaddingBytes.isPositive()) {
2658 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2659 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2660 pad, ArrayType::Normal, 0);
2661 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2662 }
2663 }
Eric Christopher6537f082013-05-16 00:45:12 +00002664
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 FType = Type;
2666 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2667 FieldSize = CGM.getContext().getTypeSize(FType);
2668 FieldAlign = CGM.getContext().toBits(Align);
2669
Eric Christopher6537f082013-05-16 00:45:12 +00002670 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002671 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2672 0, FieldSize, FieldAlign,
2673 FieldOffset, 0, FieldTy);
2674 EltTys.push_back(FieldTy);
2675 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002676
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002677 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002678
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002680
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002681 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002682 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683}
2684
2685/// EmitDeclare - Emit local variable declaration debug info.
2686void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002687 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002688 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002689 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002690 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2691
David Blaikiefc946272013-08-19 03:37:48 +00002692 bool Unwritten =
2693 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2694 cast<Decl>(VD->getDeclContext())->isImplicit());
2695 llvm::DIFile Unit;
2696 if (!Unwritten)
2697 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002698 llvm::DIType Ty;
2699 uint64_t XOffset = 0;
2700 if (VD->hasAttr<BlocksAttr>())
2701 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002702 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002703 Ty = getOrCreateType(VD->getType(), Unit);
2704
2705 // If there is no debug info for this type then do not emit debug info
2706 // for this variable.
2707 if (!Ty)
2708 return;
2709
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002710 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002711 unsigned Line = 0;
2712 unsigned Column = 0;
2713 if (!Unwritten) {
2714 Line = getLineNumber(VD->getLocation());
2715 Column = getColumnNumber(VD->getLocation());
2716 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002717 unsigned Flags = 0;
2718 if (VD->isImplicit())
2719 Flags |= llvm::DIDescriptor::FlagArtificial;
2720 // If this is the first argument and it is implicit then
2721 // give it an object pointer flag.
2722 // FIXME: There has to be a better way to do this, but for static
2723 // functions there won't be an implicit param at arg1 and
2724 // otherwise it is 'self' or 'this'.
2725 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2726 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002727 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002728 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2729 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002730 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002731
2732 llvm::MDNode *Scope = LexicalBlockStack.back();
2733
2734 StringRef Name = VD->getName();
2735 if (!Name.empty()) {
2736 if (VD->hasAttr<BlocksAttr>()) {
2737 CharUnits offset = CharUnits::fromQuantity(32);
2738 SmallVector<llvm::Value *, 9> addr;
2739 llvm::Type *Int64Ty = CGM.Int64Ty;
2740 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2741 // offset of __forwarding field
2742 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002743 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002744 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2745 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2746 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2747 // offset of x field
2748 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2749 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2750
2751 // Create the descriptor for the variable.
2752 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002753 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002754 llvm::DIDescriptor(Scope),
2755 VD->getName(), Unit, Line, Ty,
2756 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002757
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002758 // Insert an llvm.dbg.declare into the current block.
2759 llvm::Instruction *Call =
2760 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2761 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2762 return;
Adrian Prantl39232cd2013-09-18 22:18:17 +00002763 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl95d3d1a2013-09-18 22:08:57 +00002764 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikie436653b2013-01-05 05:58:35 +00002765 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2766 // If VD is an anonymous union then Storage represents value for
2767 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002768 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002769 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002770 for (RecordDecl::field_iterator I = RD->field_begin(),
2771 E = RD->field_end();
2772 I != E; ++I) {
2773 FieldDecl *Field = *I;
2774 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2775 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002776
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002777 // Ignore unnamed fields. Do not ignore unnamed records.
2778 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2779 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002780
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781 // Use VarDecl's Tag, Scope and Line number.
2782 llvm::DIVariable D =
2783 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002784 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 CGM.getLangOpts().Optimize, Flags,
2786 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002787
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002788 // Insert an llvm.dbg.declare into the current block.
2789 llvm::Instruction *Call =
2790 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2791 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2792 }
David Blaikied8180cf2013-01-05 20:03:07 +00002793 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002794 }
2795 }
David Blaikie436653b2013-01-05 05:58:35 +00002796
2797 // Create the descriptor for the variable.
2798 llvm::DIVariable D =
2799 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2800 Name, Unit, Line, Ty,
2801 CGM.getLangOpts().Optimize, Flags, ArgNo);
2802
2803 // Insert an llvm.dbg.declare into the current block.
2804 llvm::Instruction *Call =
2805 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2806 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002807}
2808
2809void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2810 llvm::Value *Storage,
2811 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002812 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002813 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2814}
2815
Adrian Prantle86fcc42013-03-29 19:20:29 +00002816/// Look up the completed type for a self pointer in the TypeCache and
2817/// create a copy of it with the ObjectPointer and Artificial flags
2818/// set. If the type is not cached, a new one is created. This should
2819/// never happen though, since creating a type for the implicit self
2820/// argument implies that we already parsed the interface definition
2821/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002822llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2823 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002824 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002825 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002826 else DEBUG(llvm::dbgs() << "No cached type for self.");
2827 return DBuilder.createObjectPointerType(Ty);
2828}
2829
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002830void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2831 llvm::Value *Storage,
2832 CGBuilderTy &Builder,
2833 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002834 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002835 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002836
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002837 if (Builder.GetInsertBlock() == 0)
2838 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002839
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002840 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002841
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002842 uint64_t XOffset = 0;
2843 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2844 llvm::DIType Ty;
2845 if (isByRef)
2846 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002847 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002848 Ty = getOrCreateType(VD->getType(), Unit);
2849
2850 // Self is passed along as an implicit non-arg variable in a
2851 // block. Mark it as the object pointer.
2852 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002853 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002854
2855 // Get location information.
2856 unsigned Line = getLineNumber(VD->getLocation());
2857 unsigned Column = getColumnNumber(VD->getLocation());
2858
2859 const llvm::DataLayout &target = CGM.getDataLayout();
2860
2861 CharUnits offset = CharUnits::fromQuantity(
2862 target.getStructLayout(blockInfo.StructureType)
2863 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2864
2865 SmallVector<llvm::Value *, 9> addr;
2866 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002867 if (isa<llvm::AllocaInst>(Storage))
2868 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002869 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2870 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2871 if (isByRef) {
2872 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2873 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2874 // offset of __forwarding field
2875 offset = CGM.getContext()
2876 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2877 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2878 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2879 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2880 // offset of x field
2881 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2882 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2883 }
2884
2885 // Create the descriptor for the variable.
2886 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002887 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002888 llvm::DIDescriptor(LexicalBlockStack.back()),
2889 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002890
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002891 // Insert an llvm.dbg.declare into the current block.
2892 llvm::Instruction *Call =
2893 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2894 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2895 LexicalBlockStack.back()));
2896}
2897
2898/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2899/// variable declaration.
2900void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2901 unsigned ArgNo,
2902 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002903 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002904 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2905}
2906
2907namespace {
2908 struct BlockLayoutChunk {
2909 uint64_t OffsetInBits;
2910 const BlockDecl::Capture *Capture;
2911 };
2912 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2913 return l.OffsetInBits < r.OffsetInBits;
2914 }
2915}
2916
2917void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002918 llvm::Value *Arg,
2919 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002920 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002921 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002922 ASTContext &C = CGM.getContext();
2923 const BlockDecl *blockDecl = block.getBlockDecl();
2924
2925 // Collect some general information about the block's location.
2926 SourceLocation loc = blockDecl->getCaretLocation();
2927 llvm::DIFile tunit = getOrCreateFile(loc);
2928 unsigned line = getLineNumber(loc);
2929 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002930
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002931 // Build the debug-info type for the block literal.
2932 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2933
2934 const llvm::StructLayout *blockLayout =
2935 CGM.getDataLayout().getStructLayout(block.StructureType);
2936
2937 SmallVector<llvm::Value*, 16> fields;
2938 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2939 blockLayout->getElementOffsetInBits(0),
2940 tunit, tunit));
2941 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2942 blockLayout->getElementOffsetInBits(1),
2943 tunit, tunit));
2944 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2945 blockLayout->getElementOffsetInBits(2),
2946 tunit, tunit));
2947 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2948 blockLayout->getElementOffsetInBits(3),
2949 tunit, tunit));
2950 fields.push_back(createFieldType("__descriptor",
2951 C.getPointerType(block.NeedsCopyDispose ?
2952 C.getBlockDescriptorExtendedType() :
2953 C.getBlockDescriptorType()),
2954 0, loc, AS_public,
2955 blockLayout->getElementOffsetInBits(4),
2956 tunit, tunit));
2957
2958 // We want to sort the captures by offset, not because DWARF
2959 // requires this, but because we're paranoid about debuggers.
2960 SmallVector<BlockLayoutChunk, 8> chunks;
2961
2962 // 'this' capture.
2963 if (blockDecl->capturesCXXThis()) {
2964 BlockLayoutChunk chunk;
2965 chunk.OffsetInBits =
2966 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2967 chunk.Capture = 0;
2968 chunks.push_back(chunk);
2969 }
2970
2971 // Variable captures.
2972 for (BlockDecl::capture_const_iterator
2973 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2974 i != e; ++i) {
2975 const BlockDecl::Capture &capture = *i;
2976 const VarDecl *variable = capture.getVariable();
2977 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2978
2979 // Ignore constant captures.
2980 if (captureInfo.isConstant())
2981 continue;
2982
2983 BlockLayoutChunk chunk;
2984 chunk.OffsetInBits =
2985 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2986 chunk.Capture = &capture;
2987 chunks.push_back(chunk);
2988 }
2989
2990 // Sort by offset.
2991 llvm::array_pod_sort(chunks.begin(), chunks.end());
2992
2993 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2994 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2995 uint64_t offsetInBits = i->OffsetInBits;
2996 const BlockDecl::Capture *capture = i->Capture;
2997
2998 // If we have a null capture, this must be the C++ 'this' capture.
2999 if (!capture) {
3000 const CXXMethodDecl *method =
3001 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3002 QualType type = method->getThisType(C);
3003
3004 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3005 offsetInBits, tunit, tunit));
3006 continue;
3007 }
3008
3009 const VarDecl *variable = capture->getVariable();
3010 StringRef name = variable->getName();
3011
3012 llvm::DIType fieldType;
3013 if (capture->isByRef()) {
3014 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3015
3016 // FIXME: this creates a second copy of this type!
3017 uint64_t xoffset;
3018 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3019 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3020 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3021 ptrInfo.first, ptrInfo.second,
3022 offsetInBits, 0, fieldType);
3023 } else {
3024 fieldType = createFieldType(name, variable->getType(), 0,
3025 loc, AS_public, offsetInBits, tunit, tunit);
3026 }
3027 fields.push_back(fieldType);
3028 }
3029
3030 SmallString<36> typeName;
3031 llvm::raw_svector_ostream(typeName)
3032 << "__block_literal_" << CGM.getUniqueBlockCount();
3033
3034 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3035
3036 llvm::DIType type =
3037 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3038 CGM.getContext().toBits(block.BlockSize),
3039 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003040 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003041 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3042
3043 // Get overall information about the block.
3044 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3045 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003046
3047 // Create the descriptor for the parameter.
3048 llvm::DIVariable debugVar =
3049 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003050 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003051 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003052 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003053 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3054
Adrian Prantlbea407c2013-03-14 21:52:59 +00003055 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003056 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003057 llvm::Instruction *DbgVal =
3058 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003059 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003060 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3061 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003062
Adrian Prantlbea407c2013-03-14 21:52:59 +00003063 // Insert an llvm.dbg.declare into the current block.
3064 llvm::Instruction *DbgDecl =
3065 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3066 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003067}
3068
David Blaikie5434fc22013-08-20 01:28:15 +00003069/// If D is an out-of-class definition of a static data member of a class, find
3070/// its corresponding in-class declaration.
3071llvm::DIDerivedType
3072CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3073 if (!D->isStaticDataMember())
3074 return llvm::DIDerivedType();
3075 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3076 StaticDataMemberCache.find(D->getCanonicalDecl());
3077 if (MI != StaticDataMemberCache.end()) {
3078 assert(MI->second && "Static data member declaration should still exist");
3079 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003080 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003081
3082 // If the member wasn't found in the cache, lazily construct and add it to the
3083 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003084 llvm::DICompositeType Ctxt(
3085 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3086 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3087 Ctxt.addMember(T);
3088 return T;
3089}
3090
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003091/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003092void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003093 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003094 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003095 // Create global variable debug descriptor.
3096 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3097 unsigned LineNo = getLineNumber(D->getLocation());
3098
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003099 setLocation(D->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003100
3101 QualType T = D->getType();
3102 if (T->isIncompleteArrayType()) {
3103
3104 // CodeGen turns int[] into int[1] so we'll do the same here.
3105 llvm::APInt ConstVal(32, 1);
3106 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3107
3108 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3109 ArrayType::Normal, 0);
3110 }
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003111 StringRef DeclName = D->getName();
3112 StringRef LinkageName;
3113 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3114 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3115 LinkageName = Var->getName();
3116 if (LinkageName == DeclName)
3117 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003118 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003119 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003120 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3121 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003122 Var->hasInternalLinkage(), Var,
David Blaikie5434fc22013-08-20 01:28:15 +00003123 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003124 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003125}
3126
3127/// EmitGlobalVariable - Emit information about an objective-c interface.
3128void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3129 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003130 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003131 // Create global variable debug descriptor.
3132 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3133 unsigned LineNo = getLineNumber(ID->getLocation());
3134
3135 StringRef Name = ID->getName();
3136
3137 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3138 if (T->isIncompleteArrayType()) {
3139
3140 // CodeGen turns int[] into int[1] so we'll do the same here.
3141 llvm::APInt ConstVal(32, 1);
3142 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3143
3144 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3145 ArrayType::Normal, 0);
3146 }
3147
3148 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3149 getOrCreateType(T, Unit),
3150 Var->hasInternalLinkage(), Var);
3151}
3152
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003153/// EmitGlobalVariable - Emit global variable's debug info.
3154void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3155 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003156 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003157 // Create the descriptor for the variable.
3158 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3159 StringRef Name = VD->getName();
3160 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3161 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3162 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3163 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3164 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3165 }
3166 // Do not use DIGlobalVariable for enums.
3167 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3168 return;
3169 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3170 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3171 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3172 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikie9faebd22013-05-20 04:58:53 +00003173}
3174
3175llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3176 if (!LexicalBlockStack.empty())
3177 return llvm::DIScope(LexicalBlockStack.back());
3178 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003179}
3180
David Blaikie957dac52013-04-22 06:13:21 +00003181void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003182 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3183 return;
David Blaikie957dac52013-04-22 06:13:21 +00003184 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003185 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3186 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003187 getLineNumber(UD.getLocation()));
3188}
3189
David Blaikie9faebd22013-05-20 04:58:53 +00003190void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3191 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3192 return;
3193 assert(UD.shadow_size() &&
3194 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3195 // Emitting one decl is sufficient - debuggers can detect that this is an
3196 // overloaded name & provide lookup for all the overloads.
3197 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003198 if (llvm::DIDescriptor Target =
3199 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003200 DBuilder.createImportedDeclaration(
3201 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3202 getLineNumber(USD.getLocation()));
3203}
3204
David Blaikiefc46ebc2013-05-20 22:50:41 +00003205llvm::DIImportedEntity
3206CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3207 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3208 return llvm::DIImportedEntity(0);
3209 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3210 if (VH)
3211 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3212 llvm::DIImportedEntity R(0);
3213 if (const NamespaceAliasDecl *Underlying =
3214 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3215 // This could cache & dedup here rather than relying on metadata deduping.
3216 R = DBuilder.createImportedModule(
3217 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3218 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3219 NA.getName());
3220 else
3221 R = DBuilder.createImportedModule(
3222 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3223 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3224 getLineNumber(NA.getLocation()), NA.getName());
3225 VH = R;
3226 return R;
3227}
3228
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003229/// getOrCreateNamesSpace - Return namespace descriptor for the given
3230/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003231llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003232CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003233 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003234 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003235 NameSpaceCache.find(NSDecl);
3236 if (I != NameSpaceCache.end())
3237 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003238
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003239 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3240 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003241 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003242 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3243 llvm::DINameSpace NS =
3244 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3245 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3246 return NS;
3247}
3248
3249void CGDebugInfo::finalize() {
3250 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3251 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3252 llvm::DIType Ty, RepTy;
3253 // Verify that the debug info still exists.
3254 if (llvm::Value *V = VI->second)
3255 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003256
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003257 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3258 TypeCache.find(VI->first);
3259 if (it != TypeCache.end()) {
3260 // Verify that the debug info still exists.
3261 if (llvm::Value *V = it->second)
3262 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3263 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003264
Eric Christopherb2d13922013-07-18 00:52:50 +00003265 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003266 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003267 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003268
3269 // We keep our own list of retained types, because we need to look
3270 // up the final type in the type cache.
3271 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3272 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Ren18760452013-08-29 20:48:48 +00003273 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003274
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003275 DBuilder.finalize();
3276}