blob: beb62362e75f4b3d0f4e2a25dc83072abef1632c [file] [log] [blame]
Guy Benyei11169dd2012-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 Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-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 Carruthffd55512013-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 Benyei11169dd2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher75e17682013-05-16 00:45:23 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()),
Guy Benyei11169dd2012-12-18 14:30:41 +000046 BlockLiteralGenericSet(false) {
47 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
55void CGDebugInfo::setLocation(SourceLocation Loc) {
56 // If the new location isn't valid return.
57 if (!Loc.isValid()) return;
58
59 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
60
61 // If we've changed files in the middle of a lexical scope go ahead
62 // and create a new lexical scope with file node if it's different
63 // from the one in the scope.
64 if (LexicalBlockStack.empty()) return;
65
66 SourceManager &SM = CGM.getContext().getSourceManager();
67 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
68 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
69
70 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
71 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 return;
73
74 llvm::MDNode *LB = LexicalBlockStack.back();
75 llvm::DIScope Scope = llvm::DIScope(LB);
76 if (Scope.isLexicalBlockFile()) {
77 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
78 llvm::DIDescriptor D
79 = DBuilder.createLexicalBlockFile(LBF.getScope(),
80 getOrCreateFile(CurLoc));
81 llvm::MDNode *N = D;
82 LexicalBlockStack.pop_back();
83 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +000084 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000085 llvm::DIDescriptor D
86 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
87 llvm::MDNode *N = D;
88 LexicalBlockStack.pop_back();
89 LexicalBlockStack.push_back(N);
90 }
91}
92
93/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +000094llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +000095 if (!Context)
96 return TheCU;
97
98 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
99 I = RegionMap.find(Context);
100 if (I != RegionMap.end()) {
101 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000103 }
104
105 // Check namespace.
106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000107 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000108
David Blaikiebfa52742013-04-19 06:56:38 +0000109 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
110 if (!RDecl->isDependentType())
111 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000112 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000113 return TheCU;
114}
115
116/// getFunctionName - Get function name for the given FunctionDecl. If the
117/// name is constructred on demand (e.g. C++ destructor) then the name
118/// is stored on the side.
119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120 assert (FD && "Invalid FunctionDecl!");
121 IdentifierInfo *FII = FD->getIdentifier();
122 FunctionTemplateSpecializationInfo *Info
123 = FD->getTemplateSpecializationInfo();
124 if (!Info && FII)
125 return FII->getName();
126
127 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000128 SmallString<128> NS;
129 llvm::raw_svector_ostream OS(NS);
130 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000131
132 // Add any template specialization args.
133 if (Info) {
134 const TemplateArgumentList *TArgs = Info->TemplateArguments;
135 const TemplateArgument *Args = TArgs->data();
136 unsigned NumArgs = TArgs->size();
137 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000140 }
141
142 // Copy this name on the side and use its reference.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000143 OS.flush();
144 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
145 memcpy(StrPtr, NS.data(), NS.size());
146 return StringRef(StrPtr, NS.size());
Guy Benyei11169dd2012-12-18 14:30:41 +0000147}
148
149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
150 SmallString<256> MethodName;
151 llvm::raw_svector_ostream OS(MethodName);
152 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
153 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000154 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000155 dyn_cast<const ObjCImplementationDecl>(DC)) {
156 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000157 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 dyn_cast<const ObjCInterfaceDecl>(DC)) {
159 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000160 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000161 dyn_cast<const ObjCCategoryImplDecl>(DC)){
162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000164 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000165 // We can extract the type of the class from the self pointer.
166 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
167 QualType ClassTy =
168 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
169 ClassTy.print(OS, PrintingPolicy(LangOptions()));
170 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000171 }
172 OS << ' ' << OMD->getSelector().getAsString() << ']';
173
174 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
175 memcpy(StrPtr, MethodName.begin(), OS.tell());
176 return StringRef(StrPtr, OS.tell());
177}
178
179/// getSelectorName - Return selector name. This is used for debugging
180/// info.
181StringRef CGDebugInfo::getSelectorName(Selector S) {
182 const std::string &SName = S.getAsString();
183 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
184 memcpy(StrPtr, SName.data(), SName.size());
185 return StringRef(StrPtr, SName.size());
186}
187
188/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000189StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000190CGDebugInfo::getClassName(const RecordDecl *RD) {
191 const ClassTemplateSpecializationDecl *Spec
192 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
193 if (!Spec)
194 return RD->getName();
195
196 const TemplateArgument *Args;
197 unsigned NumArgs;
198 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
199 const TemplateSpecializationType *TST =
200 cast<TemplateSpecializationType>(TAW->getType());
201 Args = TST->getArgs();
202 NumArgs = TST->getNumArgs();
203 } else {
204 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
205 Args = TemplateArgs.data();
206 NumArgs = TemplateArgs.size();
207 }
208 StringRef Name = RD->getIdentifier()->getName();
209 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000210 SmallString<128> TemplateArgList;
211 {
212 llvm::raw_svector_ostream OS(TemplateArgList);
213 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
214 Policy);
215 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000216
217 // Copy this name on the side and use its reference.
218 size_t Length = Name.size() + TemplateArgList.size();
219 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
220 memcpy(StrPtr, Name.data(), Name.size());
221 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
222 return StringRef(StrPtr, Length);
223}
224
225/// getOrCreateFile - Get the file debug info descriptor for the input location.
226llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
227 if (!Loc.isValid())
228 // If Location is not valid then use main input file.
229 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230
231 SourceManager &SM = CGM.getContext().getSourceManager();
232 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
233
234 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
235 // If the location is not valid then use main input file.
236 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
237
238 // Cache the results.
239 const char *fname = PLoc.getFilename();
240 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
241 DIFileCache.find(fname);
242
243 if (it != DIFileCache.end()) {
244 // Verify that the information still exists.
245 if (llvm::Value *V = it->second)
246 return llvm::DIFile(cast<llvm::MDNode>(V));
247 }
248
249 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
250
251 DIFileCache[fname] = F;
252 return F;
253}
254
255/// getOrCreateMainFile - Get the file info for main compile unit.
256llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
257 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
258}
259
260/// getLineNumber - Get line number for the location. If location is invalid
261/// then use current location.
262unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
263 if (Loc.isInvalid() && CurLoc.isInvalid())
264 return 0;
265 SourceManager &SM = CGM.getContext().getSourceManager();
266 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
267 return PLoc.isValid()? PLoc.getLine() : 0;
268}
269
270/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000272 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000273 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000274 return 0;
275
276 // If the location is invalid then use the current column.
277 if (Loc.isInvalid() && CurLoc.isInvalid())
278 return 0;
279 SourceManager &SM = CGM.getContext().getSourceManager();
280 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
281 return PLoc.isValid()? PLoc.getColumn() : 0;
282}
283
284StringRef CGDebugInfo::getCurrentDirname() {
285 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
286 return CGM.getCodeGenOpts().DebugCompilationDir;
287
288 if (!CWDName.empty())
289 return CWDName;
290 SmallString<256> CWD;
291 llvm::sys::fs::current_path(CWD);
292 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
293 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
294 return CWDName = StringRef(CompDirnamePtr, CWD.size());
295}
296
297/// CreateCompileUnit - Create new compile unit.
298void CGDebugInfo::CreateCompileUnit() {
299
300 // Get absolute path name.
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
303 if (MainFileName.empty())
304 MainFileName = "<unknown>";
305
306 // The main file name provided via the "-main-file-name" option contains just
307 // the file name itself with no path information. This file name may have had
308 // a relative path, so we look into the actual file entry for the main
309 // file to determine the real absolute path for the file.
310 std::string MainFileDir;
311 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
312 MainFileDir = MainFile->getDir()->getName();
313 if (MainFileDir != ".")
314 MainFileName = MainFileDir + "/" + MainFileName;
315 }
316
317 // Save filename string.
318 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
319 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
320 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherf1545832013-02-22 23:50:16 +0000321
322 // Save split dwarf file string.
323 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
324 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
325 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
326 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopherb2a008c2013-05-16 00:45:12 +0000327
Guy Benyei11169dd2012-12-18 14:30:41 +0000328 unsigned LangTag;
329 const LangOptions &LO = CGM.getLangOpts();
330 if (LO.CPlusPlus) {
331 if (LO.ObjC1)
332 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
333 else
334 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
335 } else if (LO.ObjC1) {
336 LangTag = llvm::dwarf::DW_LANG_ObjC;
337 } else if (LO.C99) {
338 LangTag = llvm::dwarf::DW_LANG_C99;
339 } else {
340 LangTag = llvm::dwarf::DW_LANG_C89;
341 }
342
343 std::string Producer = getClangFullVersion();
344
345 // Figure out which version of the ObjC runtime we have.
346 unsigned RuntimeVers = 0;
347 if (LO.ObjC1)
348 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
349
350 // Create new compile unit.
Eric Christopherc0c5d462013-02-21 22:35:08 +0000351 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
352 Producer, LO.Optimize,
Eric Christopherf1545832013-02-22 23:50:16 +0000353 CGM.getCodeGenOpts().DwarfDebugFlags,
354 RuntimeVers, SplitDwarfFilename);
Guy Benyei11169dd2012-12-18 14:30:41 +0000355 // FIXME - Eliminate TheCU.
356 TheCU = llvm::DICompileUnit(DBuilder.getCU());
357}
358
359/// CreateType - Get the Basic type from the cache or create a new
360/// one if necessary.
361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
362 unsigned Encoding = 0;
363 StringRef BTName;
364 switch (BT->getKind()) {
365#define BUILTIN_TYPE(Id, SingletonId)
366#define PLACEHOLDER_TYPE(Id, SingletonId) \
367 case BuiltinType::Id:
368#include "clang/AST/BuiltinTypes.def"
369 case BuiltinType::Dependent:
370 llvm_unreachable("Unexpected builtin type");
371 case BuiltinType::NullPtr:
372 return DBuilder.
373 createNullPtrType(BT->getName(CGM.getLangOpts()));
374 case BuiltinType::Void:
375 return llvm::DIType();
376 case BuiltinType::ObjCClass:
377 if (ClassTy.Verify())
378 return ClassTy;
379 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
380 "objc_class", TheCU,
381 getOrCreateMainFile(), 0);
382 return ClassTy;
383 case BuiltinType::ObjCId: {
384 // typedef struct objc_class *Class;
385 // typedef struct objc_object {
386 // Class isa;
387 // } *id;
388
389 if (ObjTy.Verify())
390 return ObjTy;
391
392 if (!ClassTy.Verify())
393 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
394 "objc_class", TheCU,
395 getOrCreateMainFile(), 0);
396
397 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000398
Guy Benyei11169dd2012-12-18 14:30:41 +0000399 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
400
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000401 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000402 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
403 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000404
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000405 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
406 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 return ObjTy;
408 }
409 case BuiltinType::ObjCSel: {
410 if (SelTy.Verify())
411 return SelTy;
412 SelTy =
413 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
414 "objc_selector", TheCU, getOrCreateMainFile(),
415 0);
416 return SelTy;
417 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000418
419 case BuiltinType::OCLImage1d:
420 return getOrCreateStructPtrType("opencl_image1d_t",
421 OCLImage1dDITy);
422 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000423 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000424 OCLImage1dArrayDITy);
425 case BuiltinType::OCLImage1dBuffer:
426 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
427 OCLImage1dBufferDITy);
428 case BuiltinType::OCLImage2d:
429 return getOrCreateStructPtrType("opencl_image2d_t",
430 OCLImage2dDITy);
431 case BuiltinType::OCLImage2dArray:
432 return getOrCreateStructPtrType("opencl_image2d_array_t",
433 OCLImage2dArrayDITy);
434 case BuiltinType::OCLImage3d:
435 return getOrCreateStructPtrType("opencl_image3d_t",
436 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000437 case BuiltinType::OCLSampler:
438 return DBuilder.createBasicType("opencl_sampler_t",
439 CGM.getContext().getTypeSize(BT),
440 CGM.getContext().getTypeAlign(BT),
441 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000442 case BuiltinType::OCLEvent:
443 return getOrCreateStructPtrType("opencl_event_t",
444 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000445
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 case BuiltinType::UChar:
447 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
448 case BuiltinType::Char_S:
449 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
450 case BuiltinType::Char16:
451 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
452 case BuiltinType::UShort:
453 case BuiltinType::UInt:
454 case BuiltinType::UInt128:
455 case BuiltinType::ULong:
456 case BuiltinType::WChar_U:
457 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
458 case BuiltinType::Short:
459 case BuiltinType::Int:
460 case BuiltinType::Int128:
461 case BuiltinType::Long:
462 case BuiltinType::WChar_S:
463 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
464 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
465 case BuiltinType::Half:
466 case BuiltinType::Float:
467 case BuiltinType::LongDouble:
468 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
469 }
470
471 switch (BT->getKind()) {
472 case BuiltinType::Long: BTName = "long int"; break;
473 case BuiltinType::LongLong: BTName = "long long int"; break;
474 case BuiltinType::ULong: BTName = "long unsigned int"; break;
475 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
476 default:
477 BTName = BT->getName(CGM.getLangOpts());
478 break;
479 }
480 // Bit size, align and offset of the type.
481 uint64_t Size = CGM.getContext().getTypeSize(BT);
482 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000483 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000484 DBuilder.createBasicType(BTName, Size, Align, Encoding);
485 return DbgTy;
486}
487
488llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
489 // Bit size, align and offset of the type.
490 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
491 if (Ty->isComplexIntegerType())
492 Encoding = llvm::dwarf::DW_ATE_lo_user;
493
494 uint64_t Size = CGM.getContext().getTypeSize(Ty);
495 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000496 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000497 DBuilder.createBasicType("complex", Size, Align, Encoding);
498
499 return DbgTy;
500}
501
502/// CreateCVRType - Get the qualified type from the cache or create
503/// a new one if necessary.
David Blaikiee36464c2013-06-05 05:32:23 +0000504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit, bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000505 QualifierCollector Qc;
506 const Type *T = Qc.strip(Ty);
507
508 // Ignore these qualifiers for now.
509 Qc.removeObjCGCAttr();
510 Qc.removeAddressSpace();
511 Qc.removeObjCLifetime();
512
513 // We will create one Derived type for one qualifier and recurse to handle any
514 // additional ones.
515 unsigned Tag;
516 if (Qc.hasConst()) {
517 Tag = llvm::dwarf::DW_TAG_const_type;
518 Qc.removeConst();
519 } else if (Qc.hasVolatile()) {
520 Tag = llvm::dwarf::DW_TAG_volatile_type;
521 Qc.removeVolatile();
522 } else if (Qc.hasRestrict()) {
523 Tag = llvm::dwarf::DW_TAG_restrict_type;
524 Qc.removeRestrict();
525 } else {
526 assert(Qc.empty() && "Unknown type qualifier for debug info");
527 return getOrCreateType(QualType(T, 0), Unit);
528 }
529
David Blaikiee36464c2013-06-05 05:32:23 +0000530 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +0000531
532 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
533 // CVR derived types.
534 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000535
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 return DbgTy;
537}
538
539llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
540 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000541
542 // The frontend treats 'id' as a typedef to an ObjCObjectType,
543 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
544 // debug info, we want to emit 'id' in both cases.
545 if (Ty->isObjCQualifiedIdType())
546 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
547
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000549 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000550 Ty->getPointeeType(), Unit);
551 return DbgTy;
552}
553
554llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
555 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000556 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 Ty->getPointeeType(), Unit);
558}
559
560// Creates a forward declaration for a RecordDecl in the given context.
561llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
562 llvm::DIDescriptor Ctx) {
563 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
564 unsigned Line = getLineNumber(RD->getLocation());
565 StringRef RDName = getClassName(RD);
566
567 unsigned Tag = 0;
568 if (RD->isStruct() || RD->isInterface())
569 Tag = llvm::dwarf::DW_TAG_structure_type;
570 else if (RD->isUnion())
571 Tag = llvm::dwarf::DW_TAG_union_type;
572 else {
573 assert(RD->isClass());
574 Tag = llvm::dwarf::DW_TAG_class_type;
575 }
576
577 // Create the type.
578 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
579}
580
581// Walk up the context chain and create forward decls for record decls,
582// and normal descriptors for namespaces.
583llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
584 if (!Context)
585 return TheCU;
586
587 // See if we already have the parent.
588 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
589 I = RegionMap.find(Context);
590 if (I != RegionMap.end()) {
591 llvm::Value *V = I->second;
592 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
593 }
Eric Christopherb2a008c2013-05-16 00:45:12 +0000594
Guy Benyei11169dd2012-12-18 14:30:41 +0000595 // Check namespace.
596 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
597 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
598
599 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
600 if (!RD->isDependentType()) {
Eric Christopher0fdcb312013-05-16 00:52:20 +0000601 llvm::DIType Ty =
602 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
603 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 return llvm::DIDescriptor(Ty);
605 }
606 }
607 return TheCU;
608}
609
David Blaikie4583bea2013-05-24 21:33:22 +0000610/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei11169dd2012-12-18 14:30:41 +0000611/// then emit record's fwd if debug info size reduction is enabled.
David Blaikie4583bea2013-05-24 21:33:22 +0000612llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
613 llvm::DIFile Unit) {
David Blaikiebd483762013-05-20 04:58:53 +0000614 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000615 return getOrCreateType(PointeeTy, Unit);
David Blaikiee36464c2013-06-05 05:32:23 +0000616 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei11169dd2012-12-18 14:30:41 +0000617}
618
619llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000620 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000621 QualType PointeeTy,
622 llvm::DIFile Unit) {
623 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
624 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie4583bea2013-05-24 21:33:22 +0000625 return DBuilder.createReferenceType(
626 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000627
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 // Bit size, align and offset of the type.
629 // Size is always the size of a pointer. We can't use getTypeSize here
630 // because that does not return the correct value for references.
631 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000632 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
634
David Blaikie4583bea2013-05-24 21:33:22 +0000635 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 Size, Align);
637}
638
Eric Christopher0fdcb312013-05-16 00:52:20 +0000639llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
640 llvm::DIType &Cache) {
David Blaikiefefc7f72013-05-21 17:58:54 +0000641 if (Cache.Verify())
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000642 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000643 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
644 TheCU, getOrCreateMainFile(), 0);
645 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
646 Cache = DBuilder.createPointerType(Cache, Size);
647 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000648}
649
Guy Benyei11169dd2012-12-18 14:30:41 +0000650llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
651 llvm::DIFile Unit) {
652 if (BlockLiteralGenericSet)
653 return BlockLiteralGeneric;
654
655 SmallVector<llvm::Value *, 8> EltTys;
656 llvm::DIType FieldTy;
657 QualType FType;
658 uint64_t FieldSize, FieldOffset;
659 unsigned FieldAlign;
660 llvm::DIArray Elements;
661 llvm::DIType EltTy, DescTy;
662
663 FieldOffset = 0;
664 FType = CGM.getContext().UnsignedLongTy;
665 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
666 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
667
668 Elements = DBuilder.getOrCreateArray(EltTys);
669 EltTys.clear();
670
671 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
672 unsigned LineNo = getLineNumber(CurLoc);
673
674 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
675 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000676 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000677
678 // Bit size, align and offset of the type.
679 uint64_t Size = CGM.getContext().getTypeSize(Ty);
680
681 DescTy = DBuilder.createPointerType(EltTy, Size);
682
683 FieldOffset = 0;
684 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
685 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
686 FType = CGM.getContext().IntTy;
687 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
688 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
689 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
690 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
691
692 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
693 FieldTy = DescTy;
694 FieldSize = CGM.getContext().getTypeSize(Ty);
695 FieldAlign = CGM.getContext().getTypeAlign(Ty);
696 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
697 LineNo, FieldSize, FieldAlign,
698 FieldOffset, 0, FieldTy);
699 EltTys.push_back(FieldTy);
700
701 FieldOffset += FieldSize;
702 Elements = DBuilder.getOrCreateArray(EltTys);
703
704 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
705 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000706 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000707
708 BlockLiteralGenericSet = true;
709 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
710 return BlockLiteralGeneric;
711}
712
David Blaikiee36464c2013-06-05 05:32:23 +0000713llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
714 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000715 // Typedefs are derived from some other type. If we have a typedef of a
716 // typedef, make sure to emit the whole chain.
David Blaikie4583bea2013-05-24 21:33:22 +0000717 llvm::DIType Src =
David Blaikiee36464c2013-06-05 05:32:23 +0000718 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +0000719 if (!Src.Verify())
720 return llvm::DIType();
721 // We don't set size information, but do specify where the typedef was
722 // declared.
723 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
724 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000725
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 llvm::DIDescriptor TypedefContext =
727 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000728
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 return
730 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
731}
732
733llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
734 llvm::DIFile Unit) {
735 SmallVector<llvm::Value *, 16> EltTys;
736
737 // Add the result type at least.
738 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
739
740 // Set up remainder of arguments if there is a prototype.
741 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
742 if (isa<FunctionNoProtoType>(Ty))
743 EltTys.push_back(DBuilder.createUnspecifiedParameter());
744 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
745 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
746 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
747 }
748
749 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
750 return DBuilder.createSubroutineType(Unit, EltTypeArray);
751}
752
753
Guy Benyei11169dd2012-12-18 14:30:41 +0000754llvm::DIType CGDebugInfo::createFieldType(StringRef name,
755 QualType type,
756 uint64_t sizeInBitsOverride,
757 SourceLocation loc,
758 AccessSpecifier AS,
759 uint64_t offsetInBits,
760 llvm::DIFile tunit,
761 llvm::DIDescriptor scope) {
762 llvm::DIType debugType = getOrCreateType(type, tunit);
763
764 // Get the location for the field.
765 llvm::DIFile file = getOrCreateFile(loc);
766 unsigned line = getLineNumber(loc);
767
768 uint64_t sizeInBits = 0;
769 unsigned alignInBits = 0;
770 if (!type->isIncompleteArrayType()) {
771 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
772
773 if (sizeInBitsOverride)
774 sizeInBits = sizeInBitsOverride;
775 }
776
777 unsigned flags = 0;
778 if (AS == clang::AS_private)
779 flags |= llvm::DIDescriptor::FlagPrivate;
780 else if (AS == clang::AS_protected)
781 flags |= llvm::DIDescriptor::FlagProtected;
782
783 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
784 alignInBits, offsetInBits, flags, debugType);
785}
786
Eric Christopher91a31902013-01-16 01:22:32 +0000787/// CollectRecordLambdaFields - Helper for CollectRecordFields.
788void CGDebugInfo::
789CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
790 SmallVectorImpl<llvm::Value *> &elements,
791 llvm::DIType RecordTy) {
792 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
793 // has the name and the location of the variable so we should iterate over
794 // both concurrently.
795 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
796 RecordDecl::field_iterator Field = CXXDecl->field_begin();
797 unsigned fieldno = 0;
798 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
799 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
800 const LambdaExpr::Capture C = *I;
801 if (C.capturesVariable()) {
802 VarDecl *V = C.getCapturedVar();
803 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
804 StringRef VName = V->getName();
805 uint64_t SizeInBitsOverride = 0;
806 if (Field->isBitField()) {
807 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
808 assert(SizeInBitsOverride && "found named 0-width bitfield");
809 }
810 llvm::DIType fieldType
811 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
812 C.getLocation(), Field->getAccess(),
813 layout.getFieldOffset(fieldno), VUnit, RecordTy);
814 elements.push_back(fieldType);
815 } else {
816 // TODO: Need to handle 'this' in some way by probably renaming the
817 // this of the lambda class and having a field member of 'this' or
818 // by using AT_object_pointer for the function and having that be
819 // used as 'this' for semantic references.
820 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
821 FieldDecl *f = *Field;
822 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
823 QualType type = f->getType();
824 llvm::DIType fieldType
825 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
826 layout.getFieldOffset(fieldno), VUnit, RecordTy);
827
828 elements.push_back(fieldType);
829 }
830 }
831}
832
833/// CollectRecordStaticField - Helper for CollectRecordFields.
834void CGDebugInfo::
835CollectRecordStaticField(const VarDecl *Var,
836 SmallVectorImpl<llvm::Value *> &elements,
837 llvm::DIType RecordTy) {
838 // Create the descriptor for the static variable, with or without
839 // constant initializers.
840 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
841 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
842
843 // Do not describe enums as static members.
844 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
845 return;
846
847 unsigned LineNumber = getLineNumber(Var->getLocation());
848 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000849 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000850 if (Var->getInit()) {
851 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000852 if (Value) {
853 if (Value->isInt())
854 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
855 if (Value->isFloat())
856 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
857 }
Eric Christopher91a31902013-01-16 01:22:32 +0000858 }
859
860 unsigned Flags = 0;
861 AccessSpecifier Access = Var->getAccess();
862 if (Access == clang::AS_private)
863 Flags |= llvm::DIDescriptor::FlagPrivate;
864 else if (Access == clang::AS_protected)
865 Flags |= llvm::DIDescriptor::FlagProtected;
866
867 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikied42917f2013-01-20 01:19:17 +0000868 LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000869 elements.push_back(GV);
870 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
871}
872
873/// CollectRecordNormalField - Helper for CollectRecordFields.
874void CGDebugInfo::
875CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
876 llvm::DIFile tunit,
877 SmallVectorImpl<llvm::Value *> &elements,
878 llvm::DIType RecordTy) {
879 StringRef name = field->getName();
880 QualType type = field->getType();
881
882 // Ignore unnamed fields unless they're anonymous structs/unions.
883 if (name.empty() && !type->isRecordType())
884 return;
885
886 uint64_t SizeInBitsOverride = 0;
887 if (field->isBitField()) {
888 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
889 assert(SizeInBitsOverride && "found named 0-width bitfield");
890 }
891
892 llvm::DIType fieldType
893 = createFieldType(name, type, SizeInBitsOverride,
894 field->getLocation(), field->getAccess(),
895 OffsetInBits, tunit, RecordTy);
896
897 elements.push_back(fieldType);
898}
899
Guy Benyei11169dd2012-12-18 14:30:41 +0000900/// CollectRecordFields - A helper function to collect debug info for
901/// record fields. This is used while creating debug info entry for a Record.
902void CGDebugInfo::
903CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
904 SmallVectorImpl<llvm::Value *> &elements,
905 llvm::DIType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000906 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
907
Eric Christopher91a31902013-01-16 01:22:32 +0000908 if (CXXDecl && CXXDecl->isLambda())
909 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
910 else {
911 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000912
Eric Christopher91a31902013-01-16 01:22:32 +0000913 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000914 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000915
916 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 bool IsMsStruct = record->isMsStruct(CGM.getContext());
918 const FieldDecl *LastFD = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000919
Eric Christopher91a31902013-01-16 01:22:32 +0000920 // Static and non-static members should appear in the same order as
921 // the corresponding declarations in the source program.
922 for (RecordDecl::decl_iterator I = record->decls_begin(),
923 E = record->decls_end(); I != E; ++I)
924 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
925 CollectRecordStaticField(V, elements, RecordTy);
926 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
927 if (IsMsStruct) {
928 // Zero-length bitfields following non-bitfield members are
929 // completely ignored; we don't even count them.
930 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
931 continue;
932 LastFD = field;
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 }
Eric Christopher91a31902013-01-16 01:22:32 +0000934 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
935 tunit, elements, RecordTy);
936
937 // Bump field number for next field.
938 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 }
941}
942
943/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
944/// function type is not updated to include implicit "this" pointer. Use this
945/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000946llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000947CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
948 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000949 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000950 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000951 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000952 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
953 Func, Unit);
954}
David Blaikie2aaf0652013-01-07 22:24:59 +0000955
David Blaikie469f0792013-05-22 23:22:42 +0000956llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000957 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000959 llvm::DIArray Args = llvm::DICompositeType(
960 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 assert (Args.getNumElements() && "Invalid number of arguments!");
962
963 SmallVector<llvm::Value *, 16> Elts;
964
965 // First element is always return type. For 'void' functions it is NULL.
966 Elts.push_back(Args.getElement(0));
967
David Blaikie2aaf0652013-01-07 22:24:59 +0000968 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000969 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000970 if (isa<ClassTemplateSpecializationDecl>(RD)) {
971 // Create pointer type directly in this case.
972 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
973 QualType PointeeTy = ThisPtrTy->getPointeeType();
974 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000975 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000976 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
977 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000978 llvm::DIType ThisPtrType =
979 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000980 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
981 // TODO: This and the artificial type below are misleading, the
982 // types aren't artificial the argument is, but the current
983 // metadata doesn't represent that.
984 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
985 Elts.push_back(ThisPtrType);
986 } else {
987 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
988 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
989 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
990 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +0000991 }
992
993 // Copy rest of the arguments.
994 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
995 Elts.push_back(Args.getElement(i));
996
997 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
998
999 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1000}
1001
Eric Christopherb2a008c2013-05-16 00:45:12 +00001002/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001003/// inside a function.
1004static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1005 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1006 return isFunctionLocalClass(NRD);
1007 if (isa<FunctionDecl>(RD->getDeclContext()))
1008 return true;
1009 return false;
1010}
1011
1012/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1013/// a single member function GlobalDecl.
1014llvm::DISubprogram
1015CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1016 llvm::DIFile Unit,
1017 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001018 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001019 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001020
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001022 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001023
1024 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1025 // make sense to give a single ctor/dtor a linkage name.
1026 StringRef MethodLinkageName;
1027 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1028 MethodLinkageName = CGM.getMangledName(Method);
1029
1030 // Get the location for the method.
1031 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1032 unsigned MethodLine = getLineNumber(Method->getLocation());
1033
1034 // Collect virtual method info.
1035 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001036 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001038
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 if (Method->isVirtual()) {
1040 if (Method->isPure())
1041 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1042 else
1043 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001044
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 // It doesn't make sense to give a virtual destructor a vtable index,
1046 // since a single destructor has two entries in the vtable.
1047 if (!isa<CXXDestructorDecl>(Method))
1048 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1049 ContainingType = RecordTy;
1050 }
1051
1052 unsigned Flags = 0;
1053 if (Method->isImplicit())
1054 Flags |= llvm::DIDescriptor::FlagArtificial;
1055 AccessSpecifier Access = Method->getAccess();
1056 if (Access == clang::AS_private)
1057 Flags |= llvm::DIDescriptor::FlagPrivate;
1058 else if (Access == clang::AS_protected)
1059 Flags |= llvm::DIDescriptor::FlagProtected;
1060 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1061 if (CXXC->isExplicit())
1062 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001063 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001064 dyn_cast<CXXConversionDecl>(Method)) {
1065 if (CXXC->isExplicit())
1066 Flags |= llvm::DIDescriptor::FlagExplicit;
1067 }
1068 if (Method->hasPrototype())
1069 Flags |= llvm::DIDescriptor::FlagPrototyped;
1070
1071 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1072 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001073 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001075 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 /* isDefinition=*/ false,
1077 Virtuality, VIndex, ContainingType,
1078 Flags, CGM.getLangOpts().Optimize, NULL,
1079 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001080
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1082
1083 return SP;
1084}
1085
1086/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001087/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001088/// a Record.
1089void CGDebugInfo::
1090CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1091 SmallVectorImpl<llvm::Value *> &EltTys,
1092 llvm::DIType RecordTy) {
1093
1094 // Since we want more than just the individual member decls if we
1095 // have templated functions iterate over every declaration to gather
1096 // the functions.
1097 for(DeclContext::decl_iterator I = RD->decls_begin(),
1098 E = RD->decls_end(); I != E; ++I) {
1099 Decl *D = *I;
1100 if (D->isImplicit() && !D->isUsed())
1101 continue;
1102
1103 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1104 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1105 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1106 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1107 SE = FTD->spec_end(); SI != SE; ++SI)
1108 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1109 RecordTy));
1110 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001111}
Guy Benyei11169dd2012-12-18 14:30:41 +00001112
1113/// CollectCXXFriends - A helper function to collect debug info for
1114/// C++ base classes. This is used while creating debug info entry for
1115/// a Record.
1116void CGDebugInfo::
1117CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1118 SmallVectorImpl<llvm::Value *> &EltTys,
1119 llvm::DIType RecordTy) {
1120 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1121 BE = RD->friend_end(); BI != BE; ++BI) {
1122 if ((*BI)->isUnsupportedFriend())
1123 continue;
1124 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopherb2a008c2013-05-16 00:45:12 +00001125 EltTys.push_back(DBuilder.createFriend(RecordTy,
1126 getOrCreateType(TInfo->getType(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001127 Unit)));
1128 }
1129}
1130
1131/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001132/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001133/// a Record.
1134void CGDebugInfo::
1135CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1136 SmallVectorImpl<llvm::Value *> &EltTys,
1137 llvm::DIType RecordTy) {
1138
1139 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1140 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1141 BE = RD->bases_end(); BI != BE; ++BI) {
1142 unsigned BFlags = 0;
1143 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001144
Guy Benyei11169dd2012-12-18 14:30:41 +00001145 const CXXRecordDecl *Base =
1146 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001147
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 if (BI->isVirtual()) {
1149 // virtual base offset offset is -ve. The code generator emits dwarf
1150 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001151 BaseOffset =
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 0 - CGM.getVTableContext()
1153 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1154 BFlags = llvm::DIDescriptor::FlagVirtual;
1155 } else
1156 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1157 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1158 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001159
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 AccessSpecifier Access = BI->getAccessSpecifier();
1161 if (Access == clang::AS_private)
1162 BFlags |= llvm::DIDescriptor::FlagPrivate;
1163 else if (Access == clang::AS_protected)
1164 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001165
1166 llvm::DIType DTy =
1167 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 getOrCreateType(BI->getType(), Unit),
1169 BaseOffset, BFlags);
1170 EltTys.push_back(DTy);
1171 }
1172}
1173
1174/// CollectTemplateParams - A helper function to collect template parameters.
1175llvm::DIArray CGDebugInfo::
1176CollectTemplateParams(const TemplateParameterList *TPList,
1177 const TemplateArgumentList &TAList,
1178 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001179 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1181 const TemplateArgument &TA = TAList[i];
1182 const NamedDecl *ND = TPList->getParam(i);
David Blaikie38079fd2013-05-10 21:53:14 +00001183 switch (TA.getKind()) {
1184 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1186 llvm::DITemplateTypeParameter TTP =
1187 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1188 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001189 } break;
1190 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1192 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001193 DBuilder.createTemplateValueParameter(
1194 TheCU, ND->getName(), TTy,
1195 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1196 TemplateParams.push_back(TVP);
1197 } break;
1198 case TemplateArgument::Declaration: {
1199 const ValueDecl *D = TA.getAsDecl();
1200 bool InstanceMember = D->isCXXInstanceMember();
1201 QualType T = InstanceMember
1202 ? CGM.getContext().getMemberPointerType(
1203 D->getType(), cast<RecordDecl>(D->getDeclContext())
1204 ->getTypeForDecl())
1205 : CGM.getContext().getPointerType(D->getType());
1206 llvm::DIType TTy = getOrCreateType(T, Unit);
1207 llvm::Value *V = 0;
1208 // Variable pointer template parameters have a value that is the address
1209 // of the variable.
1210 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1211 V = CGM.GetAddrOfGlobalVar(VD);
1212 // Member function pointers have special support for building them, though
1213 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001214 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001215 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1216 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001217 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1218 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001219 // Member data pointers have special handling too to compute the fixed
1220 // offset within the object.
1221 if (isa<FieldDecl>(D)) {
1222 // These five lines (& possibly the above member function pointer
1223 // handling) might be able to be refactored to use similar code in
1224 // CodeGenModule::getMemberPointerConstant
1225 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1226 CharUnits chars =
1227 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1228 V = CGM.getCXXABI().EmitMemberDataPointer(
1229 cast<MemberPointerType>(T.getTypePtr()), chars);
1230 }
1231 llvm::DITemplateValueParameter TVP =
1232 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1233 TemplateParams.push_back(TVP);
1234 } break;
1235 case TemplateArgument::NullPtr: {
1236 QualType T = TA.getNullPtrType();
1237 llvm::DIType TTy = getOrCreateType(T, Unit);
1238 llvm::Value *V = 0;
1239 // Special case member data pointer null values since they're actually -1
1240 // instead of zero.
1241 if (const MemberPointerType *MPT =
1242 dyn_cast<MemberPointerType>(T.getTypePtr()))
1243 // But treat member function pointers as simple zero integers because
1244 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1245 // CodeGen grows handling for values of non-null member function
1246 // pointers then perhaps we could remove this special case and rely on
1247 // EmitNullMemberPointer for member function pointers.
1248 if (MPT->isMemberDataPointer())
1249 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1250 if (!V)
1251 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1252 llvm::DITemplateValueParameter TVP =
1253 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1254 TemplateParams.push_back(TVP);
1255 } break;
1256 case TemplateArgument::Template:
1257 // We could support this with the GCC extension
1258 // DW_TAG_GNU_template_template_param
1259 break;
David Blaikie7e4c8b02013-05-10 22:53:25 +00001260 case TemplateArgument::Pack:
1261 // And this with DW_TAG_GNU_template_parameter_pack
1262 break;
David Blaikie2b93c542013-05-10 23:36:06 +00001263 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001264 case TemplateArgument::Expression:
1265 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001266 case TemplateArgument::Null:
1267 llvm_unreachable(
1268 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 }
1270 }
1271 return DBuilder.getOrCreateArray(TemplateParams);
1272}
1273
1274/// CollectFunctionTemplateParams - A helper function to collect debug
1275/// info for function template parameters.
1276llvm::DIArray CGDebugInfo::
1277CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1278 if (FD->getTemplatedKind() ==
1279 FunctionDecl::TK_FunctionTemplateSpecialization) {
1280 const TemplateParameterList *TList =
1281 FD->getTemplateSpecializationInfo()->getTemplate()
1282 ->getTemplateParameters();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001283 return
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1285 }
1286 return llvm::DIArray();
1287}
1288
1289/// CollectCXXTemplateParams - A helper function to collect debug info for
1290/// template parameters.
1291llvm::DIArray CGDebugInfo::
1292CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1293 llvm::DIFile Unit) {
1294 llvm::PointerUnion<ClassTemplateDecl *,
1295 ClassTemplatePartialSpecializationDecl *>
1296 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001297
Guy Benyei11169dd2012-12-18 14:30:41 +00001298 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1299 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1300 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1301 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1302 return CollectTemplateParams(TPList, TAList, Unit);
1303}
1304
1305/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1306llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1307 if (VTablePtrType.isValid())
1308 return VTablePtrType;
1309
1310 ASTContext &Context = CGM.getContext();
1311
1312 /* Function type */
1313 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1314 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1315 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1316 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1317 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1318 "__vtbl_ptr_type");
1319 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1320 return VTablePtrType;
1321}
1322
1323/// getVTableName - Get vtable name for the given Class.
1324StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1325 // Construct gdb compatible name name.
1326 std::string Name = "_vptr$" + RD->getNameAsString();
1327
1328 // Copy this name on the side and use its reference.
1329 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1330 memcpy(StrPtr, Name.data(), Name.length());
1331 return StringRef(StrPtr, Name.length());
1332}
1333
1334
1335/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1336/// debug info entry in EltTys vector.
1337void CGDebugInfo::
1338CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1339 SmallVectorImpl<llvm::Value *> &EltTys) {
1340 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1341
1342 // If there is a primary base then it will hold vtable info.
1343 if (RL.getPrimaryBase())
1344 return;
1345
1346 // If this class is not dynamic then there is not any vtable info to collect.
1347 if (!RD->isDynamicClass())
1348 return;
1349
1350 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1351 llvm::DIType VPTR
1352 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001353 0, Size, 0, 0,
1354 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 getOrCreateVTablePtrType(Unit));
1356 EltTys.push_back(VPTR);
1357}
1358
Eric Christopherb2a008c2013-05-16 00:45:12 +00001359/// getOrCreateRecordType - Emit record type's standalone debug info.
1360llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001362 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1364 return T;
1365}
1366
1367/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1368/// debug info.
1369llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001370 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001371 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001373 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 return T;
1375}
1376
1377/// CreateType - get structure or union type.
David Blaikiee36464c2013-06-05 05:32:23 +00001378llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 RecordDecl *RD = Ty->getDecl();
David Blaikiee36464c2013-06-05 05:32:23 +00001380 if (Declaration) {
1381 llvm::DIDescriptor FDContext =
1382 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1383 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1384 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1385 return RetTy;
1386 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001387
1388 // Get overall information about the record type for the debug info.
1389 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1390
1391 // Records and classes and unions can all be recursive. To handle them, we
1392 // first generate a debug descriptor for the struct as a forward declaration.
1393 // Then (if it is a definition) we go through and get debug info for all of
1394 // its members. Finally, we create a descriptor for the complete type (which
1395 // may refer to the forward decl if the struct is recursive) and replace all
1396 // uses of the forward declaration with the final definition.
1397
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001398 llvm::DICompositeType FwdDecl(
1399 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1400 assert(FwdDecl.Verify() &&
David Blaikie469f0792013-05-22 23:22:42 +00001401 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001402
1403 if (FwdDecl.isForwardDecl())
1404 return FwdDecl;
1405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001407 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1409
Adrian Prantla03a85a2013-03-06 22:03:30 +00001410 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1412
1413 // Convert all the elements.
1414 SmallVector<llvm::Value *, 16> EltTys;
1415
1416 // Note: The split of CXXDecl information here is intentional, the
1417 // gdb tests will depend on a certain ordering at printout. The debug
1418 // information offsets are still correct if we merge them all together
1419 // though.
1420 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1421 if (CXXDecl) {
1422 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1423 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1424 }
1425
Eric Christopher91a31902013-01-16 01:22:32 +00001426 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1428 llvm::DIArray TParamsArray;
1429 if (CXXDecl) {
1430 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1431 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1432 if (const ClassTemplateSpecializationDecl *TSpecial
1433 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1434 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1435 }
1436
1437 LexicalBlockStack.pop_back();
1438 RegionMap.erase(Ty->getDecl());
1439
1440 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001441 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001443 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1444 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001445}
1446
1447/// CreateType - get objective-c object type.
1448llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1449 llvm::DIFile Unit) {
1450 // Ignore protocols.
1451 return getOrCreateType(Ty->getBaseType(), Unit);
1452}
1453
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001454
1455/// \return true if Getter has the default name for the property PD.
1456static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1457 const ObjCMethodDecl *Getter) {
1458 assert(PD);
1459 if (!Getter)
1460 return true;
1461
1462 assert(Getter->getDeclName().isObjCZeroArgSelector());
1463 return PD->getName() ==
1464 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1465}
1466
1467/// \return true if Setter has the default name for the property PD.
1468static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1469 const ObjCMethodDecl *Setter) {
1470 assert(PD);
1471 if (!Setter)
1472 return true;
1473
1474 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001475 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001476 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1477}
1478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479/// CreateType - get objective-c interface type.
1480llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1481 llvm::DIFile Unit) {
1482 ObjCInterfaceDecl *ID = Ty->getDecl();
1483 if (!ID)
1484 return llvm::DIType();
1485
1486 // Get overall information about the record type for the debug info.
1487 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1488 unsigned Line = getLineNumber(ID->getLocation());
1489 unsigned RuntimeLang = TheCU.getLanguage();
1490
1491 // If this is just a forward declaration return a special forward-declaration
1492 // debug type since we won't be able to lay out the entire type.
1493 ObjCInterfaceDecl *Def = ID->getDefinition();
1494 if (!Def) {
1495 llvm::DIType FwdDecl =
1496 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001497 ID->getName(), TheCU, DefUnit, Line,
1498 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 return FwdDecl;
1500 }
1501
1502 ID = Def;
1503
1504 // Bit size, align and offset of the type.
1505 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1506 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1507
1508 unsigned Flags = 0;
1509 if (ID->getImplementation())
1510 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1511
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001512 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1514 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001515 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001516
1517 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1518 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001519 QualType QualTy = QualType(Ty, 0);
1520 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 // Push the struct on region stack.
Guy Benyei11169dd2012-12-18 14:30:41 +00001522
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001523 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1525
1526 // Convert all the elements.
1527 SmallVector<llvm::Value *, 16> EltTys;
1528
1529 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1530 if (SClass) {
1531 llvm::DIType SClassTy =
1532 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1533 if (!SClassTy.isValid())
1534 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001535
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 llvm::DIType InhTag =
1537 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1538 EltTys.push_back(InhTag);
1539 }
1540
1541 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1542 E = ID->prop_end(); I != E; ++I) {
1543 const ObjCPropertyDecl *PD = *I;
1544 SourceLocation Loc = PD->getLocation();
1545 llvm::DIFile PUnit = getOrCreateFile(Loc);
1546 unsigned PLine = getLineNumber(Loc);
1547 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1548 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1549 llvm::MDNode *PropertyNode =
1550 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001551 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001552 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001554 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 getSelectorName(PD->getSetterName()),
1556 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001557 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 EltTys.push_back(PropertyNode);
1559 }
1560
1561 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1562 unsigned FieldNo = 0;
1563 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1564 Field = Field->getNextIvar(), ++FieldNo) {
1565 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1566 if (!FieldTy.isValid())
1567 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001568
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 StringRef FieldName = Field->getName();
1570
1571 // Ignore unnamed fields.
1572 if (FieldName.empty())
1573 continue;
1574
1575 // Get the location for the field.
1576 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1577 unsigned FieldLine = getLineNumber(Field->getLocation());
1578 QualType FType = Field->getType();
1579 uint64_t FieldSize = 0;
1580 unsigned FieldAlign = 0;
1581
1582 if (!FType->isIncompleteArrayType()) {
1583
1584 // Bit size, align and offset of the type.
1585 FieldSize = Field->isBitField()
1586 ? Field->getBitWidthValue(CGM.getContext())
1587 : CGM.getContext().getTypeSize(FType);
1588 FieldAlign = CGM.getContext().getTypeAlign(FType);
1589 }
1590
1591 uint64_t FieldOffset;
1592 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1593 // We don't know the runtime offset of an ivar if we're using the
1594 // non-fragile ABI. For bitfields, use the bit offset into the first
1595 // byte of storage of the bitfield. For other fields, use zero.
1596 if (Field->isBitField()) {
1597 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1598 CGM, ID, Field);
1599 FieldOffset %= CGM.getContext().getCharWidth();
1600 } else {
1601 FieldOffset = 0;
1602 }
1603 } else {
1604 FieldOffset = RL.getFieldOffset(FieldNo);
1605 }
1606
1607 unsigned Flags = 0;
1608 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1609 Flags = llvm::DIDescriptor::FlagProtected;
1610 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1611 Flags = llvm::DIDescriptor::FlagPrivate;
1612
1613 llvm::MDNode *PropertyNode = NULL;
1614 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001615 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1617 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001618 SourceLocation Loc = PD->getLocation();
1619 llvm::DIFile PUnit = getOrCreateFile(Loc);
1620 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1622 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1623 PropertyNode =
1624 DBuilder.createObjCProperty(PD->getName(),
1625 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001626 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001627 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001628 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 getSelectorName(PD->getSetterName()),
1630 PD->getPropertyAttributes(),
1631 getOrCreateType(PD->getType(), PUnit));
1632 }
1633 }
1634 }
1635 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1636 FieldLine, FieldSize, FieldAlign,
1637 FieldOffset, Flags, FieldTy,
1638 PropertyNode);
1639 EltTys.push_back(FieldTy);
1640 }
1641
1642 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001643 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001644
1645 // If the implementation is not yet set, we do not want to mark it
1646 // as complete. An implementation may declare additional
1647 // private ivars that we would miss otherwise.
1648 if (ID->getImplementation() == 0)
1649 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001650
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001652 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001653}
1654
1655llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1656 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1657 int64_t Count = Ty->getNumElements();
1658 if (Count == 0)
1659 // If number of elements are not known then this is an unbounded array.
1660 // Use Count == -1 to express such arrays.
1661 Count = -1;
1662
1663 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1664 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1665
1666 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1667 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1668
1669 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1670}
1671
1672llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1673 llvm::DIFile Unit) {
1674 uint64_t Size;
1675 uint64_t Align;
1676
1677 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1678 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1679 Size = 0;
1680 Align =
1681 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1682 } else if (Ty->isIncompleteArrayType()) {
1683 Size = 0;
1684 if (Ty->getElementType()->isIncompleteType())
1685 Align = 0;
1686 else
1687 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001688 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 Size = 0;
1690 Align = 0;
1691 } else {
1692 // Size and align of the whole array, not the element type.
1693 Size = CGM.getContext().getTypeSize(Ty);
1694 Align = CGM.getContext().getTypeAlign(Ty);
1695 }
1696
1697 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1698 // interior arrays, do we care? Why aren't nested arrays represented the
1699 // obvious/recursive way?
1700 SmallVector<llvm::Value *, 8> Subscripts;
1701 QualType EltTy(Ty, 0);
1702 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1703 // If the number of elements is known, then count is that number. Otherwise,
1704 // it's -1. This allows us to represent a subrange with an array of 0
1705 // elements, like this:
1706 //
1707 // struct foo {
1708 // int x[0];
1709 // };
1710 int64_t Count = -1; // Count == -1 is an unbounded array.
1711 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1712 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001713
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 // FIXME: Verify this is right for VLAs.
1715 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1716 EltTy = Ty->getElementType();
1717 }
1718
1719 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1720
Eric Christopherb2a008c2013-05-16 00:45:12 +00001721 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001722 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1723 SubscriptArray);
1724 return DbgTy;
1725}
1726
Eric Christopherb2a008c2013-05-16 00:45:12 +00001727llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001728 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001729 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 Ty, Ty->getPointeeType(), Unit);
1731}
1732
Eric Christopherb2a008c2013-05-16 00:45:12 +00001733llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001735 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 Ty, Ty->getPointeeType(), Unit);
1737}
1738
Eric Christopherb2a008c2013-05-16 00:45:12 +00001739llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001740 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001741 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1742 if (!Ty->getPointeeType()->isFunctionType())
1743 return DBuilder.createMemberPointerType(
David Blaikie4583bea2013-05-24 21:33:22 +00001744 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikie2c705ca2013-01-19 19:20:56 +00001745 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1746 CGM.getContext().getPointerType(
1747 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1748 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1749 ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001750}
1751
Eric Christopherb2a008c2013-05-16 00:45:12 +00001752llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 llvm::DIFile U) {
1754 // Ignore the atomic wrapping
1755 // FIXME: What is the correct representation?
1756 return getOrCreateType(Ty->getValueType(), U);
1757}
1758
1759/// CreateEnumType - get enumeration type.
1760llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1761 uint64_t Size = 0;
1762 uint64_t Align = 0;
1763 if (!ED->getTypeForDecl()->isIncompleteType()) {
1764 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1765 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1766 }
1767
1768 // If this is just a forward declaration, construct an appropriately
1769 // marked node and just return it.
1770 if (!ED->getDefinition()) {
1771 llvm::DIDescriptor EDContext;
1772 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1773 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1774 unsigned Line = getLineNumber(ED->getLocation());
1775 StringRef EDName = ED->getName();
1776 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1777 EDName, EDContext, DefUnit, Line, 0,
1778 Size, Align);
1779 }
1780
1781 // Create DIEnumerator elements for each enumerator.
1782 SmallVector<llvm::Value *, 16> Enumerators;
1783 ED = ED->getDefinition();
1784 for (EnumDecl::enumerator_iterator
1785 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1786 Enum != EnumEnd; ++Enum) {
1787 Enumerators.push_back(
1788 DBuilder.createEnumerator(Enum->getName(),
1789 Enum->getInitVal().getZExtValue()));
1790 }
1791
1792 // Return a CompositeType for the enum itself.
1793 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1794
1795 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1796 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001797 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001799 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001801 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001802 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1803 Size, Align, EltArray,
1804 ClassTy);
1805 return DbgTy;
1806}
1807
David Blaikie05491062013-01-21 04:37:12 +00001808static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1809 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 do {
David Blaikie05491062013-01-21 04:37:12 +00001811 Quals += T.getLocalQualifiers();
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 QualType LastT = T;
1813 switch (T->getTypeClass()) {
1814 default:
David Blaikie05491062013-01-21 04:37:12 +00001815 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001816 case Type::TemplateSpecialization:
1817 T = cast<TemplateSpecializationType>(T)->desugar();
1818 break;
1819 case Type::TypeOfExpr:
1820 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1821 break;
1822 case Type::TypeOf:
1823 T = cast<TypeOfType>(T)->getUnderlyingType();
1824 break;
1825 case Type::Decltype:
1826 T = cast<DecltypeType>(T)->getUnderlyingType();
1827 break;
1828 case Type::UnaryTransform:
1829 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1830 break;
1831 case Type::Attributed:
1832 T = cast<AttributedType>(T)->getEquivalentType();
1833 break;
1834 case Type::Elaborated:
1835 T = cast<ElaboratedType>(T)->getNamedType();
1836 break;
1837 case Type::Paren:
1838 T = cast<ParenType>(T)->getInnerType();
1839 break;
David Blaikie05491062013-01-21 04:37:12 +00001840 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 break;
1843 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001844 QualType DT = cast<AutoType>(T)->getDeducedType();
1845 if (DT.isNull())
1846 return T;
1847 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 break;
1849 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001850
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001852 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 } while (true);
1854}
1855
Eric Christopher0fdcb312013-05-16 00:52:20 +00001856/// getType - Get the type from the cache or return null type if it doesn't
1857/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001858llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1859
1860 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001861 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001862
Guy Benyei11169dd2012-12-18 14:30:41 +00001863 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001864 if (Ty->getTypeClass() == Type::ObjCInterface) {
1865 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1866 if (V)
1867 return llvm::DIType(cast<llvm::MDNode>(V));
1868 else return llvm::DIType();
1869 }
1870
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1872 TypeCache.find(Ty.getAsOpaquePtr());
1873 if (it != TypeCache.end()) {
1874 // Verify that the debug info still exists.
1875 if (llvm::Value *V = it->second)
1876 return llvm::DIType(cast<llvm::MDNode>(V));
1877 }
1878
1879 return llvm::DIType();
1880}
1881
1882/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1883/// doesn't exist.
1884llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1885
1886 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001887 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001888
1889 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001890 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1892 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001893 if (it != CompletedTypeCache.end())
1894 V = it->second;
1895 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00001896 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 }
1898
Adrian Prantla03a85a2013-03-06 22:03:30 +00001899 // Verify that any cached debug info still exists.
1900 if (V != 0)
1901 return llvm::DIType(cast<llvm::MDNode>(V));
1902
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 return llvm::DIType();
1904}
1905
Adrian Prantl73409ce2013-03-11 18:33:46 +00001906/// getCachedInterfaceTypeOrNull - Get the type from the interface
1907/// cache, unless it needs to regenerated. Otherwise return null.
1908llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1909 // Is there a cached interface that hasn't changed?
1910 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1911 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1912
1913 if (it1 != ObjCInterfaceCache.end())
1914 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1915 if (Checksum(Decl) == it1->second.second)
1916 // Return cached forward declaration.
1917 return it1->second.first;
1918
1919 return 0;
1920}
Guy Benyei11169dd2012-12-18 14:30:41 +00001921
1922/// getOrCreateType - Get the type from the cache or create a new
1923/// one if necessary.
David Blaikiee36464c2013-06-05 05:32:23 +00001924llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit, bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 if (Ty.isNull())
1926 return llvm::DIType();
1927
1928 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001929 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001930
1931 llvm::DIType T = getCompletedTypeOrNull(Ty);
1932
1933 if (T.Verify())
1934 return T;
1935
1936 // Otherwise create the type.
David Blaikiee36464c2013-06-05 05:32:23 +00001937 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantl73409ce2013-03-11 18:33:46 +00001938 void* TyPtr = Ty.getAsOpaquePtr();
1939
1940 // And update the type cache.
1941 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00001942
1943 llvm::DIType TC = getTypeOrNull(Ty);
1944 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00001945 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1946 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1947 // Interface types may have elements added to them by a
1948 // subsequent implementation or extension, so we keep them in
1949 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00001950 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00001951 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00001952 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1953 if (V.first)
1954 return llvm::DIType(cast<llvm::MDNode>(V.first));
1955 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1956 Decl->getName(), TheCU, Unit,
1957 getLineNumber(Decl->getLocation()),
1958 TheCU.getLanguage());
1959 // Store the forward declaration in the cache.
1960 V.first = TC;
1961 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00001962
David Blaikie8e5939b2013-05-21 18:29:40 +00001963 // Register the type for replacement in finalize().
1964 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1965
Adrian Prantl73409ce2013-03-11 18:33:46 +00001966 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00001967 }
1968
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00001970 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00001971
1972 return Res;
1973}
1974
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00001975/// Currently the checksum of an interface includes the number of
1976/// ivars and property accessors.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001977unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00001978 *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00001979 // The assumption is that the number of ivars can only increase
1980 // monotonically, so it is safe to just use their current number as
1981 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00001982 unsigned Sum = 0;
1983 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
1984 Ivar != 0; Ivar = Ivar->getNextIvar())
1985 ++Sum;
1986
1987 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00001988}
1989
1990ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1991 switch (Ty->getTypeClass()) {
1992 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00001993 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1994 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001995 case Type::ObjCInterface:
1996 return cast<ObjCInterfaceType>(Ty)->getDecl();
1997 default:
1998 return 0;
1999 }
2000}
2001
Guy Benyei11169dd2012-12-18 14:30:41 +00002002/// CreateTypeNode - Create a new debug type node.
David Blaikiee36464c2013-06-05 05:32:23 +00002003llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit, bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002004 // Handle qualifiers, which recursively handles what they refer to.
2005 if (Ty.hasLocalQualifiers())
David Blaikiee36464c2013-06-05 05:32:23 +00002006 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002007
2008 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002009
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 // Work out details of type.
2011 switch (Ty->getTypeClass()) {
2012#define TYPE(Class, Base)
2013#define ABSTRACT_TYPE(Class, Base)
2014#define NON_CANONICAL_TYPE(Class, Base)
2015#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2016#include "clang/AST/TypeNodes.def"
2017 llvm_unreachable("Dependent types cannot show up in debug information");
2018
2019 case Type::ExtVector:
2020 case Type::Vector:
2021 return CreateType(cast<VectorType>(Ty), Unit);
2022 case Type::ObjCObjectPointer:
2023 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2024 case Type::ObjCObject:
2025 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2026 case Type::ObjCInterface:
2027 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2028 case Type::Builtin:
2029 return CreateType(cast<BuiltinType>(Ty));
2030 case Type::Complex:
2031 return CreateType(cast<ComplexType>(Ty));
2032 case Type::Pointer:
2033 return CreateType(cast<PointerType>(Ty), Unit);
2034 case Type::BlockPointer:
2035 return CreateType(cast<BlockPointerType>(Ty), Unit);
2036 case Type::Typedef:
David Blaikiee36464c2013-06-05 05:32:23 +00002037 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 case Type::Record:
David Blaikiee36464c2013-06-05 05:32:23 +00002039 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 case Type::Enum:
2041 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2042 case Type::FunctionProto:
2043 case Type::FunctionNoProto:
2044 return CreateType(cast<FunctionType>(Ty), Unit);
2045 case Type::ConstantArray:
2046 case Type::VariableArray:
2047 case Type::IncompleteArray:
2048 return CreateType(cast<ArrayType>(Ty), Unit);
2049
2050 case Type::LValueReference:
2051 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2052 case Type::RValueReference:
2053 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2054
2055 case Type::MemberPointer:
2056 return CreateType(cast<MemberPointerType>(Ty), Unit);
2057
2058 case Type::Atomic:
2059 return CreateType(cast<AtomicType>(Ty), Unit);
2060
2061 case Type::Attributed:
2062 case Type::TemplateSpecialization:
2063 case Type::Elaborated:
2064 case Type::Paren:
2065 case Type::SubstTemplateTypeParm:
2066 case Type::TypeOfExpr:
2067 case Type::TypeOf:
2068 case Type::Decltype:
2069 case Type::UnaryTransform:
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002071 case Type::Auto:
2072 Diag = "auto";
2073 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002075
Guy Benyei11169dd2012-12-18 14:30:41 +00002076 assert(Diag && "Fall through without a diagnostic?");
2077 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2078 "debug information for %0 is not yet supported");
2079 CGM.getDiags().Report(DiagID)
2080 << Diag;
2081 return llvm::DIType();
2082}
2083
2084/// getOrCreateLimitedType - Get the type from the cache or create a new
2085/// limited type if necessary.
2086llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002087 llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 if (Ty.isNull())
2089 return llvm::DIType();
2090
2091 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002092 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002093
2094 llvm::DIType T = getTypeOrNull(Ty);
2095
2096 // We may have cached a forward decl when we could have created
2097 // a non-forward decl. Go ahead and create a non-forward decl
2098 // now.
2099 if (T.Verify() && !T.isForwardDecl()) return T;
2100
2101 // Otherwise create the type.
2102 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2103
2104 if (T.Verify() && T.isForwardDecl())
2105 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2106 static_cast<llvm::Value*>(T)));
2107
2108 // And update the type cache.
2109 TypeCache[Ty.getAsOpaquePtr()] = Res;
2110 return Res;
2111}
2112
2113// TODO: Currently used for context chains when limiting debug info.
2114llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2115 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002116
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 // Get overall information about the record type for the debug info.
2118 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2119 unsigned Line = getLineNumber(RD->getLocation());
2120 StringRef RDName = getClassName(RD);
2121
2122 llvm::DIDescriptor RDContext;
Eric Christopher75e17682013-05-16 00:45:23 +00002123 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2125 else
2126 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2127
2128 // If this is just a forward declaration, construct an appropriately
2129 // marked node and just return it.
2130 if (!RD->getDefinition())
2131 return createRecordFwdDecl(RD, RDContext);
2132
2133 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2134 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2135 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie49ae6a72013-03-26 23:47:35 +00002136 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002137
Guy Benyei11169dd2012-12-18 14:30:41 +00002138 if (RD->isUnion())
2139 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002140 Size, Align, 0, llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002141 else if (RD->isClass()) {
2142 // FIXME: This could be a struct type giving a default visibility different
2143 // than C++ class type, but needs llvm metadata changes first.
2144 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002145 Size, Align, 0, 0, llvm::DIType(),
2146 llvm::DIArray(), llvm::DIType(),
2147 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 } else
2149 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002150 Size, Align, 0, llvm::DIType(),
2151 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002152
2153 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002154 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002155
2156 if (CXXDecl) {
2157 // A class's primary base or the class itself contains the vtable.
David Blaikie49ae6a72013-03-26 23:47:35 +00002158 llvm::DICompositeType ContainingType;
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2160 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2161 // Seek non virtual primary base root.
2162 while (1) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002163 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2164 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2165 if (PBT && !BRL.isPrimaryBaseVirtual())
2166 PBase = PBT;
2167 else
2168 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002169 }
David Blaikie49ae6a72013-03-26 23:47:35 +00002170 ContainingType = llvm::DICompositeType(
2171 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2172 } else if (CXXDecl->isDynamicClass())
Guy Benyei11169dd2012-12-18 14:30:41 +00002173 ContainingType = RealDecl;
2174
David Blaikie49ae6a72013-03-26 23:47:35 +00002175 RealDecl.setContainingType(ContainingType);
Guy Benyei11169dd2012-12-18 14:30:41 +00002176 }
2177 return llvm::DIType(RealDecl);
2178}
2179
2180/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2181/// declare composite types that haven't been processed yet.
2182llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2183
2184 // Work out details of type.
2185 switch (Ty->getTypeClass()) {
2186#define TYPE(Class, Base)
2187#define ABSTRACT_TYPE(Class, Base)
2188#define NON_CANONICAL_TYPE(Class, Base)
2189#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2190 #include "clang/AST/TypeNodes.def"
2191 llvm_unreachable("Dependent types cannot show up in debug information");
2192
2193 case Type::Record:
2194 return CreateLimitedType(cast<RecordType>(Ty));
2195 default:
David Blaikiee36464c2013-06-05 05:32:23 +00002196 return CreateTypeNode(Ty, Unit, false);
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 }
2198}
2199
2200/// CreateMemberType - Create new member and increase Offset by FType's size.
2201llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2202 StringRef Name,
2203 uint64_t *Offset) {
2204 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2205 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2206 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2207 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2208 FieldSize, FieldAlign,
2209 *Offset, 0, FieldTy);
2210 *Offset += FieldSize;
2211 return Ty;
2212}
2213
David Blaikiebd483762013-05-20 04:58:53 +00002214llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2215 // We only need a declaration (not a definition) of the type - so use whatever
2216 // we would otherwise do to get a type for a pointee. (forward declarations in
2217 // limited debug info, full definitions (if the type definition is available)
2218 // in unlimited debug info)
2219 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2220 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikie4583bea2013-05-24 21:33:22 +00002221 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2222 DefUnit);
David Blaikiebd483762013-05-20 04:58:53 +00002223 }
2224 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2225 // This doesn't handle providing declarations (for functions or variables) for
2226 // entities without definitions in this TU, nor when the definition proceeds
2227 // the call to this function.
2228 // FIXME: This should be split out into more specific maps with support for
2229 // emitting forward declarations and merging definitions with declarations,
2230 // the same way as we do for types.
2231 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2232 DeclCache.find(D->getCanonicalDecl());
2233 if (I == DeclCache.end())
2234 return llvm::DIDescriptor();
2235 llvm::Value *V = I->second;
2236 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2237}
2238
Guy Benyei11169dd2012-12-18 14:30:41 +00002239/// getFunctionDeclaration - Return debug info descriptor to describe method
2240/// declaration for the given method definition.
2241llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2242 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2243 if (!FD) return llvm::DISubprogram();
2244
2245 // Setup context.
2246 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2247
2248 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2249 MI = SPCache.find(FD->getCanonicalDecl());
2250 if (MI != SPCache.end()) {
2251 llvm::Value *V = MI->second;
2252 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2253 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2254 return SP;
2255 }
2256
2257 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2258 E = FD->redecls_end(); I != E; ++I) {
2259 const FunctionDecl *NextFD = *I;
2260 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2261 MI = SPCache.find(NextFD->getCanonicalDecl());
2262 if (MI != SPCache.end()) {
2263 llvm::Value *V = MI->second;
2264 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2265 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2266 return SP;
2267 }
2268 }
2269 return llvm::DISubprogram();
2270}
2271
2272// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2273// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002274llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2275 QualType FnType,
2276 llvm::DIFile F) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002277
2278 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2279 return getOrCreateMethodType(Method, F);
2280 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2281 // Add "self" and "_cmd"
2282 SmallVector<llvm::Value *, 16> Elts;
2283
2284 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl5f360102013-05-22 21:37:49 +00002285 QualType ResultTy = OMethod->getResultType();
2286
2287 // Replace the instancetype keyword with the actual type.
2288 if (ResultTy == CGM.getContext().getObjCInstanceType())
2289 ResultTy = CGM.getContext().getPointerType(
2290 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2291
Adrian Prantl7bec9032013-05-10 21:08:31 +00002292 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002294 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2295 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2296 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 // "_cmd" pointer is always second argument.
2298 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2299 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2300 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002301 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 PE = OMethod->param_end(); PI != PE; ++PI)
2303 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2304
2305 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2306 return DBuilder.createSubroutineType(F, EltTypeArray);
2307 }
David Blaikie469f0792013-05-22 23:22:42 +00002308 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002309}
2310
2311/// EmitFunctionStart - Constructs the debug code for entering a function.
2312void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2313 llvm::Function *Fn,
2314 CGBuilderTy &Builder) {
2315
2316 StringRef Name;
2317 StringRef LinkageName;
2318
2319 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2320
2321 const Decl *D = GD.getDecl();
2322 // Function may lack declaration in source code if it is created by Clang
2323 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2324 bool HasDecl = (D != 0);
2325 // Use the location of the declaration.
2326 SourceLocation Loc;
2327 if (HasDecl)
2328 Loc = D->getLocation();
2329
2330 unsigned Flags = 0;
2331 llvm::DIFile Unit = getOrCreateFile(Loc);
2332 llvm::DIDescriptor FDContext(Unit);
2333 llvm::DIArray TParamsArray;
2334 if (!HasDecl) {
2335 // Use llvm function name.
2336 Name = Fn->getName();
2337 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2338 // If there is a DISubprogram for this function available then use it.
2339 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2340 FI = SPCache.find(FD->getCanonicalDecl());
2341 if (FI != SPCache.end()) {
2342 llvm::Value *V = FI->second;
2343 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2344 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2345 llvm::MDNode *SPN = SP;
2346 LexicalBlockStack.push_back(SPN);
2347 RegionMap[D] = llvm::WeakVH(SP);
2348 return;
2349 }
2350 }
2351 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002352 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 if (FD->hasPrototype()) {
2354 LinkageName = CGM.getMangledName(GD);
2355 Flags |= llvm::DIDescriptor::FlagPrototyped;
2356 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002357 // No need to replicate the linkage name if it isn't different from the
2358 // subprogram name, no need to have it at all unless coverage is enabled or
2359 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002361 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2362 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002363 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 LinkageName = StringRef();
2365
Eric Christopher75e17682013-05-16 00:45:23 +00002366 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 if (const NamespaceDecl *NSDecl =
2368 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2369 FDContext = getOrCreateNameSpace(NSDecl);
2370 else if (const RecordDecl *RDecl =
2371 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2372 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2373
2374 // Collect template parameters.
2375 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2376 }
2377 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2378 Name = getObjCMethodName(OMD);
2379 Flags |= llvm::DIDescriptor::FlagPrototyped;
2380 } else {
2381 // Use llvm function name.
2382 Name = Fn->getName();
2383 Flags |= llvm::DIDescriptor::FlagPrototyped;
2384 }
2385 if (!Name.empty() && Name[0] == '\01')
2386 Name = Name.substr(1);
2387
2388 unsigned LineNo = getLineNumber(Loc);
2389 if (!HasDecl || D->isImplicit())
2390 Flags |= llvm::DIDescriptor::FlagArtificial;
2391
David Blaikie469f0792013-05-22 23:22:42 +00002392 llvm::DICompositeType DIFnType;
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 llvm::DISubprogram SPDecl;
2394 if (HasDecl &&
Eric Christopher75e17682013-05-16 00:45:23 +00002395 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2397 SPDecl = getFunctionDeclaration(D);
2398 } else {
2399 // Create fake but valid subroutine type. Otherwise
2400 // llvm::DISubprogram::Verify() would return false, and
2401 // subprogram DIE will miss DW_AT_decl_file and
2402 // DW_AT_decl_line fields.
2403 SmallVector<llvm::Value*, 16> Elts;
2404 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2405 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2406 }
2407 llvm::DISubprogram SP;
2408 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2409 LineNo, DIFnType,
2410 Fn->hasInternalLinkage(), true/*definition*/,
2411 getLineNumber(CurLoc), Flags,
2412 CGM.getLangOpts().Optimize,
2413 Fn, TParamsArray, SPDecl);
David Blaikiebd483762013-05-20 04:58:53 +00002414 if (HasDecl)
2415 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002416
2417 // Push function on region stack.
2418 llvm::MDNode *SPN = SP;
2419 LexicalBlockStack.push_back(SPN);
2420 if (HasDecl)
2421 RegionMap[D] = llvm::WeakVH(SP);
2422}
2423
2424/// EmitLocation - Emit metadata to indicate a change in line/column
2425/// information in the source file.
Adrian Prantlc7822422013-03-12 20:43:25 +00002426void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2427 bool ForceColumnInfo) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002428
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 // Update our current location
2430 setLocation(Loc);
2431
2432 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2433
2434 // Don't bother if things are the same as last time.
2435 SourceManager &SM = CGM.getContext().getSourceManager();
2436 if (CurLoc == PrevLoc ||
2437 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2438 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002439 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2440 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2441 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002443
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 // Update last state.
2445 PrevLoc = CurLoc;
2446
2447 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002448 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2449 (getLineNumber(CurLoc),
2450 getColumnNumber(CurLoc, ForceColumnInfo),
2451 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002452}
2453
2454/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2455/// the stack.
2456void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2457 llvm::DIDescriptor D =
2458 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2459 llvm::DIDescriptor() :
2460 llvm::DIDescriptor(LexicalBlockStack.back()),
2461 getOrCreateFile(CurLoc),
2462 getLineNumber(CurLoc),
2463 getColumnNumber(CurLoc));
2464 llvm::MDNode *DN = D;
2465 LexicalBlockStack.push_back(DN);
2466}
2467
2468/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2469/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002470void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2471 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // Set our current location.
2473 setLocation(Loc);
2474
2475 // Create a new lexical block and push it on the stack.
2476 CreateLexicalBlock(Loc);
2477
2478 // Emit a line table change for the current location inside the new scope.
2479 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2480 getColumnNumber(Loc),
2481 LexicalBlockStack.back()));
2482}
2483
2484/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2485/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002486void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2487 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2489
2490 // Provide an entry in the line table for the end of the block.
2491 EmitLocation(Builder, Loc);
2492
2493 LexicalBlockStack.pop_back();
2494}
2495
2496/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2497void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2498 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2499 unsigned RCount = FnBeginRegionCount.back();
2500 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2501
2502 // Pop all regions for this function.
2503 while (LexicalBlockStack.size() != RCount)
2504 EmitLexicalBlockEnd(Builder, CurLoc);
2505 FnBeginRegionCount.pop_back();
2506}
2507
Eric Christopherb2a008c2013-05-16 00:45:12 +00002508// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002509// See BuildByRefType.
2510llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2511 uint64_t *XOffset) {
2512
2513 SmallVector<llvm::Value *, 5> EltTys;
2514 QualType FType;
2515 uint64_t FieldSize, FieldOffset;
2516 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002517
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002519 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002520
2521 FieldOffset = 0;
2522 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2523 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2524 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2525 FType = CGM.getContext().IntTy;
2526 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2527 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2528
2529 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2530 if (HasCopyAndDispose) {
2531 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2532 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2533 &FieldOffset));
2534 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2535 &FieldOffset));
2536 }
2537 bool HasByrefExtendedLayout;
2538 Qualifiers::ObjCLifetime Lifetime;
2539 if (CGM.getContext().getByrefLifetime(Type,
2540 Lifetime, HasByrefExtendedLayout)
2541 && HasByrefExtendedLayout)
2542 EltTys.push_back(CreateMemberType(Unit, FType,
2543 "__byref_variable_layout",
2544 &FieldOffset));
Eric Christopherb2a008c2013-05-16 00:45:12 +00002545
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2547 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002548 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002549 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2551 CharUnits AlignedOffsetInBytes
2552 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2553 CharUnits NumPaddingBytes
2554 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002555
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 if (NumPaddingBytes.isPositive()) {
2557 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2558 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2559 pad, ArrayType::Normal, 0);
2560 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2561 }
2562 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002563
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 FType = Type;
2565 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2566 FieldSize = CGM.getContext().getTypeSize(FType);
2567 FieldAlign = CGM.getContext().toBits(Align);
2568
Eric Christopherb2a008c2013-05-16 00:45:12 +00002569 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2571 0, FieldSize, FieldAlign,
2572 FieldOffset, 0, FieldTy);
2573 EltTys.push_back(FieldTy);
2574 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002575
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002579
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002581 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002582}
2583
2584/// EmitDeclare - Emit local variable declaration debug info.
2585void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002586 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002588 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2590
2591 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2592 llvm::DIType Ty;
2593 uint64_t XOffset = 0;
2594 if (VD->hasAttr<BlocksAttr>())
2595 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002596 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 Ty = getOrCreateType(VD->getType(), Unit);
2598
2599 // If there is no debug info for this type then do not emit debug info
2600 // for this variable.
2601 if (!Ty)
2602 return;
2603
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 // Get location information.
2605 unsigned Line = getLineNumber(VD->getLocation());
2606 unsigned Column = getColumnNumber(VD->getLocation());
2607 unsigned Flags = 0;
2608 if (VD->isImplicit())
2609 Flags |= llvm::DIDescriptor::FlagArtificial;
2610 // If this is the first argument and it is implicit then
2611 // give it an object pointer flag.
2612 // FIXME: There has to be a better way to do this, but for static
2613 // functions there won't be an implicit param at arg1 and
2614 // otherwise it is 'self' or 'this'.
2615 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2616 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2617
2618 llvm::MDNode *Scope = LexicalBlockStack.back();
2619
2620 StringRef Name = VD->getName();
2621 if (!Name.empty()) {
2622 if (VD->hasAttr<BlocksAttr>()) {
2623 CharUnits offset = CharUnits::fromQuantity(32);
2624 SmallVector<llvm::Value *, 9> addr;
2625 llvm::Type *Int64Ty = CGM.Int64Ty;
2626 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2627 // offset of __forwarding field
2628 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002629 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2631 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2632 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2633 // offset of x field
2634 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2635 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2636
2637 // Create the descriptor for the variable.
2638 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002639 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 llvm::DIDescriptor(Scope),
2641 VD->getName(), Unit, Line, Ty,
2642 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 // Insert an llvm.dbg.declare into the current block.
2645 llvm::Instruction *Call =
2646 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2647 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2648 return;
Adrian Prantlab067ae2013-04-30 22:45:09 +00002649 } else if (isa<VariableArrayType>(VD->getType())) {
2650 // These are "complex" variables in that they need an op_deref.
2651 // Create the descriptor for the variable.
2652 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2653 llvm::DIBuilder::OpDeref);
2654 llvm::DIVariable D =
2655 DBuilder.createComplexVariable(Tag,
2656 llvm::DIDescriptor(Scope),
2657 Name, Unit, Line, Ty,
2658 Addr, ArgNo);
2659
2660 // Insert an llvm.dbg.declare into the current block.
2661 llvm::Instruction *Call =
2662 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2663 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2664 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002666 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2667 // If VD is an anonymous union then Storage represents value for
2668 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002670 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 for (RecordDecl::field_iterator I = RD->field_begin(),
2672 E = RD->field_end();
2673 I != E; ++I) {
2674 FieldDecl *Field = *I;
2675 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2676 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002677
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 // Ignore unnamed fields. Do not ignore unnamed records.
2679 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2680 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002681
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 // Use VarDecl's Tag, Scope and Line number.
2683 llvm::DIVariable D =
2684 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002685 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 CGM.getLangOpts().Optimize, Flags,
2687 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002688
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 // Insert an llvm.dbg.declare into the current block.
2690 llvm::Instruction *Call =
2691 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2692 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2693 }
David Blaikie219c7d92013-01-05 20:03:07 +00002694 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 }
2696 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002697
2698 // Create the descriptor for the variable.
2699 llvm::DIVariable D =
2700 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2701 Name, Unit, Line, Ty,
2702 CGM.getLangOpts().Optimize, Flags, ArgNo);
2703
2704 // Insert an llvm.dbg.declare into the current block.
2705 llvm::Instruction *Call =
2706 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2707 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002708}
2709
2710void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2711 llvm::Value *Storage,
2712 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002713 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2715}
2716
Adrian Prantlde17db32013-03-29 19:20:29 +00002717/// Look up the completed type for a self pointer in the TypeCache and
2718/// create a copy of it with the ObjectPointer and Artificial flags
2719/// set. If the type is not cached, a new one is created. This should
2720/// never happen though, since creating a type for the implicit self
2721/// argument implies that we already parsed the interface definition
2722/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002723llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2724 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002725 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2726 if (CachedTy.Verify()) Ty = CachedTy;
2727 else DEBUG(llvm::dbgs() << "No cached type for self.");
2728 return DBuilder.createObjectPointerType(Ty);
2729}
2730
Guy Benyei11169dd2012-12-18 14:30:41 +00002731void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2732 llvm::Value *Storage,
2733 CGBuilderTy &Builder,
2734 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002735 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002737
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 if (Builder.GetInsertBlock() == 0)
2739 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002742
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 uint64_t XOffset = 0;
2744 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2745 llvm::DIType Ty;
2746 if (isByRef)
2747 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002748 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 Ty = getOrCreateType(VD->getType(), Unit);
2750
2751 // Self is passed along as an implicit non-arg variable in a
2752 // block. Mark it as the object pointer.
2753 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002754 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002755
2756 // Get location information.
2757 unsigned Line = getLineNumber(VD->getLocation());
2758 unsigned Column = getColumnNumber(VD->getLocation());
2759
2760 const llvm::DataLayout &target = CGM.getDataLayout();
2761
2762 CharUnits offset = CharUnits::fromQuantity(
2763 target.getStructLayout(blockInfo.StructureType)
2764 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2765
2766 SmallVector<llvm::Value *, 9> addr;
2767 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002768 if (isa<llvm::AllocaInst>(Storage))
2769 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2771 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2772 if (isByRef) {
2773 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2774 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2775 // offset of __forwarding field
2776 offset = CGM.getContext()
2777 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2778 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2779 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2780 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2781 // offset of x field
2782 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2783 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2784 }
2785
2786 // Create the descriptor for the variable.
2787 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002788 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 llvm::DIDescriptor(LexicalBlockStack.back()),
2790 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002791
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 // Insert an llvm.dbg.declare into the current block.
2793 llvm::Instruction *Call =
2794 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2795 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2796 LexicalBlockStack.back()));
2797}
2798
2799/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2800/// variable declaration.
2801void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2802 unsigned ArgNo,
2803 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002804 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2806}
2807
2808namespace {
2809 struct BlockLayoutChunk {
2810 uint64_t OffsetInBits;
2811 const BlockDecl::Capture *Capture;
2812 };
2813 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2814 return l.OffsetInBits < r.OffsetInBits;
2815 }
2816}
2817
2818void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002819 llvm::Value *Arg,
2820 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002822 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 ASTContext &C = CGM.getContext();
2824 const BlockDecl *blockDecl = block.getBlockDecl();
2825
2826 // Collect some general information about the block's location.
2827 SourceLocation loc = blockDecl->getCaretLocation();
2828 llvm::DIFile tunit = getOrCreateFile(loc);
2829 unsigned line = getLineNumber(loc);
2830 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002831
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 // Build the debug-info type for the block literal.
2833 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2834
2835 const llvm::StructLayout *blockLayout =
2836 CGM.getDataLayout().getStructLayout(block.StructureType);
2837
2838 SmallVector<llvm::Value*, 16> fields;
2839 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2840 blockLayout->getElementOffsetInBits(0),
2841 tunit, tunit));
2842 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2843 blockLayout->getElementOffsetInBits(1),
2844 tunit, tunit));
2845 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2846 blockLayout->getElementOffsetInBits(2),
2847 tunit, tunit));
2848 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2849 blockLayout->getElementOffsetInBits(3),
2850 tunit, tunit));
2851 fields.push_back(createFieldType("__descriptor",
2852 C.getPointerType(block.NeedsCopyDispose ?
2853 C.getBlockDescriptorExtendedType() :
2854 C.getBlockDescriptorType()),
2855 0, loc, AS_public,
2856 blockLayout->getElementOffsetInBits(4),
2857 tunit, tunit));
2858
2859 // We want to sort the captures by offset, not because DWARF
2860 // requires this, but because we're paranoid about debuggers.
2861 SmallVector<BlockLayoutChunk, 8> chunks;
2862
2863 // 'this' capture.
2864 if (blockDecl->capturesCXXThis()) {
2865 BlockLayoutChunk chunk;
2866 chunk.OffsetInBits =
2867 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2868 chunk.Capture = 0;
2869 chunks.push_back(chunk);
2870 }
2871
2872 // Variable captures.
2873 for (BlockDecl::capture_const_iterator
2874 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2875 i != e; ++i) {
2876 const BlockDecl::Capture &capture = *i;
2877 const VarDecl *variable = capture.getVariable();
2878 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2879
2880 // Ignore constant captures.
2881 if (captureInfo.isConstant())
2882 continue;
2883
2884 BlockLayoutChunk chunk;
2885 chunk.OffsetInBits =
2886 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2887 chunk.Capture = &capture;
2888 chunks.push_back(chunk);
2889 }
2890
2891 // Sort by offset.
2892 llvm::array_pod_sort(chunks.begin(), chunks.end());
2893
2894 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2895 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2896 uint64_t offsetInBits = i->OffsetInBits;
2897 const BlockDecl::Capture *capture = i->Capture;
2898
2899 // If we have a null capture, this must be the C++ 'this' capture.
2900 if (!capture) {
2901 const CXXMethodDecl *method =
2902 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2903 QualType type = method->getThisType(C);
2904
2905 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2906 offsetInBits, tunit, tunit));
2907 continue;
2908 }
2909
2910 const VarDecl *variable = capture->getVariable();
2911 StringRef name = variable->getName();
2912
2913 llvm::DIType fieldType;
2914 if (capture->isByRef()) {
2915 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2916
2917 // FIXME: this creates a second copy of this type!
2918 uint64_t xoffset;
2919 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2920 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2921 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2922 ptrInfo.first, ptrInfo.second,
2923 offsetInBits, 0, fieldType);
2924 } else {
2925 fieldType = createFieldType(name, variable->getType(), 0,
2926 loc, AS_public, offsetInBits, tunit, tunit);
2927 }
2928 fields.push_back(fieldType);
2929 }
2930
2931 SmallString<36> typeName;
2932 llvm::raw_svector_ostream(typeName)
2933 << "__block_literal_" << CGM.getUniqueBlockCount();
2934
2935 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2936
2937 llvm::DIType type =
2938 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2939 CGM.getContext().toBits(block.BlockSize),
2940 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00002941 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2943
2944 // Get overall information about the block.
2945 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2946 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00002947
2948 // Create the descriptor for the parameter.
2949 llvm::DIVariable debugVar =
2950 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002951 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00002952 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002954 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2955
Adrian Prantl616bef42013-03-14 21:52:59 +00002956 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00002957 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00002958 llvm::Instruction *DbgVal =
2959 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002960 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00002961 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2962 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00002963
Adrian Prantl616bef42013-03-14 21:52:59 +00002964 // Insert an llvm.dbg.declare into the current block.
2965 llvm::Instruction *DbgDecl =
2966 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2967 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002968}
2969
Eric Christopher91a31902013-01-16 01:22:32 +00002970/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2971/// a static data member of a class, find its corresponding in-class
2972/// declaration.
2973llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2974 if (cast<VarDecl>(D)->isStaticDataMember()) {
2975 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2976 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2977 if (MI != StaticDataMemberCache.end())
2978 // Verify the info still exists.
2979 if (llvm::Value *V = MI->second)
2980 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2981 }
2982 return llvm::DIDerivedType();
2983}
2984
Guy Benyei11169dd2012-12-18 14:30:41 +00002985/// EmitGlobalVariable - Emit information about a global variable.
2986void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2987 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00002988 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 // Create global variable debug descriptor.
2990 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2991 unsigned LineNo = getLineNumber(D->getLocation());
2992
2993 setLocation(D->getLocation());
2994
2995 QualType T = D->getType();
2996 if (T->isIncompleteArrayType()) {
2997
2998 // CodeGen turns int[] into int[1] so we'll do the same here.
2999 llvm::APInt ConstVal(32, 1);
3000 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3001
3002 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3003 ArrayType::Normal, 0);
3004 }
3005 StringRef DeclName = D->getName();
3006 StringRef LinkageName;
3007 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3008 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3009 LinkageName = Var->getName();
3010 if (LinkageName == DeclName)
3011 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003012 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikiebd483762013-05-20 04:58:53 +00003014 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003015 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher91a31902013-01-16 01:22:32 +00003016 Var->hasInternalLinkage(), Var,
3017 getStaticDataMemberDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00003018 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003019}
3020
3021/// EmitGlobalVariable - Emit information about an objective-c interface.
3022void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3023 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003024 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 // Create global variable debug descriptor.
3026 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3027 unsigned LineNo = getLineNumber(ID->getLocation());
3028
3029 StringRef Name = ID->getName();
3030
3031 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3032 if (T->isIncompleteArrayType()) {
3033
3034 // CodeGen turns int[] into int[1] so we'll do the same here.
3035 llvm::APInt ConstVal(32, 1);
3036 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3037
3038 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3039 ArrayType::Normal, 0);
3040 }
3041
3042 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3043 getOrCreateType(T, Unit),
3044 Var->hasInternalLinkage(), Var);
3045}
3046
3047/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003048void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003050 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 // Create the descriptor for the variable.
3052 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3053 StringRef Name = VD->getName();
3054 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3055 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3056 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3057 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3058 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3059 }
3060 // Do not use DIGlobalVariable for enums.
3061 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3062 return;
David Blaikiebd483762013-05-20 04:58:53 +00003063 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 getLineNumber(VD->getLocation()),
Eric Christopher91a31902013-01-16 01:22:32 +00003065 Ty, true, Init,
3066 getStaticDataMemberDeclaration(VD));
David Blaikiebd483762013-05-20 04:58:53 +00003067 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3068}
3069
3070llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3071 if (!LexicalBlockStack.empty())
3072 return llvm::DIScope(LexicalBlockStack.back());
3073 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003074}
3075
David Blaikie9f88fe82013-04-22 06:13:21 +00003076void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003077 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3078 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003079 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003080 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3081 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003082 getLineNumber(UD.getLocation()));
3083}
3084
David Blaikiebd483762013-05-20 04:58:53 +00003085void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3086 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3087 return;
3088 assert(UD.shadow_size() &&
3089 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3090 // Emitting one decl is sufficient - debuggers can detect that this is an
3091 // overloaded name & provide lookup for all the overloads.
3092 const UsingShadowDecl &USD = **UD.shadow_begin();
3093 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3094 DBuilder.createImportedDeclaration(
3095 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3096 getLineNumber(USD.getLocation()));
3097}
3098
David Blaikief121b932013-05-20 22:50:41 +00003099llvm::DIImportedEntity
3100CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3101 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3102 return llvm::DIImportedEntity(0);
3103 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3104 if (VH)
3105 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3106 llvm::DIImportedEntity R(0);
3107 if (const NamespaceAliasDecl *Underlying =
3108 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3109 // This could cache & dedup here rather than relying on metadata deduping.
3110 R = DBuilder.createImportedModule(
3111 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3112 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3113 NA.getName());
3114 else
3115 R = DBuilder.createImportedModule(
3116 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3117 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3118 getLineNumber(NA.getLocation()), NA.getName());
3119 VH = R;
3120 return R;
3121}
3122
Guy Benyei11169dd2012-12-18 14:30:41 +00003123/// getOrCreateNamesSpace - Return namespace descriptor for the given
3124/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003125llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003126CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00003127 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 NameSpaceCache.find(NSDecl);
3129 if (I != NameSpaceCache.end())
3130 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3133 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003134 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3136 llvm::DINameSpace NS =
3137 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3138 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3139 return NS;
3140}
3141
3142void CGDebugInfo::finalize() {
3143 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3144 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3145 llvm::DIType Ty, RepTy;
3146 // Verify that the debug info still exists.
3147 if (llvm::Value *V = VI->second)
3148 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003149
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3151 TypeCache.find(VI->first);
3152 if (it != TypeCache.end()) {
3153 // Verify that the debug info still exists.
3154 if (llvm::Value *V = it->second)
3155 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3156 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003157
Adrian Prantl0f6df002013-03-29 19:20:35 +00003158 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003161
3162 // We keep our own list of retained types, because we need to look
3163 // up the final type in the type cache.
3164 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3165 RE = RetainedTypes.end(); RI != RE; ++RI)
3166 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3167
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 DBuilder.finalize();
3169}