blob: 36d869232d63d4556d63e7ac2b3934b5aa864198 [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:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000372 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000373 case BuiltinType::Void:
374 return llvm::DIType();
375 case BuiltinType::ObjCClass:
Manman Ren0d441f12013-07-02 19:01:53 +0000376 if (ClassTy.isType())
Guy Benyei11169dd2012-12-18 14:30:41 +0000377 return ClassTy;
378 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
379 "objc_class", TheCU,
380 getOrCreateMainFile(), 0);
381 return ClassTy;
382 case BuiltinType::ObjCId: {
383 // typedef struct objc_class *Class;
384 // typedef struct objc_object {
385 // Class isa;
386 // } *id;
387
Manman Ren0d441f12013-07-02 19:01:53 +0000388 if (ObjTy.isCompositeType())
Guy Benyei11169dd2012-12-18 14:30:41 +0000389 return ObjTy;
390
Manman Ren0d441f12013-07-02 19:01:53 +0000391 if (!ClassTy.isType())
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
393 "objc_class", TheCU,
394 getOrCreateMainFile(), 0);
395
396 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000397
Guy Benyei11169dd2012-12-18 14:30:41 +0000398 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
399
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000400 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000401 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
402 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000403
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000404 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
405 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000406 return ObjTy;
407 }
408 case BuiltinType::ObjCSel: {
Manman Ren0d441f12013-07-02 19:01:53 +0000409 if (SelTy.isType())
Guy Benyei11169dd2012-12-18 14:30:41 +0000410 return SelTy;
411 SelTy =
412 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413 "objc_selector", TheCU, getOrCreateMainFile(),
414 0);
415 return SelTy;
416 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000417
418 case BuiltinType::OCLImage1d:
419 return getOrCreateStructPtrType("opencl_image1d_t",
420 OCLImage1dDITy);
421 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000422 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000423 OCLImage1dArrayDITy);
424 case BuiltinType::OCLImage1dBuffer:
425 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
426 OCLImage1dBufferDITy);
427 case BuiltinType::OCLImage2d:
428 return getOrCreateStructPtrType("opencl_image2d_t",
429 OCLImage2dDITy);
430 case BuiltinType::OCLImage2dArray:
431 return getOrCreateStructPtrType("opencl_image2d_array_t",
432 OCLImage2dArrayDITy);
433 case BuiltinType::OCLImage3d:
434 return getOrCreateStructPtrType("opencl_image3d_t",
435 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000436 case BuiltinType::OCLSampler:
437 return DBuilder.createBasicType("opencl_sampler_t",
438 CGM.getContext().getTypeSize(BT),
439 CGM.getContext().getTypeAlign(BT),
440 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000441 case BuiltinType::OCLEvent:
442 return getOrCreateStructPtrType("opencl_event_t",
443 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000444
Guy Benyei11169dd2012-12-18 14:30:41 +0000445 case BuiltinType::UChar:
446 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
447 case BuiltinType::Char_S:
448 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
449 case BuiltinType::Char16:
450 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
451 case BuiltinType::UShort:
452 case BuiltinType::UInt:
453 case BuiltinType::UInt128:
454 case BuiltinType::ULong:
455 case BuiltinType::WChar_U:
456 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
457 case BuiltinType::Short:
458 case BuiltinType::Int:
459 case BuiltinType::Int128:
460 case BuiltinType::Long:
461 case BuiltinType::WChar_S:
462 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
463 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
464 case BuiltinType::Half:
465 case BuiltinType::Float:
466 case BuiltinType::LongDouble:
467 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
468 }
469
470 switch (BT->getKind()) {
471 case BuiltinType::Long: BTName = "long int"; break;
472 case BuiltinType::LongLong: BTName = "long long int"; break;
473 case BuiltinType::ULong: BTName = "long unsigned int"; break;
474 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
475 default:
476 BTName = BT->getName(CGM.getLangOpts());
477 break;
478 }
479 // Bit size, align and offset of the type.
480 uint64_t Size = CGM.getContext().getTypeSize(BT);
481 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000482 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000483 DBuilder.createBasicType(BTName, Size, Align, Encoding);
484 return DbgTy;
485}
486
487llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
488 // Bit size, align and offset of the type.
489 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
490 if (Ty->isComplexIntegerType())
491 Encoding = llvm::dwarf::DW_ATE_lo_user;
492
493 uint64_t Size = CGM.getContext().getTypeSize(Ty);
494 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000495 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000496 DBuilder.createBasicType("complex", Size, Align, Encoding);
497
498 return DbgTy;
499}
500
501/// CreateCVRType - Get the qualified type from the cache or create
502/// a new one if necessary.
Eric Christopher1ecc5632013-06-07 22:54:39 +0000503llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
504 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
Eric Christopher1ecc5632013-06-07 22:54:39 +0000530 llvm::DIType FromTy =
531 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +0000532
533 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
534 // CVR derived types.
535 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000536
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 return DbgTy;
538}
539
540llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
541 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000542
543 // The frontend treats 'id' as a typedef to an ObjCObjectType,
544 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
545 // debug info, we want to emit 'id' in both cases.
546 if (Ty->isObjCQualifiedIdType())
547 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
548
Guy Benyei11169dd2012-12-18 14:30:41 +0000549 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000550 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000551 Ty->getPointeeType(), Unit);
552 return DbgTy;
553}
554
555llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
556 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000557 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000558 Ty->getPointeeType(), Unit);
559}
560
561// Creates a forward declaration for a RecordDecl in the given context.
562llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
563 llvm::DIDescriptor Ctx) {
564 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
565 unsigned Line = getLineNumber(RD->getLocation());
566 StringRef RDName = getClassName(RD);
567
568 unsigned Tag = 0;
569 if (RD->isStruct() || RD->isInterface())
570 Tag = llvm::dwarf::DW_TAG_structure_type;
571 else if (RD->isUnion())
572 Tag = llvm::dwarf::DW_TAG_union_type;
573 else {
574 assert(RD->isClass());
575 Tag = llvm::dwarf::DW_TAG_class_type;
576 }
577
578 // Create the type.
579 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
580}
581
582// Walk up the context chain and create forward decls for record decls,
583// and normal descriptors for namespaces.
584llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
585 if (!Context)
586 return TheCU;
587
588 // See if we already have the parent.
589 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
590 I = RegionMap.find(Context);
591 if (I != RegionMap.end()) {
592 llvm::Value *V = I->second;
593 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
594 }
Eric Christopherb2a008c2013-05-16 00:45:12 +0000595
Guy Benyei11169dd2012-12-18 14:30:41 +0000596 // Check namespace.
597 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
598 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
599
600 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
601 if (!RD->isDependentType()) {
Eric Christopher0fdcb312013-05-16 00:52:20 +0000602 llvm::DIType Ty =
603 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
604 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 return llvm::DIDescriptor(Ty);
606 }
607 }
608 return TheCU;
609}
610
David Blaikie4583bea2013-05-24 21:33:22 +0000611/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei11169dd2012-12-18 14:30:41 +0000612/// then emit record's fwd if debug info size reduction is enabled.
David Blaikie4583bea2013-05-24 21:33:22 +0000613llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
614 llvm::DIFile Unit) {
David Blaikiebd483762013-05-20 04:58:53 +0000615 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000616 return getOrCreateType(PointeeTy, Unit);
David Blaikiee36464c2013-06-05 05:32:23 +0000617 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei11169dd2012-12-18 14:30:41 +0000618}
619
620llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000621 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000622 QualType PointeeTy,
623 llvm::DIFile Unit) {
624 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
625 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie4583bea2013-05-24 21:33:22 +0000626 return DBuilder.createReferenceType(
627 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000628
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 // Bit size, align and offset of the type.
630 // Size is always the size of a pointer. We can't use getTypeSize here
631 // because that does not return the correct value for references.
632 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000633 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000634 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
635
David Blaikie4583bea2013-05-24 21:33:22 +0000636 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 Size, Align);
638}
639
Eric Christopher0fdcb312013-05-16 00:52:20 +0000640llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
641 llvm::DIType &Cache) {
Manman Ren0d441f12013-07-02 19:01:53 +0000642 if (Cache.isType())
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000643 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000644 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
645 TheCU, getOrCreateMainFile(), 0);
646 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
647 Cache = DBuilder.createPointerType(Cache, Size);
648 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000649}
650
Guy Benyei11169dd2012-12-18 14:30:41 +0000651llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
652 llvm::DIFile Unit) {
653 if (BlockLiteralGenericSet)
654 return BlockLiteralGeneric;
655
656 SmallVector<llvm::Value *, 8> EltTys;
657 llvm::DIType FieldTy;
658 QualType FType;
659 uint64_t FieldSize, FieldOffset;
660 unsigned FieldAlign;
661 llvm::DIArray Elements;
662 llvm::DIType EltTy, DescTy;
663
664 FieldOffset = 0;
665 FType = CGM.getContext().UnsignedLongTy;
666 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
667 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
668
669 Elements = DBuilder.getOrCreateArray(EltTys);
670 EltTys.clear();
671
672 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
673 unsigned LineNo = getLineNumber(CurLoc);
674
675 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
676 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000677 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000678
679 // Bit size, align and offset of the type.
680 uint64_t Size = CGM.getContext().getTypeSize(Ty);
681
682 DescTy = DBuilder.createPointerType(EltTy, Size);
683
684 FieldOffset = 0;
685 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
686 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
687 FType = CGM.getContext().IntTy;
688 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
689 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
690 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
691 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
692
693 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
694 FieldTy = DescTy;
695 FieldSize = CGM.getContext().getTypeSize(Ty);
696 FieldAlign = CGM.getContext().getTypeAlign(Ty);
697 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
698 LineNo, FieldSize, FieldAlign,
699 FieldOffset, 0, FieldTy);
700 EltTys.push_back(FieldTy);
701
702 FieldOffset += FieldSize;
703 Elements = DBuilder.getOrCreateArray(EltTys);
704
705 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
706 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000707 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000708
709 BlockLiteralGenericSet = true;
710 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
711 return BlockLiteralGeneric;
712}
713
David Blaikiee36464c2013-06-05 05:32:23 +0000714llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
715 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000716 // Typedefs are derived from some other type. If we have a typedef of a
717 // typedef, make sure to emit the whole chain.
David Blaikie4583bea2013-05-24 21:33:22 +0000718 llvm::DIType Src =
David Blaikiee36464c2013-06-05 05:32:23 +0000719 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Manman Ren0d441f12013-07-02 19:01:53 +0000720 if (!Src.isType())
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return llvm::DIType();
722 // We don't set size information, but do specify where the typedef was
723 // declared.
724 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
725 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000726
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 llvm::DIDescriptor TypedefContext =
728 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000729
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 return
731 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
732}
733
734llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
735 llvm::DIFile Unit) {
736 SmallVector<llvm::Value *, 16> EltTys;
737
738 // Add the result type at least.
739 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
740
741 // Set up remainder of arguments if there is a prototype.
742 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
743 if (isa<FunctionNoProtoType>(Ty))
744 EltTys.push_back(DBuilder.createUnspecifiedParameter());
745 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
746 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
747 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
748 }
749
750 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
751 return DBuilder.createSubroutineType(Unit, EltTypeArray);
752}
753
754
Guy Benyei11169dd2012-12-18 14:30:41 +0000755llvm::DIType CGDebugInfo::createFieldType(StringRef name,
756 QualType type,
757 uint64_t sizeInBitsOverride,
758 SourceLocation loc,
759 AccessSpecifier AS,
760 uint64_t offsetInBits,
761 llvm::DIFile tunit,
762 llvm::DIDescriptor scope) {
763 llvm::DIType debugType = getOrCreateType(type, tunit);
764
765 // Get the location for the field.
766 llvm::DIFile file = getOrCreateFile(loc);
767 unsigned line = getLineNumber(loc);
768
769 uint64_t sizeInBits = 0;
770 unsigned alignInBits = 0;
771 if (!type->isIncompleteArrayType()) {
772 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
773
774 if (sizeInBitsOverride)
775 sizeInBits = sizeInBitsOverride;
776 }
777
778 unsigned flags = 0;
779 if (AS == clang::AS_private)
780 flags |= llvm::DIDescriptor::FlagPrivate;
781 else if (AS == clang::AS_protected)
782 flags |= llvm::DIDescriptor::FlagProtected;
783
784 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
785 alignInBits, offsetInBits, flags, debugType);
786}
787
Eric Christopher91a31902013-01-16 01:22:32 +0000788/// CollectRecordLambdaFields - Helper for CollectRecordFields.
789void CGDebugInfo::
790CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
791 SmallVectorImpl<llvm::Value *> &elements,
792 llvm::DIType RecordTy) {
793 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
794 // has the name and the location of the variable so we should iterate over
795 // both concurrently.
796 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
797 RecordDecl::field_iterator Field = CXXDecl->field_begin();
798 unsigned fieldno = 0;
799 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
800 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
801 const LambdaExpr::Capture C = *I;
802 if (C.capturesVariable()) {
803 VarDecl *V = C.getCapturedVar();
804 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
805 StringRef VName = V->getName();
806 uint64_t SizeInBitsOverride = 0;
807 if (Field->isBitField()) {
808 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
809 assert(SizeInBitsOverride && "found named 0-width bitfield");
810 }
811 llvm::DIType fieldType
812 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
813 C.getLocation(), Field->getAccess(),
814 layout.getFieldOffset(fieldno), VUnit, RecordTy);
815 elements.push_back(fieldType);
816 } else {
817 // TODO: Need to handle 'this' in some way by probably renaming the
818 // this of the lambda class and having a field member of 'this' or
819 // by using AT_object_pointer for the function and having that be
820 // used as 'this' for semantic references.
821 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
822 FieldDecl *f = *Field;
823 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
824 QualType type = f->getType();
825 llvm::DIType fieldType
826 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
827 layout.getFieldOffset(fieldno), VUnit, RecordTy);
828
829 elements.push_back(fieldType);
830 }
831 }
832}
833
834/// CollectRecordStaticField - Helper for CollectRecordFields.
835void CGDebugInfo::
836CollectRecordStaticField(const VarDecl *Var,
837 SmallVectorImpl<llvm::Value *> &elements,
838 llvm::DIType RecordTy) {
839 // Create the descriptor for the static variable, with or without
840 // constant initializers.
841 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
842 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
843
844 // Do not describe enums as static members.
845 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
846 return;
847
848 unsigned LineNumber = getLineNumber(Var->getLocation());
849 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000850 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000851 if (Var->getInit()) {
852 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000853 if (Value) {
854 if (Value->isInt())
855 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
856 if (Value->isFloat())
857 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
858 }
Eric Christopher91a31902013-01-16 01:22:32 +0000859 }
860
861 unsigned Flags = 0;
862 AccessSpecifier Access = Var->getAccess();
863 if (Access == clang::AS_private)
864 Flags |= llvm::DIDescriptor::FlagPrivate;
865 else if (Access == clang::AS_protected)
866 Flags |= llvm::DIDescriptor::FlagProtected;
867
868 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikied42917f2013-01-20 01:19:17 +0000869 LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000870 elements.push_back(GV);
871 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
872}
873
874/// CollectRecordNormalField - Helper for CollectRecordFields.
875void CGDebugInfo::
876CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
877 llvm::DIFile tunit,
878 SmallVectorImpl<llvm::Value *> &elements,
879 llvm::DIType RecordTy) {
880 StringRef name = field->getName();
881 QualType type = field->getType();
882
883 // Ignore unnamed fields unless they're anonymous structs/unions.
884 if (name.empty() && !type->isRecordType())
885 return;
886
887 uint64_t SizeInBitsOverride = 0;
888 if (field->isBitField()) {
889 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
890 assert(SizeInBitsOverride && "found named 0-width bitfield");
891 }
892
893 llvm::DIType fieldType
894 = createFieldType(name, type, SizeInBitsOverride,
895 field->getLocation(), field->getAccess(),
896 OffsetInBits, tunit, RecordTy);
897
898 elements.push_back(fieldType);
899}
900
Guy Benyei11169dd2012-12-18 14:30:41 +0000901/// CollectRecordFields - A helper function to collect debug info for
902/// record fields. This is used while creating debug info entry for a Record.
903void CGDebugInfo::
904CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
905 SmallVectorImpl<llvm::Value *> &elements,
906 llvm::DIType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
908
Eric Christopher91a31902013-01-16 01:22:32 +0000909 if (CXXDecl && CXXDecl->isLambda())
910 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
911 else {
912 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000913
Eric Christopher91a31902013-01-16 01:22:32 +0000914 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000915 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000916
Eric Christopher91a31902013-01-16 01:22:32 +0000917 // Static and non-static members should appear in the same order as
918 // the corresponding declarations in the source program.
919 for (RecordDecl::decl_iterator I = record->decls_begin(),
920 E = record->decls_end(); I != E; ++I)
921 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
922 CollectRecordStaticField(V, elements, RecordTy);
923 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000924 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
925 tunit, elements, RecordTy);
926
927 // Bump field number for next field.
928 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000929 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 }
931}
932
933/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
934/// function type is not updated to include implicit "this" pointer. Use this
935/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000936llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000937CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
938 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000939 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000940 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000941 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000942 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
943 Func, Unit);
944}
David Blaikie2aaf0652013-01-07 22:24:59 +0000945
David Blaikie469f0792013-05-22 23:22:42 +0000946llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000947 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000949 llvm::DIArray Args = llvm::DICompositeType(
950 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 assert (Args.getNumElements() && "Invalid number of arguments!");
952
953 SmallVector<llvm::Value *, 16> Elts;
954
955 // First element is always return type. For 'void' functions it is NULL.
956 Elts.push_back(Args.getElement(0));
957
David Blaikie2aaf0652013-01-07 22:24:59 +0000958 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000959 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000960 if (isa<ClassTemplateSpecializationDecl>(RD)) {
961 // Create pointer type directly in this case.
962 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
963 QualType PointeeTy = ThisPtrTy->getPointeeType();
964 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000965 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000966 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
967 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000968 llvm::DIType ThisPtrType =
969 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000970 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
971 // TODO: This and the artificial type below are misleading, the
972 // types aren't artificial the argument is, but the current
973 // metadata doesn't represent that.
974 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
975 Elts.push_back(ThisPtrType);
976 } else {
977 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
978 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
979 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
980 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 }
982
983 // Copy rest of the arguments.
984 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
985 Elts.push_back(Args.getElement(i));
986
987 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
988
989 return DBuilder.createSubroutineType(Unit, EltTypeArray);
990}
991
Eric Christopherb2a008c2013-05-16 00:45:12 +0000992/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +0000993/// inside a function.
994static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
995 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
996 return isFunctionLocalClass(NRD);
997 if (isa<FunctionDecl>(RD->getDeclContext()))
998 return true;
999 return false;
1000}
1001
1002/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1003/// a single member function GlobalDecl.
1004llvm::DISubprogram
1005CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1006 llvm::DIFile Unit,
1007 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001008 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001010
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001012 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001013
1014 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1015 // make sense to give a single ctor/dtor a linkage name.
1016 StringRef MethodLinkageName;
1017 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1018 MethodLinkageName = CGM.getMangledName(Method);
1019
1020 // Get the location for the method.
1021 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1022 unsigned MethodLine = getLineNumber(Method->getLocation());
1023
1024 // Collect virtual method info.
1025 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001026 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001028
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 if (Method->isVirtual()) {
1030 if (Method->isPure())
1031 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1032 else
1033 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001034
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 // It doesn't make sense to give a virtual destructor a vtable index,
1036 // since a single destructor has two entries in the vtable.
1037 if (!isa<CXXDestructorDecl>(Method))
1038 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1039 ContainingType = RecordTy;
1040 }
1041
1042 unsigned Flags = 0;
1043 if (Method->isImplicit())
1044 Flags |= llvm::DIDescriptor::FlagArtificial;
1045 AccessSpecifier Access = Method->getAccess();
1046 if (Access == clang::AS_private)
1047 Flags |= llvm::DIDescriptor::FlagPrivate;
1048 else if (Access == clang::AS_protected)
1049 Flags |= llvm::DIDescriptor::FlagProtected;
1050 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1051 if (CXXC->isExplicit())
1052 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001053 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001054 dyn_cast<CXXConversionDecl>(Method)) {
1055 if (CXXC->isExplicit())
1056 Flags |= llvm::DIDescriptor::FlagExplicit;
1057 }
1058 if (Method->hasPrototype())
1059 Flags |= llvm::DIDescriptor::FlagPrototyped;
1060
1061 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1062 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001063 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001064 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001065 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 /* isDefinition=*/ false,
1067 Virtuality, VIndex, ContainingType,
1068 Flags, CGM.getLangOpts().Optimize, NULL,
1069 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001070
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1072
1073 return SP;
1074}
1075
1076/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001077/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001078/// a Record.
1079void CGDebugInfo::
1080CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1081 SmallVectorImpl<llvm::Value *> &EltTys,
1082 llvm::DIType RecordTy) {
1083
1084 // Since we want more than just the individual member decls if we
1085 // have templated functions iterate over every declaration to gather
1086 // the functions.
1087 for(DeclContext::decl_iterator I = RD->decls_begin(),
1088 E = RD->decls_end(); I != E; ++I) {
1089 Decl *D = *I;
1090 if (D->isImplicit() && !D->isUsed())
1091 continue;
1092
1093 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1094 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1095 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1096 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1097 SE = FTD->spec_end(); SI != SE; ++SI)
1098 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1099 RecordTy));
1100 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001101}
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
1103/// CollectCXXFriends - A helper function to collect debug info for
1104/// C++ base classes. This is used while creating debug info entry for
1105/// a Record.
1106void CGDebugInfo::
1107CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1108 SmallVectorImpl<llvm::Value *> &EltTys,
1109 llvm::DIType RecordTy) {
1110 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1111 BE = RD->friend_end(); BI != BE; ++BI) {
1112 if ((*BI)->isUnsupportedFriend())
1113 continue;
1114 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopherb2a008c2013-05-16 00:45:12 +00001115 EltTys.push_back(DBuilder.createFriend(RecordTy,
1116 getOrCreateType(TInfo->getType(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 Unit)));
1118 }
1119}
1120
1121/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001122/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001123/// a Record.
1124void CGDebugInfo::
1125CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1126 SmallVectorImpl<llvm::Value *> &EltTys,
1127 llvm::DIType RecordTy) {
1128
1129 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1130 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1131 BE = RD->bases_end(); BI != BE; ++BI) {
1132 unsigned BFlags = 0;
1133 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001134
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 const CXXRecordDecl *Base =
1136 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001137
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 if (BI->isVirtual()) {
1139 // virtual base offset offset is -ve. The code generator emits dwarf
1140 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001141 BaseOffset =
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 0 - CGM.getVTableContext()
1143 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1144 BFlags = llvm::DIDescriptor::FlagVirtual;
1145 } else
1146 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1147 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1148 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 AccessSpecifier Access = BI->getAccessSpecifier();
1151 if (Access == clang::AS_private)
1152 BFlags |= llvm::DIDescriptor::FlagPrivate;
1153 else if (Access == clang::AS_protected)
1154 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001155
1156 llvm::DIType DTy =
1157 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 getOrCreateType(BI->getType(), Unit),
1159 BaseOffset, BFlags);
1160 EltTys.push_back(DTy);
1161 }
1162}
1163
1164/// CollectTemplateParams - A helper function to collect template parameters.
1165llvm::DIArray CGDebugInfo::
1166CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001167 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001169 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1171 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001172 StringRef Name;
1173 if (TPList)
1174 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001175 switch (TA.getKind()) {
1176 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1178 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001179 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001181 } break;
1182 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1184 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001185 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001186 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001187 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1188 TemplateParams.push_back(TVP);
1189 } break;
1190 case TemplateArgument::Declaration: {
1191 const ValueDecl *D = TA.getAsDecl();
1192 bool InstanceMember = D->isCXXInstanceMember();
1193 QualType T = InstanceMember
1194 ? CGM.getContext().getMemberPointerType(
1195 D->getType(), cast<RecordDecl>(D->getDeclContext())
1196 ->getTypeForDecl())
1197 : CGM.getContext().getPointerType(D->getType());
1198 llvm::DIType TTy = getOrCreateType(T, Unit);
1199 llvm::Value *V = 0;
1200 // Variable pointer template parameters have a value that is the address
1201 // of the variable.
1202 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1203 V = CGM.GetAddrOfGlobalVar(VD);
1204 // Member function pointers have special support for building them, though
1205 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001206 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001207 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1208 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001209 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1210 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001211 // Member data pointers have special handling too to compute the fixed
1212 // offset within the object.
1213 if (isa<FieldDecl>(D)) {
1214 // These five lines (& possibly the above member function pointer
1215 // handling) might be able to be refactored to use similar code in
1216 // CodeGenModule::getMemberPointerConstant
1217 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1218 CharUnits chars =
1219 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1220 V = CGM.getCXXABI().EmitMemberDataPointer(
1221 cast<MemberPointerType>(T.getTypePtr()), chars);
1222 }
1223 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001224 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001225 TemplateParams.push_back(TVP);
1226 } break;
1227 case TemplateArgument::NullPtr: {
1228 QualType T = TA.getNullPtrType();
1229 llvm::DIType TTy = getOrCreateType(T, Unit);
1230 llvm::Value *V = 0;
1231 // Special case member data pointer null values since they're actually -1
1232 // instead of zero.
1233 if (const MemberPointerType *MPT =
1234 dyn_cast<MemberPointerType>(T.getTypePtr()))
1235 // But treat member function pointers as simple zero integers because
1236 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1237 // CodeGen grows handling for values of non-null member function
1238 // pointers then perhaps we could remove this special case and rely on
1239 // EmitNullMemberPointer for member function pointers.
1240 if (MPT->isMemberDataPointer())
1241 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1242 if (!V)
1243 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1244 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001245 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001246 TemplateParams.push_back(TVP);
1247 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001248 case TemplateArgument::Template: {
1249 llvm::DITemplateValueParameter TVP =
1250 DBuilder.createTemplateTemplateParameter(
1251 TheCU, Name, llvm::DIType(),
1252 TA.getAsTemplate().getAsTemplateDecl()
1253 ->getQualifiedNameAsString());
1254 TemplateParams.push_back(TVP);
1255 } break;
1256 case TemplateArgument::Pack: {
1257 llvm::DITemplateValueParameter TVP =
1258 DBuilder.createTemplateParameterPack(
1259 TheCU, Name, llvm::DIType(),
1260 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1261 TemplateParams.push_back(TVP);
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();
David Blaikie47c11502013-06-22 18:59:18 +00001283 return CollectTemplateParams(
1284 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001285 }
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();
David Blaikie47c11502013-06-22 18:59:18 +00001302 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001303}
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();
Adrian Prantl1f56b2a2013-06-18 23:32:21 +00001380 // Limited debug info should only remove struct definitions that can
1381 // safely be replaced by a forward declaration in the source code.
David Blaikie48ad6dc2013-07-13 21:08:14 +00001382 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
1383 !RD->isCompleteDefinitionRequired()) {
Adrian Prantl1f56b2a2013-06-18 23:32:21 +00001384 // FIXME: This implementation is problematic; there are some test
1385 // cases where we violate the above principle, such as
1386 // test/CodeGen/debug-info-records.c .
David Blaikiee36464c2013-06-05 05:32:23 +00001387 llvm::DIDescriptor FDContext =
1388 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1389 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1390 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1391 return RetTy;
1392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
1394 // Get overall information about the record type for the debug info.
1395 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1396
1397 // Records and classes and unions can all be recursive. To handle them, we
1398 // first generate a debug descriptor for the struct as a forward declaration.
1399 // Then (if it is a definition) we go through and get debug info for all of
1400 // its members. Finally, we create a descriptor for the complete type (which
1401 // may refer to the forward decl if the struct is recursive) and replace all
1402 // uses of the forward declaration with the final definition.
1403
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001404 llvm::DICompositeType FwdDecl(
1405 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001406 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001407 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001408
1409 if (FwdDecl.isForwardDecl())
1410 return FwdDecl;
1411
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001413 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1415
Adrian Prantla03a85a2013-03-06 22:03:30 +00001416 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1418
1419 // Convert all the elements.
1420 SmallVector<llvm::Value *, 16> EltTys;
1421
1422 // Note: The split of CXXDecl information here is intentional, the
1423 // gdb tests will depend on a certain ordering at printout. The debug
1424 // information offsets are still correct if we merge them all together
1425 // though.
1426 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1427 if (CXXDecl) {
1428 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1429 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1430 }
1431
Eric Christopher91a31902013-01-16 01:22:32 +00001432 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1434 llvm::DIArray TParamsArray;
1435 if (CXXDecl) {
1436 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1437 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1438 if (const ClassTemplateSpecializationDecl *TSpecial
1439 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1440 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1441 }
1442
1443 LexicalBlockStack.pop_back();
1444 RegionMap.erase(Ty->getDecl());
1445
1446 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001447 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001449 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1450 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001451}
1452
1453/// CreateType - get objective-c object type.
1454llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1455 llvm::DIFile Unit) {
1456 // Ignore protocols.
1457 return getOrCreateType(Ty->getBaseType(), Unit);
1458}
1459
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001460
1461/// \return true if Getter has the default name for the property PD.
1462static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1463 const ObjCMethodDecl *Getter) {
1464 assert(PD);
1465 if (!Getter)
1466 return true;
1467
1468 assert(Getter->getDeclName().isObjCZeroArgSelector());
1469 return PD->getName() ==
1470 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1471}
1472
1473/// \return true if Setter has the default name for the property PD.
1474static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1475 const ObjCMethodDecl *Setter) {
1476 assert(PD);
1477 if (!Setter)
1478 return true;
1479
1480 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001481 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001482 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1483}
1484
Guy Benyei11169dd2012-12-18 14:30:41 +00001485/// CreateType - get objective-c interface type.
1486llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1487 llvm::DIFile Unit) {
1488 ObjCInterfaceDecl *ID = Ty->getDecl();
1489 if (!ID)
1490 return llvm::DIType();
1491
1492 // Get overall information about the record type for the debug info.
1493 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1494 unsigned Line = getLineNumber(ID->getLocation());
1495 unsigned RuntimeLang = TheCU.getLanguage();
1496
1497 // If this is just a forward declaration return a special forward-declaration
1498 // debug type since we won't be able to lay out the entire type.
1499 ObjCInterfaceDecl *Def = ID->getDefinition();
1500 if (!Def) {
1501 llvm::DIType FwdDecl =
1502 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001503 ID->getName(), TheCU, DefUnit, Line,
1504 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 return FwdDecl;
1506 }
1507
1508 ID = Def;
1509
1510 // Bit size, align and offset of the type.
1511 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1512 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1513
1514 unsigned Flags = 0;
1515 if (ID->getImplementation())
1516 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1517
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001518 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1520 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001521 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001522
1523 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1524 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001525 QualType QualTy = QualType(Ty, 0);
1526 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001527
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001528 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001529 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1531
1532 // Convert all the elements.
1533 SmallVector<llvm::Value *, 16> EltTys;
1534
1535 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1536 if (SClass) {
1537 llvm::DIType SClassTy =
1538 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1539 if (!SClassTy.isValid())
1540 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001541
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 llvm::DIType InhTag =
1543 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1544 EltTys.push_back(InhTag);
1545 }
1546
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001547 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1549 E = ID->prop_end(); I != E; ++I) {
1550 const ObjCPropertyDecl *PD = *I;
1551 SourceLocation Loc = PD->getLocation();
1552 llvm::DIFile PUnit = getOrCreateFile(Loc);
1553 unsigned PLine = getLineNumber(Loc);
1554 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1555 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1556 llvm::MDNode *PropertyNode =
1557 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001558 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001559 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001561 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 getSelectorName(PD->getSetterName()),
1563 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001564 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 EltTys.push_back(PropertyNode);
1566 }
1567
1568 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1569 unsigned FieldNo = 0;
1570 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1571 Field = Field->getNextIvar(), ++FieldNo) {
1572 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1573 if (!FieldTy.isValid())
1574 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001575
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 StringRef FieldName = Field->getName();
1577
1578 // Ignore unnamed fields.
1579 if (FieldName.empty())
1580 continue;
1581
1582 // Get the location for the field.
1583 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1584 unsigned FieldLine = getLineNumber(Field->getLocation());
1585 QualType FType = Field->getType();
1586 uint64_t FieldSize = 0;
1587 unsigned FieldAlign = 0;
1588
1589 if (!FType->isIncompleteArrayType()) {
1590
1591 // Bit size, align and offset of the type.
1592 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001593 ? Field->getBitWidthValue(CGM.getContext())
1594 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 FieldAlign = CGM.getContext().getTypeAlign(FType);
1596 }
1597
1598 uint64_t FieldOffset;
1599 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1600 // We don't know the runtime offset of an ivar if we're using the
1601 // non-fragile ABI. For bitfields, use the bit offset into the first
1602 // byte of storage of the bitfield. For other fields, use zero.
1603 if (Field->isBitField()) {
1604 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1605 CGM, ID, Field);
1606 FieldOffset %= CGM.getContext().getCharWidth();
1607 } else {
1608 FieldOffset = 0;
1609 }
1610 } else {
1611 FieldOffset = RL.getFieldOffset(FieldNo);
1612 }
1613
1614 unsigned Flags = 0;
1615 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1616 Flags = llvm::DIDescriptor::FlagProtected;
1617 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1618 Flags = llvm::DIDescriptor::FlagPrivate;
1619
1620 llvm::MDNode *PropertyNode = NULL;
1621 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001622 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1624 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001625 SourceLocation Loc = PD->getLocation();
1626 llvm::DIFile PUnit = getOrCreateFile(Loc);
1627 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1629 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1630 PropertyNode =
1631 DBuilder.createObjCProperty(PD->getName(),
1632 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001633 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001635 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 getSelectorName(PD->getSetterName()),
1637 PD->getPropertyAttributes(),
1638 getOrCreateType(PD->getType(), PUnit));
1639 }
1640 }
1641 }
1642 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1643 FieldLine, FieldSize, FieldAlign,
1644 FieldOffset, Flags, FieldTy,
1645 PropertyNode);
1646 EltTys.push_back(FieldTy);
1647 }
1648
1649 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001650 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001651
1652 // If the implementation is not yet set, we do not want to mark it
1653 // as complete. An implementation may declare additional
1654 // private ivars that we would miss otherwise.
1655 if (ID->getImplementation() == 0)
1656 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001657
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001659 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001660}
1661
1662llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1663 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1664 int64_t Count = Ty->getNumElements();
1665 if (Count == 0)
1666 // If number of elements are not known then this is an unbounded array.
1667 // Use Count == -1 to express such arrays.
1668 Count = -1;
1669
1670 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1671 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1672
1673 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1674 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1675
1676 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1677}
1678
1679llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1680 llvm::DIFile Unit) {
1681 uint64_t Size;
1682 uint64_t Align;
1683
1684 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1685 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1686 Size = 0;
1687 Align =
1688 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1689 } else if (Ty->isIncompleteArrayType()) {
1690 Size = 0;
1691 if (Ty->getElementType()->isIncompleteType())
1692 Align = 0;
1693 else
1694 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001695 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 Size = 0;
1697 Align = 0;
1698 } else {
1699 // Size and align of the whole array, not the element type.
1700 Size = CGM.getContext().getTypeSize(Ty);
1701 Align = CGM.getContext().getTypeAlign(Ty);
1702 }
1703
1704 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1705 // interior arrays, do we care? Why aren't nested arrays represented the
1706 // obvious/recursive way?
1707 SmallVector<llvm::Value *, 8> Subscripts;
1708 QualType EltTy(Ty, 0);
1709 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1710 // If the number of elements is known, then count is that number. Otherwise,
1711 // it's -1. This allows us to represent a subrange with an array of 0
1712 // elements, like this:
1713 //
1714 // struct foo {
1715 // int x[0];
1716 // };
1717 int64_t Count = -1; // Count == -1 is an unbounded array.
1718 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1719 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 // FIXME: Verify this is right for VLAs.
1722 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1723 EltTy = Ty->getElementType();
1724 }
1725
1726 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1727
Eric Christopherb2a008c2013-05-16 00:45:12 +00001728 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1730 SubscriptArray);
1731 return DbgTy;
1732}
1733
Eric Christopherb2a008c2013-05-16 00:45:12 +00001734llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001735 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001736 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001737 Ty, Ty->getPointeeType(), Unit);
1738}
1739
Eric Christopherb2a008c2013-05-16 00:45:12 +00001740llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001742 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 Ty, Ty->getPointeeType(), Unit);
1744}
1745
Eric Christopherb2a008c2013-05-16 00:45:12 +00001746llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001748 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1749 if (!Ty->getPointeeType()->isFunctionType())
1750 return DBuilder.createMemberPointerType(
David Blaikie4583bea2013-05-24 21:33:22 +00001751 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikie2c705ca2013-01-19 19:20:56 +00001752 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1753 CGM.getContext().getPointerType(
1754 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1755 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1756 ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001757}
1758
Eric Christopherb2a008c2013-05-16 00:45:12 +00001759llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 llvm::DIFile U) {
1761 // Ignore the atomic wrapping
1762 // FIXME: What is the correct representation?
1763 return getOrCreateType(Ty->getValueType(), U);
1764}
1765
1766/// CreateEnumType - get enumeration type.
1767llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1768 uint64_t Size = 0;
1769 uint64_t Align = 0;
1770 if (!ED->getTypeForDecl()->isIncompleteType()) {
1771 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1772 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1773 }
1774
1775 // If this is just a forward declaration, construct an appropriately
1776 // marked node and just return it.
1777 if (!ED->getDefinition()) {
1778 llvm::DIDescriptor EDContext;
1779 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1780 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1781 unsigned Line = getLineNumber(ED->getLocation());
1782 StringRef EDName = ED->getName();
1783 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1784 EDName, EDContext, DefUnit, Line, 0,
1785 Size, Align);
1786 }
1787
1788 // Create DIEnumerator elements for each enumerator.
1789 SmallVector<llvm::Value *, 16> Enumerators;
1790 ED = ED->getDefinition();
1791 for (EnumDecl::enumerator_iterator
1792 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1793 Enum != EnumEnd; ++Enum) {
1794 Enumerators.push_back(
1795 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001796 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 }
1798
1799 // Return a CompositeType for the enum itself.
1800 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1801
1802 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1803 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001804 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001806 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001808 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1810 Size, Align, EltArray,
1811 ClassTy);
1812 return DbgTy;
1813}
1814
David Blaikie05491062013-01-21 04:37:12 +00001815static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1816 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 do {
David Blaikie05491062013-01-21 04:37:12 +00001818 Quals += T.getLocalQualifiers();
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 QualType LastT = T;
1820 switch (T->getTypeClass()) {
1821 default:
David Blaikie05491062013-01-21 04:37:12 +00001822 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 case Type::TemplateSpecialization:
1824 T = cast<TemplateSpecializationType>(T)->desugar();
1825 break;
1826 case Type::TypeOfExpr:
1827 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1828 break;
1829 case Type::TypeOf:
1830 T = cast<TypeOfType>(T)->getUnderlyingType();
1831 break;
1832 case Type::Decltype:
1833 T = cast<DecltypeType>(T)->getUnderlyingType();
1834 break;
1835 case Type::UnaryTransform:
1836 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1837 break;
1838 case Type::Attributed:
1839 T = cast<AttributedType>(T)->getEquivalentType();
1840 break;
1841 case Type::Elaborated:
1842 T = cast<ElaboratedType>(T)->getNamedType();
1843 break;
1844 case Type::Paren:
1845 T = cast<ParenType>(T)->getInnerType();
1846 break;
David Blaikie05491062013-01-21 04:37:12 +00001847 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 break;
1850 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001851 QualType DT = cast<AutoType>(T)->getDeducedType();
1852 if (DT.isNull())
1853 return T;
1854 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 break;
1856 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001857
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001859 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 } while (true);
1861}
1862
Eric Christopher0fdcb312013-05-16 00:52:20 +00001863/// getType - Get the type from the cache or return null type if it doesn't
1864/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001865llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1866
1867 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001868 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001869
Guy Benyei11169dd2012-12-18 14:30:41 +00001870 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001871 if (Ty->getTypeClass() == Type::ObjCInterface) {
1872 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1873 if (V)
1874 return llvm::DIType(cast<llvm::MDNode>(V));
1875 else return llvm::DIType();
1876 }
1877
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1879 TypeCache.find(Ty.getAsOpaquePtr());
1880 if (it != TypeCache.end()) {
1881 // Verify that the debug info still exists.
1882 if (llvm::Value *V = it->second)
1883 return llvm::DIType(cast<llvm::MDNode>(V));
1884 }
1885
1886 return llvm::DIType();
1887}
1888
1889/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1890/// doesn't exist.
1891llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1892
1893 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001894 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001895
1896 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001897 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1899 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001900 if (it != CompletedTypeCache.end())
1901 V = it->second;
1902 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00001903 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 }
1905
Adrian Prantla03a85a2013-03-06 22:03:30 +00001906 // Verify that any cached debug info still exists.
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001907 if (V != 0)
1908 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantla03a85a2013-03-06 22:03:30 +00001909
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 return llvm::DIType();
1911}
1912
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001913void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1914 // In limited debug info we only want to do this if the complete type was
1915 // required.
1916 if (DebugKind <= CodeGenOptions::LimitedDebugInfo)
1917 return;
1918
David Blaikief7bcb0c2013-06-21 00:59:44 +00001919 QualType QTy = CGM.getContext().getRecordType(&RD);
1920 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001921
Manman Ren0d441f12013-07-02 19:01:53 +00001922 if (T.isType() && T.isForwardDecl())
David Blaikief7bcb0c2013-06-21 00:59:44 +00001923 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001924}
1925
Adrian Prantl73409ce2013-03-11 18:33:46 +00001926/// getCachedInterfaceTypeOrNull - Get the type from the interface
1927/// cache, unless it needs to regenerated. Otherwise return null.
1928llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1929 // Is there a cached interface that hasn't changed?
1930 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1931 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1932
1933 if (it1 != ObjCInterfaceCache.end())
1934 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1935 if (Checksum(Decl) == it1->second.second)
1936 // Return cached forward declaration.
1937 return it1->second.first;
1938
1939 return 0;
1940}
Guy Benyei11169dd2012-12-18 14:30:41 +00001941
1942/// getOrCreateType - Get the type from the cache or create a new
1943/// one if necessary.
Eric Christopher1ecc5632013-06-07 22:54:39 +00001944llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1945 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001946 if (Ty.isNull())
1947 return llvm::DIType();
1948
1949 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001950 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001951
1952 llvm::DIType T = getCompletedTypeOrNull(Ty);
1953
Manman Ren0d441f12013-07-02 19:01:53 +00001954 if (T.isType()) {
David Blaikie940ca4d2013-06-21 21:03:11 +00001955 // If we're looking for a definition, make sure we have definitions of any
1956 // underlying types.
1957 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1958 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1959 if (Ty.hasLocalQualifiers())
1960 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 return T;
David Blaikie940ca4d2013-06-21 21:03:11 +00001962 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001963
1964 // Otherwise create the type.
David Blaikiee36464c2013-06-05 05:32:23 +00001965 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantl73409ce2013-03-11 18:33:46 +00001966 void* TyPtr = Ty.getAsOpaquePtr();
1967
1968 // And update the type cache.
1969 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00001970
1971 llvm::DIType TC = getTypeOrNull(Ty);
Manman Ren0d441f12013-07-02 19:01:53 +00001972 if (TC.isType() && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00001973 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1974 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1975 // Interface types may have elements added to them by a
1976 // subsequent implementation or extension, so we keep them in
1977 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00001978 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00001979 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00001980 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1981 if (V.first)
1982 return llvm::DIType(cast<llvm::MDNode>(V.first));
1983 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1984 Decl->getName(), TheCU, Unit,
1985 getLineNumber(Decl->getLocation()),
1986 TheCU.getLanguage());
1987 // Store the forward declaration in the cache.
1988 V.first = TC;
1989 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00001990
David Blaikie8e5939b2013-05-21 18:29:40 +00001991 // Register the type for replacement in finalize().
1992 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1993
Adrian Prantl73409ce2013-03-11 18:33:46 +00001994 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00001995 }
1996
Guy Benyei11169dd2012-12-18 14:30:41 +00001997 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00001998 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00001999
2000 return Res;
2001}
2002
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002003/// Currently the checksum of an interface includes the number of
2004/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002005unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002006 // The assumption is that the number of ivars can only increase
2007 // monotonically, so it is safe to just use their current number as
2008 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002009 unsigned Sum = 0;
2010 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2011 Ivar != 0; Ivar = Ivar->getNextIvar())
2012 ++Sum;
2013
2014 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002015}
2016
2017ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2018 switch (Ty->getTypeClass()) {
2019 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002020 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2021 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002022 case Type::ObjCInterface:
2023 return cast<ObjCInterfaceType>(Ty)->getDecl();
2024 default:
2025 return 0;
2026 }
2027}
2028
Guy Benyei11169dd2012-12-18 14:30:41 +00002029/// CreateTypeNode - Create a new debug type node.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002030llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2031 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002032 // Handle qualifiers, which recursively handles what they refer to.
2033 if (Ty.hasLocalQualifiers())
David Blaikiee36464c2013-06-05 05:32:23 +00002034 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002035
2036 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002037
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 // Work out details of type.
2039 switch (Ty->getTypeClass()) {
2040#define TYPE(Class, Base)
2041#define ABSTRACT_TYPE(Class, Base)
2042#define NON_CANONICAL_TYPE(Class, Base)
2043#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2044#include "clang/AST/TypeNodes.def"
2045 llvm_unreachable("Dependent types cannot show up in debug information");
2046
2047 case Type::ExtVector:
2048 case Type::Vector:
2049 return CreateType(cast<VectorType>(Ty), Unit);
2050 case Type::ObjCObjectPointer:
2051 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2052 case Type::ObjCObject:
2053 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2054 case Type::ObjCInterface:
2055 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2056 case Type::Builtin:
2057 return CreateType(cast<BuiltinType>(Ty));
2058 case Type::Complex:
2059 return CreateType(cast<ComplexType>(Ty));
2060 case Type::Pointer:
2061 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner8a365022013-06-24 17:51:48 +00002062 case Type::Decayed:
2063 // Decayed types are just pointers in LLVM and DWARF.
2064 return CreateType(
2065 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 case Type::BlockPointer:
2067 return CreateType(cast<BlockPointerType>(Ty), Unit);
2068 case Type::Typedef:
David Blaikiee36464c2013-06-05 05:32:23 +00002069 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 case Type::Record:
David Blaikiee36464c2013-06-05 05:32:23 +00002071 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 case Type::Enum:
2073 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2074 case Type::FunctionProto:
2075 case Type::FunctionNoProto:
2076 return CreateType(cast<FunctionType>(Ty), Unit);
2077 case Type::ConstantArray:
2078 case Type::VariableArray:
2079 case Type::IncompleteArray:
2080 return CreateType(cast<ArrayType>(Ty), Unit);
2081
2082 case Type::LValueReference:
2083 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2084 case Type::RValueReference:
2085 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2086
2087 case Type::MemberPointer:
2088 return CreateType(cast<MemberPointerType>(Ty), Unit);
2089
2090 case Type::Atomic:
2091 return CreateType(cast<AtomicType>(Ty), Unit);
2092
2093 case Type::Attributed:
2094 case Type::TemplateSpecialization:
2095 case Type::Elaborated:
2096 case Type::Paren:
2097 case Type::SubstTemplateTypeParm:
2098 case Type::TypeOfExpr:
2099 case Type::TypeOf:
2100 case Type::Decltype:
2101 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002102 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002104 case Type::Auto:
2105 Diag = "auto";
2106 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002108
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 assert(Diag && "Fall through without a diagnostic?");
2110 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2111 "debug information for %0 is not yet supported");
2112 CGM.getDiags().Report(DiagID)
2113 << Diag;
2114 return llvm::DIType();
2115}
2116
2117/// getOrCreateLimitedType - Get the type from the cache or create a new
2118/// limited type if necessary.
2119llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002120 llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 if (Ty.isNull())
2122 return llvm::DIType();
2123
2124 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002125 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002126
2127 llvm::DIType T = getTypeOrNull(Ty);
2128
2129 // We may have cached a forward decl when we could have created
2130 // a non-forward decl. Go ahead and create a non-forward decl
2131 // now.
Manman Ren0d441f12013-07-02 19:01:53 +00002132 if (T.isType() && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002133
2134 // Otherwise create the type.
2135 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2136
Manman Ren0d441f12013-07-02 19:01:53 +00002137 if (T.isType() && T.isForwardDecl())
Guy Benyei11169dd2012-12-18 14:30:41 +00002138 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2139 static_cast<llvm::Value*>(T)));
2140
2141 // And update the type cache.
2142 TypeCache[Ty.getAsOpaquePtr()] = Res;
2143 return Res;
2144}
2145
2146// TODO: Currently used for context chains when limiting debug info.
2147llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2148 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002149
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 // Get overall information about the record type for the debug info.
2151 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2152 unsigned Line = getLineNumber(RD->getLocation());
2153 StringRef RDName = getClassName(RD);
2154
2155 llvm::DIDescriptor RDContext;
Eric Christopher75e17682013-05-16 00:45:23 +00002156 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +00002157 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2158 else
2159 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2160
2161 // If this is just a forward declaration, construct an appropriately
2162 // marked node and just return it.
2163 if (!RD->getDefinition())
2164 return createRecordFwdDecl(RD, RDContext);
2165
2166 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2167 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2168 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie49ae6a72013-03-26 23:47:35 +00002169 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002170
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 if (RD->isUnion())
2172 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002173 Size, Align, 0, llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 else if (RD->isClass()) {
2175 // FIXME: This could be a struct type giving a default visibility different
2176 // than C++ class type, but needs llvm metadata changes first.
2177 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002178 Size, Align, 0, 0, llvm::DIType(),
2179 llvm::DIArray(), llvm::DIType(),
2180 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 } else
2182 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002183 Size, Align, 0, llvm::DIType(),
2184 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002185
2186 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002187 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002188
2189 if (CXXDecl) {
2190 // A class's primary base or the class itself contains the vtable.
David Blaikie49ae6a72013-03-26 23:47:35 +00002191 llvm::DICompositeType ContainingType;
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2193 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2194 // Seek non virtual primary base root.
2195 while (1) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002196 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2197 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2198 if (PBT && !BRL.isPrimaryBaseVirtual())
2199 PBase = PBT;
2200 else
2201 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002202 }
David Blaikie49ae6a72013-03-26 23:47:35 +00002203 ContainingType = llvm::DICompositeType(
2204 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2205 } else if (CXXDecl->isDynamicClass())
Guy Benyei11169dd2012-12-18 14:30:41 +00002206 ContainingType = RealDecl;
2207
David Blaikie49ae6a72013-03-26 23:47:35 +00002208 RealDecl.setContainingType(ContainingType);
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 }
2210 return llvm::DIType(RealDecl);
2211}
2212
2213/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2214/// declare composite types that haven't been processed yet.
2215llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2216
2217 // Work out details of type.
2218 switch (Ty->getTypeClass()) {
2219#define TYPE(Class, Base)
2220#define ABSTRACT_TYPE(Class, Base)
2221#define NON_CANONICAL_TYPE(Class, Base)
2222#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2223 #include "clang/AST/TypeNodes.def"
2224 llvm_unreachable("Dependent types cannot show up in debug information");
2225
2226 case Type::Record:
2227 return CreateLimitedType(cast<RecordType>(Ty));
2228 default:
David Blaikiee36464c2013-06-05 05:32:23 +00002229 return CreateTypeNode(Ty, Unit, false);
Guy Benyei11169dd2012-12-18 14:30:41 +00002230 }
2231}
2232
2233/// CreateMemberType - Create new member and increase Offset by FType's size.
2234llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2235 StringRef Name,
2236 uint64_t *Offset) {
2237 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2238 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2239 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2240 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2241 FieldSize, FieldAlign,
2242 *Offset, 0, FieldTy);
2243 *Offset += FieldSize;
2244 return Ty;
2245}
2246
David Blaikiebd483762013-05-20 04:58:53 +00002247llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2248 // We only need a declaration (not a definition) of the type - so use whatever
2249 // we would otherwise do to get a type for a pointee. (forward declarations in
2250 // limited debug info, full definitions (if the type definition is available)
2251 // in unlimited debug info)
2252 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2253 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikie4583bea2013-05-24 21:33:22 +00002254 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2255 DefUnit);
David Blaikiebd483762013-05-20 04:58:53 +00002256 }
2257 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2258 // This doesn't handle providing declarations (for functions or variables) for
2259 // entities without definitions in this TU, nor when the definition proceeds
2260 // the call to this function.
2261 // FIXME: This should be split out into more specific maps with support for
2262 // emitting forward declarations and merging definitions with declarations,
2263 // the same way as we do for types.
2264 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2265 DeclCache.find(D->getCanonicalDecl());
2266 if (I == DeclCache.end())
2267 return llvm::DIDescriptor();
2268 llvm::Value *V = I->second;
2269 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2270}
2271
Guy Benyei11169dd2012-12-18 14:30:41 +00002272/// getFunctionDeclaration - Return debug info descriptor to describe method
2273/// declaration for the given method definition.
2274llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002275 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2276 return llvm::DISubprogram();
2277
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2279 if (!FD) return llvm::DISubprogram();
2280
2281 // Setup context.
2282 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2283
2284 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2285 MI = SPCache.find(FD->getCanonicalDecl());
2286 if (MI != SPCache.end()) {
2287 llvm::Value *V = MI->second;
2288 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002289 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 return SP;
2291 }
2292
2293 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2294 E = FD->redecls_end(); I != E; ++I) {
2295 const FunctionDecl *NextFD = *I;
2296 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2297 MI = SPCache.find(NextFD->getCanonicalDecl());
2298 if (MI != SPCache.end()) {
2299 llvm::Value *V = MI->second;
2300 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002301 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 return SP;
2303 }
2304 }
2305 return llvm::DISubprogram();
2306}
2307
2308// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2309// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002310llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2311 QualType FnType,
2312 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002313 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2314 // Create fake but valid subroutine type. Otherwise
2315 // llvm::DISubprogram::Verify() would return false, and
2316 // subprogram DIE will miss DW_AT_decl_file and
2317 // DW_AT_decl_line fields.
2318 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002319
2320 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2321 return getOrCreateMethodType(Method, F);
2322 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2323 // Add "self" and "_cmd"
2324 SmallVector<llvm::Value *, 16> Elts;
2325
2326 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl5f360102013-05-22 21:37:49 +00002327 QualType ResultTy = OMethod->getResultType();
2328
2329 // Replace the instancetype keyword with the actual type.
2330 if (ResultTy == CGM.getContext().getObjCInstanceType())
2331 ResultTy = CGM.getContext().getPointerType(
2332 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2333
Adrian Prantl7bec9032013-05-10 21:08:31 +00002334 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002336 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2337 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2338 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002339 // "_cmd" pointer is always second argument.
2340 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2341 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2342 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002343 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 PE = OMethod->param_end(); PI != PE; ++PI)
2345 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2346
2347 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2348 return DBuilder.createSubroutineType(F, EltTypeArray);
2349 }
David Blaikie469f0792013-05-22 23:22:42 +00002350 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002351}
2352
2353/// EmitFunctionStart - Constructs the debug code for entering a function.
2354void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2355 llvm::Function *Fn,
2356 CGBuilderTy &Builder) {
2357
2358 StringRef Name;
2359 StringRef LinkageName;
2360
2361 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2362
2363 const Decl *D = GD.getDecl();
2364 // Function may lack declaration in source code if it is created by Clang
2365 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2366 bool HasDecl = (D != 0);
2367 // Use the location of the declaration.
2368 SourceLocation Loc;
2369 if (HasDecl)
2370 Loc = D->getLocation();
2371
2372 unsigned Flags = 0;
2373 llvm::DIFile Unit = getOrCreateFile(Loc);
2374 llvm::DIDescriptor FDContext(Unit);
2375 llvm::DIArray TParamsArray;
2376 if (!HasDecl) {
2377 // Use llvm function name.
2378 Name = Fn->getName();
2379 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2380 // If there is a DISubprogram for this function available then use it.
2381 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2382 FI = SPCache.find(FD->getCanonicalDecl());
2383 if (FI != SPCache.end()) {
2384 llvm::Value *V = FI->second;
2385 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2386 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2387 llvm::MDNode *SPN = SP;
2388 LexicalBlockStack.push_back(SPN);
2389 RegionMap[D] = llvm::WeakVH(SP);
2390 return;
2391 }
2392 }
2393 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002394 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 if (FD->hasPrototype()) {
2396 LinkageName = CGM.getMangledName(GD);
2397 Flags |= llvm::DIDescriptor::FlagPrototyped;
2398 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002399 // No need to replicate the linkage name if it isn't different from the
2400 // subprogram name, no need to have it at all unless coverage is enabled or
2401 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002403 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2404 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002405 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 LinkageName = StringRef();
2407
Eric Christopher75e17682013-05-16 00:45:23 +00002408 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 if (const NamespaceDecl *NSDecl =
2410 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2411 FDContext = getOrCreateNameSpace(NSDecl);
2412 else if (const RecordDecl *RDecl =
2413 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2414 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2415
2416 // Collect template parameters.
2417 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2418 }
2419 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2420 Name = getObjCMethodName(OMD);
2421 Flags |= llvm::DIDescriptor::FlagPrototyped;
2422 } else {
2423 // Use llvm function name.
2424 Name = Fn->getName();
2425 Flags |= llvm::DIDescriptor::FlagPrototyped;
2426 }
2427 if (!Name.empty() && Name[0] == '\01')
2428 Name = Name.substr(1);
2429
2430 unsigned LineNo = getLineNumber(Loc);
2431 if (!HasDecl || D->isImplicit())
2432 Flags |= llvm::DIDescriptor::FlagArtificial;
2433
David Blaikie18cfbc52013-06-22 00:09:36 +00002434 llvm::DISubprogram SP = DBuilder.createFunction(
2435 FDContext, Name, LinkageName, Unit, LineNo,
2436 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2437 true /*definition*/, getLineNumber(CurLoc), Flags,
2438 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002439 if (HasDecl)
2440 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002441
2442 // Push function on region stack.
2443 llvm::MDNode *SPN = SP;
2444 LexicalBlockStack.push_back(SPN);
2445 if (HasDecl)
2446 RegionMap[D] = llvm::WeakVH(SP);
2447}
2448
2449/// EmitLocation - Emit metadata to indicate a change in line/column
2450/// information in the source file.
Adrian Prantlc7822422013-03-12 20:43:25 +00002451void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2452 bool ForceColumnInfo) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002453
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 // Update our current location
2455 setLocation(Loc);
2456
2457 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2458
2459 // Don't bother if things are the same as last time.
2460 SourceManager &SM = CGM.getContext().getSourceManager();
2461 if (CurLoc == PrevLoc ||
2462 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2463 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002464 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2465 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2466 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002468
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 // Update last state.
2470 PrevLoc = CurLoc;
2471
2472 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002473 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2474 (getLineNumber(CurLoc),
2475 getColumnNumber(CurLoc, ForceColumnInfo),
2476 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002477}
2478
2479/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2480/// the stack.
2481void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2482 llvm::DIDescriptor D =
2483 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2484 llvm::DIDescriptor() :
2485 llvm::DIDescriptor(LexicalBlockStack.back()),
2486 getOrCreateFile(CurLoc),
2487 getLineNumber(CurLoc),
2488 getColumnNumber(CurLoc));
2489 llvm::MDNode *DN = D;
2490 LexicalBlockStack.push_back(DN);
2491}
2492
2493/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2494/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002495void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2496 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 // Set our current location.
2498 setLocation(Loc);
2499
2500 // Create a new lexical block and push it on the stack.
2501 CreateLexicalBlock(Loc);
2502
2503 // Emit a line table change for the current location inside the new scope.
2504 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2505 getColumnNumber(Loc),
2506 LexicalBlockStack.back()));
2507}
2508
2509/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2510/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002511void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2512 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2514
2515 // Provide an entry in the line table for the end of the block.
2516 EmitLocation(Builder, Loc);
2517
2518 LexicalBlockStack.pop_back();
2519}
2520
2521/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2522void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2523 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2524 unsigned RCount = FnBeginRegionCount.back();
2525 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2526
2527 // Pop all regions for this function.
2528 while (LexicalBlockStack.size() != RCount)
2529 EmitLexicalBlockEnd(Builder, CurLoc);
2530 FnBeginRegionCount.pop_back();
2531}
2532
Eric Christopherb2a008c2013-05-16 00:45:12 +00002533// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002534// See BuildByRefType.
2535llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2536 uint64_t *XOffset) {
2537
2538 SmallVector<llvm::Value *, 5> EltTys;
2539 QualType FType;
2540 uint64_t FieldSize, FieldOffset;
2541 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002542
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002544 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002545
2546 FieldOffset = 0;
2547 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2548 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2549 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2550 FType = CGM.getContext().IntTy;
2551 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2552 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2553
2554 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2555 if (HasCopyAndDispose) {
2556 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2557 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2558 &FieldOffset));
2559 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2560 &FieldOffset));
2561 }
2562 bool HasByrefExtendedLayout;
2563 Qualifiers::ObjCLifetime Lifetime;
2564 if (CGM.getContext().getByrefLifetime(Type,
2565 Lifetime, HasByrefExtendedLayout)
2566 && HasByrefExtendedLayout)
2567 EltTys.push_back(CreateMemberType(Unit, FType,
2568 "__byref_variable_layout",
2569 &FieldOffset));
Eric Christopherb2a008c2013-05-16 00:45:12 +00002570
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2572 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002573 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002574 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2576 CharUnits AlignedOffsetInBytes
2577 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2578 CharUnits NumPaddingBytes
2579 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002580
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 if (NumPaddingBytes.isPositive()) {
2582 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2583 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2584 pad, ArrayType::Normal, 0);
2585 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2586 }
2587 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002588
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 FType = Type;
2590 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2591 FieldSize = CGM.getContext().getTypeSize(FType);
2592 FieldAlign = CGM.getContext().toBits(Align);
2593
Eric Christopherb2a008c2013-05-16 00:45:12 +00002594 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2596 0, FieldSize, FieldAlign,
2597 FieldOffset, 0, FieldTy);
2598 EltTys.push_back(FieldTy);
2599 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002600
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002602
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002604
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002606 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002607}
2608
2609/// EmitDeclare - Emit local variable declaration debug info.
2610void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002611 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002613 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2615
2616 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2617 llvm::DIType Ty;
2618 uint64_t XOffset = 0;
2619 if (VD->hasAttr<BlocksAttr>())
2620 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002621 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 Ty = getOrCreateType(VD->getType(), Unit);
2623
2624 // If there is no debug info for this type then do not emit debug info
2625 // for this variable.
2626 if (!Ty)
2627 return;
2628
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 // Get location information.
2630 unsigned Line = getLineNumber(VD->getLocation());
2631 unsigned Column = getColumnNumber(VD->getLocation());
2632 unsigned Flags = 0;
2633 if (VD->isImplicit())
2634 Flags |= llvm::DIDescriptor::FlagArtificial;
2635 // If this is the first argument and it is implicit then
2636 // give it an object pointer flag.
2637 // FIXME: There has to be a better way to do this, but for static
2638 // functions there won't be an implicit param at arg1 and
2639 // otherwise it is 'self' or 'this'.
2640 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2641 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002642 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2643 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && !VD->getType()->isPointerType())
2644 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002645
2646 llvm::MDNode *Scope = LexicalBlockStack.back();
2647
2648 StringRef Name = VD->getName();
2649 if (!Name.empty()) {
2650 if (VD->hasAttr<BlocksAttr>()) {
2651 CharUnits offset = CharUnits::fromQuantity(32);
2652 SmallVector<llvm::Value *, 9> addr;
2653 llvm::Type *Int64Ty = CGM.Int64Ty;
2654 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2655 // offset of __forwarding field
2656 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002657 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2659 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2660 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2661 // offset of x field
2662 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2663 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2664
2665 // Create the descriptor for the variable.
2666 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002667 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 llvm::DIDescriptor(Scope),
2669 VD->getName(), Unit, Line, Ty,
2670 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002671
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 // Insert an llvm.dbg.declare into the current block.
2673 llvm::Instruction *Call =
2674 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2675 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2676 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002678 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2679 // If VD is an anonymous union then Storage represents value for
2680 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002682 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 for (RecordDecl::field_iterator I = RD->field_begin(),
2684 E = RD->field_end();
2685 I != E; ++I) {
2686 FieldDecl *Field = *I;
2687 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2688 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002689
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 // Ignore unnamed fields. Do not ignore unnamed records.
2691 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2692 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002693
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 // Use VarDecl's Tag, Scope and Line number.
2695 llvm::DIVariable D =
2696 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002697 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 CGM.getLangOpts().Optimize, Flags,
2699 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002700
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 // Insert an llvm.dbg.declare into the current block.
2702 llvm::Instruction *Call =
2703 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2704 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2705 }
David Blaikie219c7d92013-01-05 20:03:07 +00002706 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 }
2708 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002709
2710 // Create the descriptor for the variable.
2711 llvm::DIVariable D =
2712 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2713 Name, Unit, Line, Ty,
2714 CGM.getLangOpts().Optimize, Flags, ArgNo);
2715
2716 // Insert an llvm.dbg.declare into the current block.
2717 llvm::Instruction *Call =
2718 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2719 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002720}
2721
2722void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2723 llvm::Value *Storage,
2724 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002725 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2727}
2728
Adrian Prantlde17db32013-03-29 19:20:29 +00002729/// Look up the completed type for a self pointer in the TypeCache and
2730/// create a copy of it with the ObjectPointer and Artificial flags
2731/// set. If the type is not cached, a new one is created. This should
2732/// never happen though, since creating a type for the implicit self
2733/// argument implies that we already parsed the interface definition
2734/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002735llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2736 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002737 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Manman Ren0d441f12013-07-02 19:01:53 +00002738 if (CachedTy.isType()) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002739 else DEBUG(llvm::dbgs() << "No cached type for self.");
2740 return DBuilder.createObjectPointerType(Ty);
2741}
2742
Guy Benyei11169dd2012-12-18 14:30:41 +00002743void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2744 llvm::Value *Storage,
2745 CGBuilderTy &Builder,
2746 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002747 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002749
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 if (Builder.GetInsertBlock() == 0)
2751 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002752
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002754
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 uint64_t XOffset = 0;
2756 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2757 llvm::DIType Ty;
2758 if (isByRef)
2759 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002760 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 Ty = getOrCreateType(VD->getType(), Unit);
2762
2763 // Self is passed along as an implicit non-arg variable in a
2764 // block. Mark it as the object pointer.
2765 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002766 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002767
2768 // Get location information.
2769 unsigned Line = getLineNumber(VD->getLocation());
2770 unsigned Column = getColumnNumber(VD->getLocation());
2771
2772 const llvm::DataLayout &target = CGM.getDataLayout();
2773
2774 CharUnits offset = CharUnits::fromQuantity(
2775 target.getStructLayout(blockInfo.StructureType)
2776 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2777
2778 SmallVector<llvm::Value *, 9> addr;
2779 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002780 if (isa<llvm::AllocaInst>(Storage))
2781 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2783 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2784 if (isByRef) {
2785 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2786 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2787 // offset of __forwarding field
2788 offset = CGM.getContext()
2789 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2790 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2791 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2792 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2793 // offset of x field
2794 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2795 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2796 }
2797
2798 // Create the descriptor for the variable.
2799 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002800 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 llvm::DIDescriptor(LexicalBlockStack.back()),
2802 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002803
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 // Insert an llvm.dbg.declare into the current block.
2805 llvm::Instruction *Call =
2806 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2807 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2808 LexicalBlockStack.back()));
2809}
2810
2811/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2812/// variable declaration.
2813void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2814 unsigned ArgNo,
2815 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002816 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002817 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2818}
2819
2820namespace {
2821 struct BlockLayoutChunk {
2822 uint64_t OffsetInBits;
2823 const BlockDecl::Capture *Capture;
2824 };
2825 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2826 return l.OffsetInBits < r.OffsetInBits;
2827 }
2828}
2829
2830void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002831 llvm::Value *Arg,
2832 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002834 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 ASTContext &C = CGM.getContext();
2836 const BlockDecl *blockDecl = block.getBlockDecl();
2837
2838 // Collect some general information about the block's location.
2839 SourceLocation loc = blockDecl->getCaretLocation();
2840 llvm::DIFile tunit = getOrCreateFile(loc);
2841 unsigned line = getLineNumber(loc);
2842 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002843
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 // Build the debug-info type for the block literal.
2845 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2846
2847 const llvm::StructLayout *blockLayout =
2848 CGM.getDataLayout().getStructLayout(block.StructureType);
2849
2850 SmallVector<llvm::Value*, 16> fields;
2851 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2852 blockLayout->getElementOffsetInBits(0),
2853 tunit, tunit));
2854 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2855 blockLayout->getElementOffsetInBits(1),
2856 tunit, tunit));
2857 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2858 blockLayout->getElementOffsetInBits(2),
2859 tunit, tunit));
2860 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2861 blockLayout->getElementOffsetInBits(3),
2862 tunit, tunit));
2863 fields.push_back(createFieldType("__descriptor",
2864 C.getPointerType(block.NeedsCopyDispose ?
2865 C.getBlockDescriptorExtendedType() :
2866 C.getBlockDescriptorType()),
2867 0, loc, AS_public,
2868 blockLayout->getElementOffsetInBits(4),
2869 tunit, tunit));
2870
2871 // We want to sort the captures by offset, not because DWARF
2872 // requires this, but because we're paranoid about debuggers.
2873 SmallVector<BlockLayoutChunk, 8> chunks;
2874
2875 // 'this' capture.
2876 if (blockDecl->capturesCXXThis()) {
2877 BlockLayoutChunk chunk;
2878 chunk.OffsetInBits =
2879 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2880 chunk.Capture = 0;
2881 chunks.push_back(chunk);
2882 }
2883
2884 // Variable captures.
2885 for (BlockDecl::capture_const_iterator
2886 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2887 i != e; ++i) {
2888 const BlockDecl::Capture &capture = *i;
2889 const VarDecl *variable = capture.getVariable();
2890 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2891
2892 // Ignore constant captures.
2893 if (captureInfo.isConstant())
2894 continue;
2895
2896 BlockLayoutChunk chunk;
2897 chunk.OffsetInBits =
2898 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2899 chunk.Capture = &capture;
2900 chunks.push_back(chunk);
2901 }
2902
2903 // Sort by offset.
2904 llvm::array_pod_sort(chunks.begin(), chunks.end());
2905
2906 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2907 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2908 uint64_t offsetInBits = i->OffsetInBits;
2909 const BlockDecl::Capture *capture = i->Capture;
2910
2911 // If we have a null capture, this must be the C++ 'this' capture.
2912 if (!capture) {
2913 const CXXMethodDecl *method =
2914 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2915 QualType type = method->getThisType(C);
2916
2917 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2918 offsetInBits, tunit, tunit));
2919 continue;
2920 }
2921
2922 const VarDecl *variable = capture->getVariable();
2923 StringRef name = variable->getName();
2924
2925 llvm::DIType fieldType;
2926 if (capture->isByRef()) {
2927 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2928
2929 // FIXME: this creates a second copy of this type!
2930 uint64_t xoffset;
2931 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2932 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2933 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2934 ptrInfo.first, ptrInfo.second,
2935 offsetInBits, 0, fieldType);
2936 } else {
2937 fieldType = createFieldType(name, variable->getType(), 0,
2938 loc, AS_public, offsetInBits, tunit, tunit);
2939 }
2940 fields.push_back(fieldType);
2941 }
2942
2943 SmallString<36> typeName;
2944 llvm::raw_svector_ostream(typeName)
2945 << "__block_literal_" << CGM.getUniqueBlockCount();
2946
2947 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2948
2949 llvm::DIType type =
2950 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2951 CGM.getContext().toBits(block.BlockSize),
2952 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00002953 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2955
2956 // Get overall information about the block.
2957 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2958 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959
2960 // Create the descriptor for the parameter.
2961 llvm::DIVariable debugVar =
2962 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002963 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00002964 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002966 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2967
Adrian Prantl616bef42013-03-14 21:52:59 +00002968 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00002969 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00002970 llvm::Instruction *DbgVal =
2971 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002972 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00002973 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2974 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00002975
Adrian Prantl616bef42013-03-14 21:52:59 +00002976 // Insert an llvm.dbg.declare into the current block.
2977 llvm::Instruction *DbgDecl =
2978 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2979 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002980}
2981
Eric Christopher91a31902013-01-16 01:22:32 +00002982/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2983/// a static data member of a class, find its corresponding in-class
2984/// declaration.
2985llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2986 if (cast<VarDecl>(D)->isStaticDataMember()) {
2987 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2988 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2989 if (MI != StaticDataMemberCache.end())
2990 // Verify the info still exists.
2991 if (llvm::Value *V = MI->second)
2992 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2993 }
2994 return llvm::DIDerivedType();
2995}
2996
Guy Benyei11169dd2012-12-18 14:30:41 +00002997/// EmitGlobalVariable - Emit information about a global variable.
2998void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2999 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003000 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 // Create global variable debug descriptor.
3002 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3003 unsigned LineNo = getLineNumber(D->getLocation());
3004
3005 setLocation(D->getLocation());
3006
3007 QualType T = D->getType();
3008 if (T->isIncompleteArrayType()) {
3009
3010 // CodeGen turns int[] into int[1] so we'll do the same here.
3011 llvm::APInt ConstVal(32, 1);
3012 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3013
3014 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3015 ArrayType::Normal, 0);
3016 }
3017 StringRef DeclName = D->getName();
3018 StringRef LinkageName;
3019 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3020 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3021 LinkageName = Var->getName();
3022 if (LinkageName == DeclName)
3023 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003024 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher1ecc5632013-06-07 22:54:39 +00003026 llvm::DIGlobalVariable GV =
3027 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3028 LineNo, getOrCreateType(T, Unit),
3029 Var->hasInternalLinkage(), Var,
3030 getStaticDataMemberDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00003031 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003032}
3033
3034/// EmitGlobalVariable - Emit information about an objective-c interface.
3035void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3036 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003037 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 // Create global variable debug descriptor.
3039 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3040 unsigned LineNo = getLineNumber(ID->getLocation());
3041
3042 StringRef Name = ID->getName();
3043
3044 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3045 if (T->isIncompleteArrayType()) {
3046
3047 // CodeGen turns int[] into int[1] so we'll do the same here.
3048 llvm::APInt ConstVal(32, 1);
3049 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3050
3051 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3052 ArrayType::Normal, 0);
3053 }
3054
3055 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3056 getOrCreateType(T, Unit),
3057 Var->hasInternalLinkage(), Var);
3058}
3059
3060/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003061void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003063 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 // Create the descriptor for the variable.
3065 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3066 StringRef Name = VD->getName();
3067 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3068 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3069 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3070 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3071 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3072 }
3073 // Do not use DIGlobalVariable for enums.
3074 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3075 return;
Eric Christopher1ecc5632013-06-07 22:54:39 +00003076 llvm::DIGlobalVariable GV =
3077 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3078 getLineNumber(VD->getLocation()), Ty, true,
3079 Init, getStaticDataMemberDeclaration(VD));
David Blaikiebd483762013-05-20 04:58:53 +00003080 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3081}
3082
3083llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3084 if (!LexicalBlockStack.empty())
3085 return llvm::DIScope(LexicalBlockStack.back());
3086 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003087}
3088
David Blaikie9f88fe82013-04-22 06:13:21 +00003089void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003090 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3091 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003092 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003093 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3094 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003095 getLineNumber(UD.getLocation()));
3096}
3097
David Blaikiebd483762013-05-20 04:58:53 +00003098void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3099 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3100 return;
3101 assert(UD.shadow_size() &&
3102 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3103 // Emitting one decl is sufficient - debuggers can detect that this is an
3104 // overloaded name & provide lookup for all the overloads.
3105 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003106 if (llvm::DIDescriptor Target =
3107 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003108 DBuilder.createImportedDeclaration(
3109 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3110 getLineNumber(USD.getLocation()));
3111}
3112
David Blaikief121b932013-05-20 22:50:41 +00003113llvm::DIImportedEntity
3114CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3115 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3116 return llvm::DIImportedEntity(0);
3117 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3118 if (VH)
3119 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3120 llvm::DIImportedEntity R(0);
3121 if (const NamespaceAliasDecl *Underlying =
3122 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3123 // This could cache & dedup here rather than relying on metadata deduping.
3124 R = DBuilder.createImportedModule(
3125 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3126 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3127 NA.getName());
3128 else
3129 R = DBuilder.createImportedModule(
3130 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3131 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3132 getLineNumber(NA.getLocation()), NA.getName());
3133 VH = R;
3134 return R;
3135}
3136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137/// getOrCreateNamesSpace - Return namespace descriptor for the given
3138/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003139llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003140CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00003141 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 NameSpaceCache.find(NSDecl);
3143 if (I != NameSpaceCache.end())
3144 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003145
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3147 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003148 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3150 llvm::DINameSpace NS =
3151 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3152 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3153 return NS;
3154}
3155
3156void CGDebugInfo::finalize() {
3157 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3158 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3159 llvm::DIType Ty, RepTy;
3160 // Verify that the debug info still exists.
3161 if (llvm::Value *V = VI->second)
3162 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003163
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3165 TypeCache.find(VI->first);
3166 if (it != TypeCache.end()) {
3167 // Verify that the debug info still exists.
3168 if (llvm::Value *V = it->second)
3169 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3170 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003171
Manman Ren0d441f12013-07-02 19:01:53 +00003172 if (Ty.isType() && Ty.isForwardDecl() && RepTy.isType())
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003175
3176 // We keep our own list of retained types, because we need to look
3177 // up the final type in the type cache.
3178 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3179 RE = RetainedTypes.end(); RI != RE; ++RI)
3180 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 DBuilder.finalize();
3183}