blob: 726f7361fc5f259cd4458a87a8d6328e3153734e [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher13c97672013-05-16 00:45:23 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()),
Guy Benyei7f92f2d2012-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 Blaikiea6504852013-01-26 22:16:26 +000084 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-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 Blaikiebb000792013-04-19 06:56:38 +000094llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-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 Blaikiebb000792013-04-19 06:56:38 +0000102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000103 }
104
105 // Check namespace.
106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000107 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000108
David Blaikiebb000792013-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 Benyei7f92f2d2012-12-18 14:30:41 +0000112 getOrCreateMainFile());
Guy Benyei7f92f2d2012-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 Kramer5eada842013-02-22 15:46:01 +0000128 SmallString<128> NS;
129 llvm::raw_svector_ostream OS(NS);
130 FD->printName(OS);
Guy Benyei7f92f2d2012-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 Kramer5eada842013-02-22 15:46:01 +0000138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000140 }
141
142 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-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 Benyei7f92f2d2012-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 Christopher6537f082013-05-16 00:45:12 +0000154 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000155 dyn_cast<const ObjCImplementationDecl>(DC)) {
156 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000157 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000158 dyn_cast<const ObjCInterfaceDecl>(DC)) {
159 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000160 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000161 dyn_cast<const ObjCCategoryImplDecl>(DC)){
162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000164 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-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 Benyei7f92f2d2012-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 Christopher6537f082013-05-16 00:45:12 +0000189StringRef
Guy Benyei7f92f2d2012-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 Kramer5eada842013-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 Benyei7f92f2d2012-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 Prantl00df5ea2013-03-12 20:43:25 +0000271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000272 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000273 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-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 Christopherff971d72013-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 Christopher6537f082013-05-16 00:45:12 +0000327
Guy Benyei7f92f2d2012-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 Christopherbe5f1be2013-02-21 22:35:08 +0000351 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
352 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000353 CGM.getCodeGenOpts().DwarfDebugFlags,
354 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000355 // FIXME - Eliminate TheCU.
356 TheCU = llvm::DICompileUnit(DBuilder.getCU());
357}
358
359/// CreateType - Get the Basic type from the cache or create a new
360/// one if necessary.
361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
362 unsigned Encoding = 0;
363 StringRef BTName;
364 switch (BT->getKind()) {
365#define BUILTIN_TYPE(Id, SingletonId)
366#define PLACEHOLDER_TYPE(Id, SingletonId) \
367 case BuiltinType::Id:
368#include "clang/AST/BuiltinTypes.def"
369 case BuiltinType::Dependent:
370 llvm_unreachable("Unexpected builtin type");
371 case BuiltinType::NullPtr:
372 return DBuilder.
373 createNullPtrType(BT->getName(CGM.getLangOpts()));
374 case BuiltinType::Void:
375 return llvm::DIType();
376 case BuiltinType::ObjCClass:
377 if (ClassTy.Verify())
378 return ClassTy;
379 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
380 "objc_class", TheCU,
381 getOrCreateMainFile(), 0);
382 return ClassTy;
383 case BuiltinType::ObjCId: {
384 // typedef struct objc_class *Class;
385 // typedef struct objc_object {
386 // Class isa;
387 // } *id;
388
389 if (ObjTy.Verify())
390 return ObjTy;
391
392 if (!ClassTy.Verify())
393 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
394 "objc_class", TheCU,
395 getOrCreateMainFile(), 0);
396
397 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000398
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000399 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
400
Eric Christopherf068c922013-04-02 22:59:11 +0000401 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000402 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
403 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000404
Eric Christopherf068c922013-04-02 22:59:11 +0000405 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
406 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000407 return ObjTy;
408 }
409 case BuiltinType::ObjCSel: {
410 if (SelTy.Verify())
411 return SelTy;
412 SelTy =
413 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
414 "objc_selector", TheCU, getOrCreateMainFile(),
415 0);
416 return SelTy;
417 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000418
419 case BuiltinType::OCLImage1d:
420 return getOrCreateStructPtrType("opencl_image1d_t",
421 OCLImage1dDITy);
422 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000423 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000424 OCLImage1dArrayDITy);
425 case BuiltinType::OCLImage1dBuffer:
426 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
427 OCLImage1dBufferDITy);
428 case BuiltinType::OCLImage2d:
429 return getOrCreateStructPtrType("opencl_image2d_t",
430 OCLImage2dDITy);
431 case BuiltinType::OCLImage2dArray:
432 return getOrCreateStructPtrType("opencl_image2d_array_t",
433 OCLImage2dArrayDITy);
434 case BuiltinType::OCLImage3d:
435 return getOrCreateStructPtrType("opencl_image3d_t",
436 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000437 case BuiltinType::OCLSampler:
438 return DBuilder.createBasicType("opencl_sampler_t",
439 CGM.getContext().getTypeSize(BT),
440 CGM.getContext().getTypeAlign(BT),
441 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000442 case BuiltinType::OCLEvent:
443 return getOrCreateStructPtrType("opencl_event_t",
444 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000445
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000446 case BuiltinType::UChar:
447 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
448 case BuiltinType::Char_S:
449 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
450 case BuiltinType::Char16:
451 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
452 case BuiltinType::UShort:
453 case BuiltinType::UInt:
454 case BuiltinType::UInt128:
455 case BuiltinType::ULong:
456 case BuiltinType::WChar_U:
457 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
458 case BuiltinType::Short:
459 case BuiltinType::Int:
460 case BuiltinType::Int128:
461 case BuiltinType::Long:
462 case BuiltinType::WChar_S:
463 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
464 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
465 case BuiltinType::Half:
466 case BuiltinType::Float:
467 case BuiltinType::LongDouble:
468 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
469 }
470
471 switch (BT->getKind()) {
472 case BuiltinType::Long: BTName = "long int"; break;
473 case BuiltinType::LongLong: BTName = "long long int"; break;
474 case BuiltinType::ULong: BTName = "long unsigned int"; break;
475 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
476 default:
477 BTName = BT->getName(CGM.getLangOpts());
478 break;
479 }
480 // Bit size, align and offset of the type.
481 uint64_t Size = CGM.getContext().getTypeSize(BT);
482 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000483 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000484 DBuilder.createBasicType(BTName, Size, Align, Encoding);
485 return DbgTy;
486}
487
488llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
489 // Bit size, align and offset of the type.
490 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
491 if (Ty->isComplexIntegerType())
492 Encoding = llvm::dwarf::DW_ATE_lo_user;
493
494 uint64_t Size = CGM.getContext().getTypeSize(Ty);
495 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000496 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000497 DBuilder.createBasicType("complex", Size, Align, Encoding);
498
499 return DbgTy;
500}
501
502/// CreateCVRType - Get the qualified type from the cache or create
503/// a new one if necessary.
504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
505 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
530 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
531
532 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
533 // CVR derived types.
534 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000535
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 return DbgTy;
537}
538
539llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
540 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000541
542 // The frontend treats 'id' as a typedef to an ObjCObjectType,
543 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
544 // debug info, we want to emit 'id' in both cases.
545 if (Ty->isObjCQualifiedIdType())
546 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
547
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000548 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000549 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000550 Ty->getPointeeType(), Unit);
551 return DbgTy;
552}
553
554llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
555 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000556 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000557 Ty->getPointeeType(), Unit);
558}
559
560// Creates a forward declaration for a RecordDecl in the given context.
561llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
562 llvm::DIDescriptor Ctx) {
563 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
564 unsigned Line = getLineNumber(RD->getLocation());
565 StringRef RDName = getClassName(RD);
566
567 unsigned Tag = 0;
568 if (RD->isStruct() || RD->isInterface())
569 Tag = llvm::dwarf::DW_TAG_structure_type;
570 else if (RD->isUnion())
571 Tag = llvm::dwarf::DW_TAG_union_type;
572 else {
573 assert(RD->isClass());
574 Tag = llvm::dwarf::DW_TAG_class_type;
575 }
576
577 // Create the type.
578 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
579}
580
581// Walk up the context chain and create forward decls for record decls,
582// and normal descriptors for namespaces.
583llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
584 if (!Context)
585 return TheCU;
586
587 // See if we already have the parent.
588 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
589 I = RegionMap.find(Context);
590 if (I != RegionMap.end()) {
591 llvm::Value *V = I->second;
592 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
593 }
Eric Christopher6537f082013-05-16 00:45:12 +0000594
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 // Check namespace.
596 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
597 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
598
599 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
600 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000601 llvm::DIType Ty =
602 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
603 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000604 return llvm::DIDescriptor(Ty);
605 }
606 }
607 return TheCU;
608}
609
610/// CreatePointeeType - Create Pointee type. If Pointee is a record
611/// then emit record's fwd if debug info size reduction is enabled.
612llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
613 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000614 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000615 return getOrCreateType(PointeeTy, Unit);
616
617 // Limit debug info for the pointee type.
618
619 // If we have an existing type, use that, it's still smaller than creating
620 // a new type.
621 llvm::DIType Ty = getTypeOrNull(PointeeTy);
622 if (Ty.Verify()) return Ty;
623
624 // Handle qualifiers.
625 if (PointeeTy.hasLocalQualifiers())
626 return CreateQualifiedType(PointeeTy, Unit);
627
628 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
629 RecordDecl *RD = RTy->getDecl();
630 llvm::DIDescriptor FDContext =
631 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
632 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
633 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
634 return RetTy;
635 }
636 return getOrCreateType(PointeeTy, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000637}
638
639llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000640 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000641 QualType PointeeTy,
642 llvm::DIFile Unit) {
643 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
645 return DBuilder.createReferenceType(Tag,
646 CreatePointeeType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000647
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000648 // Bit size, align and offset of the type.
649 // Size is always the size of a pointer. We can't use getTypeSize here
650 // because that does not return the correct value for references.
651 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000652 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
654
655 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
656 Size, Align);
657}
658
Eric Christopherf0890c42013-05-16 00:52:20 +0000659llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
660 llvm::DIType &Cache) {
David Blaikie1e97c1e2013-05-21 17:58:54 +0000661 if (Cache.Verify())
Guy Benyeib13621d2012-12-18 14:38:23 +0000662 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000663 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
664 TheCU, getOrCreateMainFile(), 0);
665 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
666 Cache = DBuilder.createPointerType(Cache, Size);
667 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000668}
669
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000670llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
671 llvm::DIFile Unit) {
672 if (BlockLiteralGenericSet)
673 return BlockLiteralGeneric;
674
675 SmallVector<llvm::Value *, 8> EltTys;
676 llvm::DIType FieldTy;
677 QualType FType;
678 uint64_t FieldSize, FieldOffset;
679 unsigned FieldAlign;
680 llvm::DIArray Elements;
681 llvm::DIType EltTy, DescTy;
682
683 FieldOffset = 0;
684 FType = CGM.getContext().UnsignedLongTy;
685 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
686 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
687
688 Elements = DBuilder.getOrCreateArray(EltTys);
689 EltTys.clear();
690
691 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
692 unsigned LineNo = getLineNumber(CurLoc);
693
694 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
695 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000696 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000697
698 // Bit size, align and offset of the type.
699 uint64_t Size = CGM.getContext().getTypeSize(Ty);
700
701 DescTy = DBuilder.createPointerType(EltTy, Size);
702
703 FieldOffset = 0;
704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
706 FType = CGM.getContext().IntTy;
707 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
708 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
709 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
710 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
711
712 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
713 FieldTy = DescTy;
714 FieldSize = CGM.getContext().getTypeSize(Ty);
715 FieldAlign = CGM.getContext().getTypeAlign(Ty);
716 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
717 LineNo, FieldSize, FieldAlign,
718 FieldOffset, 0, FieldTy);
719 EltTys.push_back(FieldTy);
720
721 FieldOffset += FieldSize;
722 Elements = DBuilder.getOrCreateArray(EltTys);
723
724 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
725 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000726 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000727
728 BlockLiteralGenericSet = true;
729 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
730 return BlockLiteralGeneric;
731}
732
733llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
734 // Typedefs are derived from some other type. If we have a typedef of a
735 // typedef, make sure to emit the whole chain.
David Blaikie9faebd22013-05-20 04:58:53 +0000736 llvm::DIType Src = CreatePointeeType(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000737 if (!Src.Verify())
738 return llvm::DIType();
739 // We don't set size information, but do specify where the typedef was
740 // declared.
741 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
742 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000743
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000744 llvm::DIDescriptor TypedefContext =
745 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000746
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000747 return
748 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
749}
750
751llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
752 llvm::DIFile Unit) {
753 SmallVector<llvm::Value *, 16> EltTys;
754
755 // Add the result type at least.
756 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
757
758 // Set up remainder of arguments if there is a prototype.
759 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
760 if (isa<FunctionNoProtoType>(Ty))
761 EltTys.push_back(DBuilder.createUnspecifiedParameter());
762 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
763 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
764 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
765 }
766
767 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
768 return DBuilder.createSubroutineType(Unit, EltTypeArray);
769}
770
771
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000772llvm::DIType CGDebugInfo::createFieldType(StringRef name,
773 QualType type,
774 uint64_t sizeInBitsOverride,
775 SourceLocation loc,
776 AccessSpecifier AS,
777 uint64_t offsetInBits,
778 llvm::DIFile tunit,
779 llvm::DIDescriptor scope) {
780 llvm::DIType debugType = getOrCreateType(type, tunit);
781
782 // Get the location for the field.
783 llvm::DIFile file = getOrCreateFile(loc);
784 unsigned line = getLineNumber(loc);
785
786 uint64_t sizeInBits = 0;
787 unsigned alignInBits = 0;
788 if (!type->isIncompleteArrayType()) {
789 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
790
791 if (sizeInBitsOverride)
792 sizeInBits = sizeInBitsOverride;
793 }
794
795 unsigned flags = 0;
796 if (AS == clang::AS_private)
797 flags |= llvm::DIDescriptor::FlagPrivate;
798 else if (AS == clang::AS_protected)
799 flags |= llvm::DIDescriptor::FlagProtected;
800
801 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
802 alignInBits, offsetInBits, flags, debugType);
803}
804
Eric Christopher0395de32013-01-16 01:22:32 +0000805/// CollectRecordLambdaFields - Helper for CollectRecordFields.
806void CGDebugInfo::
807CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
808 SmallVectorImpl<llvm::Value *> &elements,
809 llvm::DIType RecordTy) {
810 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
811 // has the name and the location of the variable so we should iterate over
812 // both concurrently.
813 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
814 RecordDecl::field_iterator Field = CXXDecl->field_begin();
815 unsigned fieldno = 0;
816 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
817 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
818 const LambdaExpr::Capture C = *I;
819 if (C.capturesVariable()) {
820 VarDecl *V = C.getCapturedVar();
821 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
822 StringRef VName = V->getName();
823 uint64_t SizeInBitsOverride = 0;
824 if (Field->isBitField()) {
825 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
826 assert(SizeInBitsOverride && "found named 0-width bitfield");
827 }
828 llvm::DIType fieldType
829 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
830 C.getLocation(), Field->getAccess(),
831 layout.getFieldOffset(fieldno), VUnit, RecordTy);
832 elements.push_back(fieldType);
833 } else {
834 // TODO: Need to handle 'this' in some way by probably renaming the
835 // this of the lambda class and having a field member of 'this' or
836 // by using AT_object_pointer for the function and having that be
837 // used as 'this' for semantic references.
838 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
839 FieldDecl *f = *Field;
840 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
841 QualType type = f->getType();
842 llvm::DIType fieldType
843 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
844 layout.getFieldOffset(fieldno), VUnit, RecordTy);
845
846 elements.push_back(fieldType);
847 }
848 }
849}
850
851/// CollectRecordStaticField - Helper for CollectRecordFields.
852void CGDebugInfo::
853CollectRecordStaticField(const VarDecl *Var,
854 SmallVectorImpl<llvm::Value *> &elements,
855 llvm::DIType RecordTy) {
856 // Create the descriptor for the static variable, with or without
857 // constant initializers.
858 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
859 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
860
861 // Do not describe enums as static members.
862 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
863 return;
864
865 unsigned LineNumber = getLineNumber(Var->getLocation());
866 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000867 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000868 if (Var->getInit()) {
869 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000870 if (Value) {
871 if (Value->isInt())
872 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
873 if (Value->isFloat())
874 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
875 }
Eric Christopher0395de32013-01-16 01:22:32 +0000876 }
877
878 unsigned Flags = 0;
879 AccessSpecifier Access = Var->getAccess();
880 if (Access == clang::AS_private)
881 Flags |= llvm::DIDescriptor::FlagPrivate;
882 else if (Access == clang::AS_protected)
883 Flags |= llvm::DIDescriptor::FlagProtected;
884
885 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000886 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000887 elements.push_back(GV);
888 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
889}
890
891/// CollectRecordNormalField - Helper for CollectRecordFields.
892void CGDebugInfo::
893CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
894 llvm::DIFile tunit,
895 SmallVectorImpl<llvm::Value *> &elements,
896 llvm::DIType RecordTy) {
897 StringRef name = field->getName();
898 QualType type = field->getType();
899
900 // Ignore unnamed fields unless they're anonymous structs/unions.
901 if (name.empty() && !type->isRecordType())
902 return;
903
904 uint64_t SizeInBitsOverride = 0;
905 if (field->isBitField()) {
906 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
907 assert(SizeInBitsOverride && "found named 0-width bitfield");
908 }
909
910 llvm::DIType fieldType
911 = createFieldType(name, type, SizeInBitsOverride,
912 field->getLocation(), field->getAccess(),
913 OffsetInBits, tunit, RecordTy);
914
915 elements.push_back(fieldType);
916}
917
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000918/// CollectRecordFields - A helper function to collect debug info for
919/// record fields. This is used while creating debug info entry for a Record.
920void CGDebugInfo::
921CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
922 SmallVectorImpl<llvm::Value *> &elements,
923 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000924 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
925
Eric Christopher0395de32013-01-16 01:22:32 +0000926 if (CXXDecl && CXXDecl->isLambda())
927 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
928 else {
929 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000930
Eric Christopher0395de32013-01-16 01:22:32 +0000931 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000932 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000933
934 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 bool IsMsStruct = record->isMsStruct(CGM.getContext());
936 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937
Eric Christopher0395de32013-01-16 01:22:32 +0000938 // Static and non-static members should appear in the same order as
939 // the corresponding declarations in the source program.
940 for (RecordDecl::decl_iterator I = record->decls_begin(),
941 E = record->decls_end(); I != E; ++I)
942 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
943 CollectRecordStaticField(V, elements, RecordTy);
944 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
945 if (IsMsStruct) {
946 // Zero-length bitfields following non-bitfield members are
947 // completely ignored; we don't even count them.
948 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
949 continue;
950 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000951 }
Eric Christopher0395de32013-01-16 01:22:32 +0000952 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
953 tunit, elements, RecordTy);
954
955 // Bump field number for next field.
956 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000957 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000958 }
959}
960
961/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
962/// function type is not updated to include implicit "this" pointer. Use this
963/// routine to get a method type which includes "this" pointer.
964llvm::DIType
965CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
966 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000967 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000968 if (Method->isStatic())
David Blaikie9c78f9b2013-01-07 23:06:35 +0000969 return getOrCreateType(QualType(Func, 0), Unit);
970 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
971 Func, Unit);
972}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000973
David Blaikie9c78f9b2013-01-07 23:06:35 +0000974llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
975 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000976 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000977 llvm::DIArray Args = llvm::DICompositeType(
978 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000979 assert (Args.getNumElements() && "Invalid number of arguments!");
980
981 SmallVector<llvm::Value *, 16> Elts;
982
983 // First element is always return type. For 'void' functions it is NULL.
984 Elts.push_back(Args.getElement(0));
985
David Blaikie67f8b5e2013-01-07 22:24:59 +0000986 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000987 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000988 if (isa<ClassTemplateSpecializationDecl>(RD)) {
989 // Create pointer type directly in this case.
990 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
991 QualType PointeeTy = ThisPtrTy->getPointeeType();
992 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000993 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000994 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
995 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000996 llvm::DIType ThisPtrType =
997 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000998 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
999 // TODO: This and the artificial type below are misleading, the
1000 // types aren't artificial the argument is, but the current
1001 // metadata doesn't represent that.
1002 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1003 Elts.push_back(ThisPtrType);
1004 } else {
1005 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1007 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1008 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001009 }
1010
1011 // Copy rest of the arguments.
1012 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1013 Elts.push_back(Args.getElement(i));
1014
1015 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1016
1017 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1018}
1019
Eric Christopher6537f082013-05-16 00:45:12 +00001020/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001021/// inside a function.
1022static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1023 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1024 return isFunctionLocalClass(NRD);
1025 if (isa<FunctionDecl>(RD->getDeclContext()))
1026 return true;
1027 return false;
1028}
1029
1030/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1031/// a single member function GlobalDecl.
1032llvm::DISubprogram
1033CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1034 llvm::DIFile Unit,
1035 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001036 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001037 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001038
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001039 StringRef MethodName = getFunctionName(Method);
1040 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1041
1042 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1043 // make sense to give a single ctor/dtor a linkage name.
1044 StringRef MethodLinkageName;
1045 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1046 MethodLinkageName = CGM.getMangledName(Method);
1047
1048 // Get the location for the method.
1049 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1050 unsigned MethodLine = getLineNumber(Method->getLocation());
1051
1052 // Collect virtual method info.
1053 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001054 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001055 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001056
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001057 if (Method->isVirtual()) {
1058 if (Method->isPure())
1059 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1060 else
1061 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001062
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001063 // It doesn't make sense to give a virtual destructor a vtable index,
1064 // since a single destructor has two entries in the vtable.
1065 if (!isa<CXXDestructorDecl>(Method))
1066 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1067 ContainingType = RecordTy;
1068 }
1069
1070 unsigned Flags = 0;
1071 if (Method->isImplicit())
1072 Flags |= llvm::DIDescriptor::FlagArtificial;
1073 AccessSpecifier Access = Method->getAccess();
1074 if (Access == clang::AS_private)
1075 Flags |= llvm::DIDescriptor::FlagPrivate;
1076 else if (Access == clang::AS_protected)
1077 Flags |= llvm::DIDescriptor::FlagProtected;
1078 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1079 if (CXXC->isExplicit())
1080 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001081 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001082 dyn_cast<CXXConversionDecl>(Method)) {
1083 if (CXXC->isExplicit())
1084 Flags |= llvm::DIDescriptor::FlagExplicit;
1085 }
1086 if (Method->hasPrototype())
1087 Flags |= llvm::DIDescriptor::FlagPrototyped;
1088
1089 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1090 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001091 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001092 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001093 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001094 /* isDefinition=*/ false,
1095 Virtuality, VIndex, ContainingType,
1096 Flags, CGM.getLangOpts().Optimize, NULL,
1097 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001098
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001099 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1100
1101 return SP;
1102}
1103
1104/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001105/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001106/// a Record.
1107void CGDebugInfo::
1108CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1109 SmallVectorImpl<llvm::Value *> &EltTys,
1110 llvm::DIType RecordTy) {
1111
1112 // Since we want more than just the individual member decls if we
1113 // have templated functions iterate over every declaration to gather
1114 // the functions.
1115 for(DeclContext::decl_iterator I = RD->decls_begin(),
1116 E = RD->decls_end(); I != E; ++I) {
1117 Decl *D = *I;
1118 if (D->isImplicit() && !D->isUsed())
1119 continue;
1120
1121 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1122 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1123 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1124 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1125 SE = FTD->spec_end(); SI != SE; ++SI)
1126 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1127 RecordTy));
1128 }
Eric Christopher6537f082013-05-16 00:45:12 +00001129}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001130
1131/// CollectCXXFriends - A helper function to collect debug info for
1132/// C++ base classes. This is used while creating debug info entry for
1133/// a Record.
1134void CGDebugInfo::
1135CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1136 SmallVectorImpl<llvm::Value *> &EltTys,
1137 llvm::DIType RecordTy) {
1138 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1139 BE = RD->friend_end(); BI != BE; ++BI) {
1140 if ((*BI)->isUnsupportedFriend())
1141 continue;
1142 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001143 EltTys.push_back(DBuilder.createFriend(RecordTy,
1144 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145 Unit)));
1146 }
1147}
1148
1149/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001150/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001151/// a Record.
1152void CGDebugInfo::
1153CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1154 SmallVectorImpl<llvm::Value *> &EltTys,
1155 llvm::DIType RecordTy) {
1156
1157 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1158 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1159 BE = RD->bases_end(); BI != BE; ++BI) {
1160 unsigned BFlags = 0;
1161 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001162
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001163 const CXXRecordDecl *Base =
1164 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001165
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001166 if (BI->isVirtual()) {
1167 // virtual base offset offset is -ve. The code generator emits dwarf
1168 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001169 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170 0 - CGM.getVTableContext()
1171 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1172 BFlags = llvm::DIDescriptor::FlagVirtual;
1173 } else
1174 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1175 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1176 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001177
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001178 AccessSpecifier Access = BI->getAccessSpecifier();
1179 if (Access == clang::AS_private)
1180 BFlags |= llvm::DIDescriptor::FlagPrivate;
1181 else if (Access == clang::AS_protected)
1182 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001183
1184 llvm::DIType DTy =
1185 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001186 getOrCreateType(BI->getType(), Unit),
1187 BaseOffset, BFlags);
1188 EltTys.push_back(DTy);
1189 }
1190}
1191
1192/// CollectTemplateParams - A helper function to collect template parameters.
1193llvm::DIArray CGDebugInfo::
1194CollectTemplateParams(const TemplateParameterList *TPList,
1195 const TemplateArgumentList &TAList,
1196 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001197 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001198 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1199 const TemplateArgument &TA = TAList[i];
1200 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001201 switch (TA.getKind()) {
1202 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001203 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1204 llvm::DITemplateTypeParameter TTP =
1205 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1206 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001207 } break;
1208 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001209 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1210 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001211 DBuilder.createTemplateValueParameter(
1212 TheCU, ND->getName(), TTy,
1213 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1214 TemplateParams.push_back(TVP);
1215 } break;
1216 case TemplateArgument::Declaration: {
1217 const ValueDecl *D = TA.getAsDecl();
1218 bool InstanceMember = D->isCXXInstanceMember();
1219 QualType T = InstanceMember
1220 ? CGM.getContext().getMemberPointerType(
1221 D->getType(), cast<RecordDecl>(D->getDeclContext())
1222 ->getTypeForDecl())
1223 : CGM.getContext().getPointerType(D->getType());
1224 llvm::DIType TTy = getOrCreateType(T, Unit);
1225 llvm::Value *V = 0;
1226 // Variable pointer template parameters have a value that is the address
1227 // of the variable.
1228 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1229 V = CGM.GetAddrOfGlobalVar(VD);
1230 // Member function pointers have special support for building them, though
1231 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001232 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001233 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1234 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001235 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1236 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001237 // Member data pointers have special handling too to compute the fixed
1238 // offset within the object.
1239 if (isa<FieldDecl>(D)) {
1240 // These five lines (& possibly the above member function pointer
1241 // handling) might be able to be refactored to use similar code in
1242 // CodeGenModule::getMemberPointerConstant
1243 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1244 CharUnits chars =
1245 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1246 V = CGM.getCXXABI().EmitMemberDataPointer(
1247 cast<MemberPointerType>(T.getTypePtr()), chars);
1248 }
1249 llvm::DITemplateValueParameter TVP =
1250 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1251 TemplateParams.push_back(TVP);
1252 } break;
1253 case TemplateArgument::NullPtr: {
1254 QualType T = TA.getNullPtrType();
1255 llvm::DIType TTy = getOrCreateType(T, Unit);
1256 llvm::Value *V = 0;
1257 // Special case member data pointer null values since they're actually -1
1258 // instead of zero.
1259 if (const MemberPointerType *MPT =
1260 dyn_cast<MemberPointerType>(T.getTypePtr()))
1261 // But treat member function pointers as simple zero integers because
1262 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1263 // CodeGen grows handling for values of non-null member function
1264 // pointers then perhaps we could remove this special case and rely on
1265 // EmitNullMemberPointer for member function pointers.
1266 if (MPT->isMemberDataPointer())
1267 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1268 if (!V)
1269 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1270 llvm::DITemplateValueParameter TVP =
1271 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1272 TemplateParams.push_back(TVP);
1273 } break;
1274 case TemplateArgument::Template:
1275 // We could support this with the GCC extension
1276 // DW_TAG_GNU_template_template_param
1277 break;
David Blaikie776a3642013-05-10 22:53:25 +00001278 case TemplateArgument::Pack:
1279 // And this with DW_TAG_GNU_template_parameter_pack
1280 break;
David Blaikiee8065122013-05-10 23:36:06 +00001281 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001282 case TemplateArgument::Expression:
1283 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001284 case TemplateArgument::Null:
1285 llvm_unreachable(
1286 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001287 }
1288 }
1289 return DBuilder.getOrCreateArray(TemplateParams);
1290}
1291
1292/// CollectFunctionTemplateParams - A helper function to collect debug
1293/// info for function template parameters.
1294llvm::DIArray CGDebugInfo::
1295CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1296 if (FD->getTemplatedKind() ==
1297 FunctionDecl::TK_FunctionTemplateSpecialization) {
1298 const TemplateParameterList *TList =
1299 FD->getTemplateSpecializationInfo()->getTemplate()
1300 ->getTemplateParameters();
Eric Christopher6537f082013-05-16 00:45:12 +00001301 return
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001302 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1303 }
1304 return llvm::DIArray();
1305}
1306
1307/// CollectCXXTemplateParams - A helper function to collect debug info for
1308/// template parameters.
1309llvm::DIArray CGDebugInfo::
1310CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1311 llvm::DIFile Unit) {
1312 llvm::PointerUnion<ClassTemplateDecl *,
1313 ClassTemplatePartialSpecializationDecl *>
1314 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001315
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001316 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1317 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1318 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1319 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1320 return CollectTemplateParams(TPList, TAList, Unit);
1321}
1322
1323/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1324llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1325 if (VTablePtrType.isValid())
1326 return VTablePtrType;
1327
1328 ASTContext &Context = CGM.getContext();
1329
1330 /* Function type */
1331 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1332 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1333 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1334 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1335 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1336 "__vtbl_ptr_type");
1337 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1338 return VTablePtrType;
1339}
1340
1341/// getVTableName - Get vtable name for the given Class.
1342StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1343 // Construct gdb compatible name name.
1344 std::string Name = "_vptr$" + RD->getNameAsString();
1345
1346 // Copy this name on the side and use its reference.
1347 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1348 memcpy(StrPtr, Name.data(), Name.length());
1349 return StringRef(StrPtr, Name.length());
1350}
1351
1352
1353/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1354/// debug info entry in EltTys vector.
1355void CGDebugInfo::
1356CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1357 SmallVectorImpl<llvm::Value *> &EltTys) {
1358 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1359
1360 // If there is a primary base then it will hold vtable info.
1361 if (RL.getPrimaryBase())
1362 return;
1363
1364 // If this class is not dynamic then there is not any vtable info to collect.
1365 if (!RD->isDynamicClass())
1366 return;
1367
1368 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1369 llvm::DIType VPTR
1370 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001371 0, Size, 0, 0,
1372 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001373 getOrCreateVTablePtrType(Unit));
1374 EltTys.push_back(VPTR);
1375}
1376
Eric Christopher6537f082013-05-16 00:45:12 +00001377/// getOrCreateRecordType - Emit record type's standalone debug info.
1378llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001380 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001381 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1382 return T;
1383}
1384
1385/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1386/// debug info.
1387llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001388 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001389 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001390 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001391 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392 return T;
1393}
1394
1395/// CreateType - get structure or union type.
1396llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1397 RecordDecl *RD = Ty->getDecl();
1398
1399 // Get overall information about the record type for the debug info.
1400 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1401
1402 // Records and classes and unions can all be recursive. To handle them, we
1403 // first generate a debug descriptor for the struct as a forward declaration.
1404 // Then (if it is a definition) we go through and get debug info for all of
1405 // its members. Finally, we create a descriptor for the complete type (which
1406 // may refer to the forward decl if the struct is recursive) and replace all
1407 // uses of the forward declaration with the final definition.
1408
Eric Christopherf068c922013-04-02 22:59:11 +00001409 llvm::DICompositeType FwdDecl(
1410 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1411 assert(FwdDecl.Verify() &&
1412 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001413
1414 if (FwdDecl.isForwardDecl())
1415 return FwdDecl;
1416
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001417 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001418 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001419 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1420
Adrian Prantl4919de62013-03-06 22:03:30 +00001421 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001422 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1423
1424 // Convert all the elements.
1425 SmallVector<llvm::Value *, 16> EltTys;
1426
1427 // Note: The split of CXXDecl information here is intentional, the
1428 // gdb tests will depend on a certain ordering at printout. The debug
1429 // information offsets are still correct if we merge them all together
1430 // though.
1431 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1432 if (CXXDecl) {
1433 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1434 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1435 }
1436
Eric Christopher0395de32013-01-16 01:22:32 +00001437 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001438 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1439 llvm::DIArray TParamsArray;
1440 if (CXXDecl) {
1441 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1442 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1443 if (const ClassTemplateSpecializationDecl *TSpecial
1444 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1445 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1446 }
1447
1448 LexicalBlockStack.pop_back();
1449 RegionMap.erase(Ty->getDecl());
1450
1451 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001452 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001453
Eric Christopherf068c922013-04-02 22:59:11 +00001454 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1455 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001456}
1457
1458/// CreateType - get objective-c object type.
1459llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1460 llvm::DIFile Unit) {
1461 // Ignore protocols.
1462 return getOrCreateType(Ty->getBaseType(), Unit);
1463}
1464
1465/// CreateType - get objective-c interface type.
1466llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1467 llvm::DIFile Unit) {
1468 ObjCInterfaceDecl *ID = Ty->getDecl();
1469 if (!ID)
1470 return llvm::DIType();
1471
1472 // Get overall information about the record type for the debug info.
1473 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1474 unsigned Line = getLineNumber(ID->getLocation());
1475 unsigned RuntimeLang = TheCU.getLanguage();
1476
1477 // If this is just a forward declaration return a special forward-declaration
1478 // debug type since we won't be able to lay out the entire type.
1479 ObjCInterfaceDecl *Def = ID->getDefinition();
1480 if (!Def) {
1481 llvm::DIType FwdDecl =
1482 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001483 ID->getName(), TheCU, DefUnit, Line,
1484 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001485 return FwdDecl;
1486 }
1487
1488 ID = Def;
1489
1490 // Bit size, align and offset of the type.
1491 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1492 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1493
1494 unsigned Flags = 0;
1495 if (ID->getImplementation())
1496 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1497
Eric Christopherf068c922013-04-02 22:59:11 +00001498 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1500 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001501 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001502
1503 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1504 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001505 QualType QualTy = QualType(Ty, 0);
1506 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001507 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001508
Eric Christopherf068c922013-04-02 22:59:11 +00001509 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001510 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1511
1512 // Convert all the elements.
1513 SmallVector<llvm::Value *, 16> EltTys;
1514
1515 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1516 if (SClass) {
1517 llvm::DIType SClassTy =
1518 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1519 if (!SClassTy.isValid())
1520 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001521
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001522 llvm::DIType InhTag =
1523 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1524 EltTys.push_back(InhTag);
1525 }
1526
1527 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1528 E = ID->prop_end(); I != E; ++I) {
1529 const ObjCPropertyDecl *PD = *I;
1530 SourceLocation Loc = PD->getLocation();
1531 llvm::DIFile PUnit = getOrCreateFile(Loc);
1532 unsigned PLine = getLineNumber(Loc);
1533 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1534 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1535 llvm::MDNode *PropertyNode =
1536 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001537 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001538 (Getter && Getter->isImplicit()) ? "" :
1539 getSelectorName(PD->getGetterName()),
1540 (Setter && Setter->isImplicit()) ? "" :
1541 getSelectorName(PD->getSetterName()),
1542 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001543 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001544 EltTys.push_back(PropertyNode);
1545 }
1546
1547 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1548 unsigned FieldNo = 0;
1549 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1550 Field = Field->getNextIvar(), ++FieldNo) {
1551 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1552 if (!FieldTy.isValid())
1553 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001554
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001555 StringRef FieldName = Field->getName();
1556
1557 // Ignore unnamed fields.
1558 if (FieldName.empty())
1559 continue;
1560
1561 // Get the location for the field.
1562 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1563 unsigned FieldLine = getLineNumber(Field->getLocation());
1564 QualType FType = Field->getType();
1565 uint64_t FieldSize = 0;
1566 unsigned FieldAlign = 0;
1567
1568 if (!FType->isIncompleteArrayType()) {
1569
1570 // Bit size, align and offset of the type.
1571 FieldSize = Field->isBitField()
1572 ? Field->getBitWidthValue(CGM.getContext())
1573 : CGM.getContext().getTypeSize(FType);
1574 FieldAlign = CGM.getContext().getTypeAlign(FType);
1575 }
1576
1577 uint64_t FieldOffset;
1578 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1579 // We don't know the runtime offset of an ivar if we're using the
1580 // non-fragile ABI. For bitfields, use the bit offset into the first
1581 // byte of storage of the bitfield. For other fields, use zero.
1582 if (Field->isBitField()) {
1583 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1584 CGM, ID, Field);
1585 FieldOffset %= CGM.getContext().getCharWidth();
1586 } else {
1587 FieldOffset = 0;
1588 }
1589 } else {
1590 FieldOffset = RL.getFieldOffset(FieldNo);
1591 }
1592
1593 unsigned Flags = 0;
1594 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1595 Flags = llvm::DIDescriptor::FlagProtected;
1596 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1597 Flags = llvm::DIDescriptor::FlagPrivate;
1598
1599 llvm::MDNode *PropertyNode = NULL;
1600 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001601 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001602 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1603 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001604 SourceLocation Loc = PD->getLocation();
1605 llvm::DIFile PUnit = getOrCreateFile(Loc);
1606 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001607 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1608 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1609 PropertyNode =
1610 DBuilder.createObjCProperty(PD->getName(),
1611 PUnit, PLine,
1612 (Getter && Getter->isImplicit()) ? "" :
1613 getSelectorName(PD->getGetterName()),
1614 (Setter && Setter->isImplicit()) ? "" :
1615 getSelectorName(PD->getSetterName()),
1616 PD->getPropertyAttributes(),
1617 getOrCreateType(PD->getType(), PUnit));
1618 }
1619 }
1620 }
1621 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1622 FieldLine, FieldSize, FieldAlign,
1623 FieldOffset, Flags, FieldTy,
1624 PropertyNode);
1625 EltTys.push_back(FieldTy);
1626 }
1627
1628 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001629 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001630
1631 // If the implementation is not yet set, we do not want to mark it
1632 // as complete. An implementation may declare additional
1633 // private ivars that we would miss otherwise.
1634 if (ID->getImplementation() == 0)
1635 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001636
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001637 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001638 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639}
1640
1641llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1642 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1643 int64_t Count = Ty->getNumElements();
1644 if (Count == 0)
1645 // If number of elements are not known then this is an unbounded array.
1646 // Use Count == -1 to express such arrays.
1647 Count = -1;
1648
1649 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1650 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1651
1652 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1653 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1654
1655 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1656}
1657
1658llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1659 llvm::DIFile Unit) {
1660 uint64_t Size;
1661 uint64_t Align;
1662
1663 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1664 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1665 Size = 0;
1666 Align =
1667 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1668 } else if (Ty->isIncompleteArrayType()) {
1669 Size = 0;
1670 if (Ty->getElementType()->isIncompleteType())
1671 Align = 0;
1672 else
1673 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001674 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001675 Size = 0;
1676 Align = 0;
1677 } else {
1678 // Size and align of the whole array, not the element type.
1679 Size = CGM.getContext().getTypeSize(Ty);
1680 Align = CGM.getContext().getTypeAlign(Ty);
1681 }
1682
1683 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1684 // interior arrays, do we care? Why aren't nested arrays represented the
1685 // obvious/recursive way?
1686 SmallVector<llvm::Value *, 8> Subscripts;
1687 QualType EltTy(Ty, 0);
1688 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1689 // If the number of elements is known, then count is that number. Otherwise,
1690 // it's -1. This allows us to represent a subrange with an array of 0
1691 // elements, like this:
1692 //
1693 // struct foo {
1694 // int x[0];
1695 // };
1696 int64_t Count = -1; // Count == -1 is an unbounded array.
1697 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1698 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001699
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001700 // FIXME: Verify this is right for VLAs.
1701 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1702 EltTy = Ty->getElementType();
1703 }
1704
1705 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1706
Eric Christopher6537f082013-05-16 00:45:12 +00001707 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001708 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1709 SubscriptArray);
1710 return DbgTy;
1711}
1712
Eric Christopher6537f082013-05-16 00:45:12 +00001713llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001715 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001716 Ty, Ty->getPointeeType(), Unit);
1717}
1718
Eric Christopher6537f082013-05-16 00:45:12 +00001719llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001720 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001721 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001722 Ty, Ty->getPointeeType(), Unit);
1723}
1724
Eric Christopher6537f082013-05-16 00:45:12 +00001725llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001726 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001727 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1728 if (!Ty->getPointeeType()->isFunctionType())
1729 return DBuilder.createMemberPointerType(
1730 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1731 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1732 CGM.getContext().getPointerType(
1733 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1734 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1735 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001736}
1737
Eric Christopher6537f082013-05-16 00:45:12 +00001738llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 llvm::DIFile U) {
1740 // Ignore the atomic wrapping
1741 // FIXME: What is the correct representation?
1742 return getOrCreateType(Ty->getValueType(), U);
1743}
1744
1745/// CreateEnumType - get enumeration type.
1746llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1747 uint64_t Size = 0;
1748 uint64_t Align = 0;
1749 if (!ED->getTypeForDecl()->isIncompleteType()) {
1750 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1751 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1752 }
1753
1754 // If this is just a forward declaration, construct an appropriately
1755 // marked node and just return it.
1756 if (!ED->getDefinition()) {
1757 llvm::DIDescriptor EDContext;
1758 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1759 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1760 unsigned Line = getLineNumber(ED->getLocation());
1761 StringRef EDName = ED->getName();
1762 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1763 EDName, EDContext, DefUnit, Line, 0,
1764 Size, Align);
1765 }
1766
1767 // Create DIEnumerator elements for each enumerator.
1768 SmallVector<llvm::Value *, 16> Enumerators;
1769 ED = ED->getDefinition();
1770 for (EnumDecl::enumerator_iterator
1771 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1772 Enum != EnumEnd; ++Enum) {
1773 Enumerators.push_back(
1774 DBuilder.createEnumerator(Enum->getName(),
1775 Enum->getInitVal().getZExtValue()));
1776 }
1777
1778 // Return a CompositeType for the enum itself.
1779 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1780
1781 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1782 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001783 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001784 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001785 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001787 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001788 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1789 Size, Align, EltArray,
1790 ClassTy);
1791 return DbgTy;
1792}
1793
David Blaikie4b12be62013-01-21 04:37:12 +00001794static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1795 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001796 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001797 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001798 QualType LastT = T;
1799 switch (T->getTypeClass()) {
1800 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001801 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001802 case Type::TemplateSpecialization:
1803 T = cast<TemplateSpecializationType>(T)->desugar();
1804 break;
1805 case Type::TypeOfExpr:
1806 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1807 break;
1808 case Type::TypeOf:
1809 T = cast<TypeOfType>(T)->getUnderlyingType();
1810 break;
1811 case Type::Decltype:
1812 T = cast<DecltypeType>(T)->getUnderlyingType();
1813 break;
1814 case Type::UnaryTransform:
1815 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1816 break;
1817 case Type::Attributed:
1818 T = cast<AttributedType>(T)->getEquivalentType();
1819 break;
1820 case Type::Elaborated:
1821 T = cast<ElaboratedType>(T)->getNamedType();
1822 break;
1823 case Type::Paren:
1824 T = cast<ParenType>(T)->getInnerType();
1825 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001826 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001827 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001828 break;
1829 case Type::Auto:
1830 T = cast<AutoType>(T)->getDeducedType();
1831 break;
1832 }
Eric Christopher6537f082013-05-16 00:45:12 +00001833
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001835 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001836 } while (true);
1837}
1838
Eric Christopherf0890c42013-05-16 00:52:20 +00001839/// getType - Get the type from the cache or return null type if it doesn't
1840/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1842
1843 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001844 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001845
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001847 if (Ty->getTypeClass() == Type::ObjCInterface) {
1848 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1849 if (V)
1850 return llvm::DIType(cast<llvm::MDNode>(V));
1851 else return llvm::DIType();
1852 }
1853
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001854 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1855 TypeCache.find(Ty.getAsOpaquePtr());
1856 if (it != TypeCache.end()) {
1857 // Verify that the debug info still exists.
1858 if (llvm::Value *V = it->second)
1859 return llvm::DIType(cast<llvm::MDNode>(V));
1860 }
1861
1862 return llvm::DIType();
1863}
1864
1865/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1866/// doesn't exist.
1867llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1868
1869 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001870 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871
1872 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001873 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001874 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1875 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001876 if (it != CompletedTypeCache.end())
1877 V = it->second;
1878 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001879 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 }
1881
Adrian Prantl4919de62013-03-06 22:03:30 +00001882 // Verify that any cached debug info still exists.
1883 if (V != 0)
1884 return llvm::DIType(cast<llvm::MDNode>(V));
1885
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001886 return llvm::DIType();
1887}
1888
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001889/// getCachedInterfaceTypeOrNull - Get the type from the interface
1890/// cache, unless it needs to regenerated. Otherwise return null.
1891llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1892 // Is there a cached interface that hasn't changed?
1893 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1894 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1895
1896 if (it1 != ObjCInterfaceCache.end())
1897 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1898 if (Checksum(Decl) == it1->second.second)
1899 // Return cached forward declaration.
1900 return it1->second.first;
1901
1902 return 0;
1903}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001904
1905/// getOrCreateType - Get the type from the cache or create a new
1906/// one if necessary.
1907llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1908 if (Ty.isNull())
1909 return llvm::DIType();
1910
1911 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001912 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001913
1914 llvm::DIType T = getCompletedTypeOrNull(Ty);
1915
1916 if (T.Verify())
1917 return T;
1918
1919 // Otherwise create the type.
1920 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001921 void* TyPtr = Ty.getAsOpaquePtr();
1922
1923 // And update the type cache.
1924 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001925
1926 llvm::DIType TC = getTypeOrNull(Ty);
1927 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001928 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1929 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1930 // Interface types may have elements added to them by a
1931 // subsequent implementation or extension, so we keep them in
1932 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001933 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001934 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1935 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1936 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1937 if (it != ObjCInterfaceCache.end())
1938 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
David Blaikie297dee82013-05-21 18:08:19 +00001939 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001940 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001941 Decl->getName(), TheCU, Unit,
1942 getLineNumber(Decl->getLocation()),
1943 TheCU.getLanguage());
David Blaikie297dee82013-05-21 18:08:19 +00001944 // Store the forward declaration in the cache.
1945 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001946
David Blaikie297dee82013-05-21 18:08:19 +00001947 // Register the type for replacement in finalize().
1948 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1949 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001950 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001951 }
1952
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001953 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001954 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001955
1956 return Res;
1957}
1958
Adrian Prantl4919de62013-03-06 22:03:30 +00001959/// Currently the checksum merely consists of the number of ivars.
1960unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001961 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001962 unsigned IvarNo = 0;
1963 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1964 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1965 return IvarNo;
1966}
1967
1968ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1969 switch (Ty->getTypeClass()) {
1970 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00001971 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1972 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00001973 case Type::ObjCInterface:
1974 return cast<ObjCInterfaceType>(Ty)->getDecl();
1975 default:
1976 return 0;
1977 }
1978}
1979
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001980/// CreateTypeNode - Create a new debug type node.
1981llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1982 // Handle qualifiers, which recursively handles what they refer to.
1983 if (Ty.hasLocalQualifiers())
1984 return CreateQualifiedType(Ty, Unit);
1985
1986 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001987
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001988 // Work out details of type.
1989 switch (Ty->getTypeClass()) {
1990#define TYPE(Class, Base)
1991#define ABSTRACT_TYPE(Class, Base)
1992#define NON_CANONICAL_TYPE(Class, Base)
1993#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1994#include "clang/AST/TypeNodes.def"
1995 llvm_unreachable("Dependent types cannot show up in debug information");
1996
1997 case Type::ExtVector:
1998 case Type::Vector:
1999 return CreateType(cast<VectorType>(Ty), Unit);
2000 case Type::ObjCObjectPointer:
2001 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2002 case Type::ObjCObject:
2003 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2004 case Type::ObjCInterface:
2005 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2006 case Type::Builtin:
2007 return CreateType(cast<BuiltinType>(Ty));
2008 case Type::Complex:
2009 return CreateType(cast<ComplexType>(Ty));
2010 case Type::Pointer:
2011 return CreateType(cast<PointerType>(Ty), Unit);
2012 case Type::BlockPointer:
2013 return CreateType(cast<BlockPointerType>(Ty), Unit);
2014 case Type::Typedef:
2015 return CreateType(cast<TypedefType>(Ty), Unit);
2016 case Type::Record:
2017 return CreateType(cast<RecordType>(Ty));
2018 case Type::Enum:
2019 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2020 case Type::FunctionProto:
2021 case Type::FunctionNoProto:
2022 return CreateType(cast<FunctionType>(Ty), Unit);
2023 case Type::ConstantArray:
2024 case Type::VariableArray:
2025 case Type::IncompleteArray:
2026 return CreateType(cast<ArrayType>(Ty), Unit);
2027
2028 case Type::LValueReference:
2029 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2030 case Type::RValueReference:
2031 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2032
2033 case Type::MemberPointer:
2034 return CreateType(cast<MemberPointerType>(Ty), Unit);
2035
2036 case Type::Atomic:
2037 return CreateType(cast<AtomicType>(Ty), Unit);
2038
2039 case Type::Attributed:
2040 case Type::TemplateSpecialization:
2041 case Type::Elaborated:
2042 case Type::Paren:
2043 case Type::SubstTemplateTypeParm:
2044 case Type::TypeOfExpr:
2045 case Type::TypeOf:
2046 case Type::Decltype:
2047 case Type::UnaryTransform:
2048 case Type::Auto:
2049 llvm_unreachable("type should have been unwrapped!");
2050 }
Eric Christopher6537f082013-05-16 00:45:12 +00002051
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002052 assert(Diag && "Fall through without a diagnostic?");
2053 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2054 "debug information for %0 is not yet supported");
2055 CGM.getDiags().Report(DiagID)
2056 << Diag;
2057 return llvm::DIType();
2058}
2059
2060/// getOrCreateLimitedType - Get the type from the cache or create a new
2061/// limited type if necessary.
2062llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002063 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002064 if (Ty.isNull())
2065 return llvm::DIType();
2066
2067 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002068 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002069
2070 llvm::DIType T = getTypeOrNull(Ty);
2071
2072 // We may have cached a forward decl when we could have created
2073 // a non-forward decl. Go ahead and create a non-forward decl
2074 // now.
2075 if (T.Verify() && !T.isForwardDecl()) return T;
2076
2077 // Otherwise create the type.
2078 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2079
2080 if (T.Verify() && T.isForwardDecl())
2081 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2082 static_cast<llvm::Value*>(T)));
2083
2084 // And update the type cache.
2085 TypeCache[Ty.getAsOpaquePtr()] = Res;
2086 return Res;
2087}
2088
2089// TODO: Currently used for context chains when limiting debug info.
2090llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2091 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002092
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002093 // Get overall information about the record type for the debug info.
2094 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2095 unsigned Line = getLineNumber(RD->getLocation());
2096 StringRef RDName = getClassName(RD);
2097
2098 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002099 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2101 else
2102 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2103
2104 // If this is just a forward declaration, construct an appropriately
2105 // marked node and just return it.
2106 if (!RD->getDefinition())
2107 return createRecordFwdDecl(RD, RDContext);
2108
2109 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2110 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2111 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002112 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002113
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002114 if (RD->isUnion())
2115 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002116 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002117 else if (RD->isClass()) {
2118 // FIXME: This could be a struct type giving a default visibility different
2119 // than C++ class type, but needs llvm metadata changes first.
2120 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002121 Size, Align, 0, 0, llvm::DIType(),
2122 llvm::DIArray(), llvm::DIType(),
2123 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002124 } else
2125 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002126 Size, Align, 0, llvm::DIType(),
2127 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002128
2129 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002130 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002131
2132 if (CXXDecl) {
2133 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002134 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002135 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2136 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2137 // Seek non virtual primary base root.
2138 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002139 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2140 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2141 if (PBT && !BRL.isPrimaryBaseVirtual())
2142 PBase = PBT;
2143 else
2144 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002145 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002146 ContainingType = llvm::DICompositeType(
2147 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2148 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002149 ContainingType = RealDecl;
2150
David Blaikie2fcadbe2013-03-26 23:47:35 +00002151 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002152 }
2153 return llvm::DIType(RealDecl);
2154}
2155
2156/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2157/// declare composite types that haven't been processed yet.
2158llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2159
2160 // Work out details of type.
2161 switch (Ty->getTypeClass()) {
2162#define TYPE(Class, Base)
2163#define ABSTRACT_TYPE(Class, Base)
2164#define NON_CANONICAL_TYPE(Class, Base)
2165#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2166 #include "clang/AST/TypeNodes.def"
2167 llvm_unreachable("Dependent types cannot show up in debug information");
2168
2169 case Type::Record:
2170 return CreateLimitedType(cast<RecordType>(Ty));
2171 default:
2172 return CreateTypeNode(Ty, Unit);
2173 }
2174}
2175
2176/// CreateMemberType - Create new member and increase Offset by FType's size.
2177llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2178 StringRef Name,
2179 uint64_t *Offset) {
2180 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2181 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2182 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2183 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2184 FieldSize, FieldAlign,
2185 *Offset, 0, FieldTy);
2186 *Offset += FieldSize;
2187 return Ty;
2188}
2189
David Blaikie9faebd22013-05-20 04:58:53 +00002190llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2191 // We only need a declaration (not a definition) of the type - so use whatever
2192 // we would otherwise do to get a type for a pointee. (forward declarations in
2193 // limited debug info, full definitions (if the type definition is available)
2194 // in unlimited debug info)
2195 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2196 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
2197 return CreatePointeeType(CGM.getContext().getTypeDeclType(TD), DefUnit);
2198 }
2199 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2200 // This doesn't handle providing declarations (for functions or variables) for
2201 // entities without definitions in this TU, nor when the definition proceeds
2202 // the call to this function.
2203 // FIXME: This should be split out into more specific maps with support for
2204 // emitting forward declarations and merging definitions with declarations,
2205 // the same way as we do for types.
2206 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2207 DeclCache.find(D->getCanonicalDecl());
2208 if (I == DeclCache.end())
2209 return llvm::DIDescriptor();
2210 llvm::Value *V = I->second;
2211 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2212}
2213
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002214/// getFunctionDeclaration - Return debug info descriptor to describe method
2215/// declaration for the given method definition.
2216llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2217 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2218 if (!FD) return llvm::DISubprogram();
2219
2220 // Setup context.
2221 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2222
2223 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2224 MI = SPCache.find(FD->getCanonicalDecl());
2225 if (MI != SPCache.end()) {
2226 llvm::Value *V = MI->second;
2227 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2228 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2229 return SP;
2230 }
2231
2232 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2233 E = FD->redecls_end(); I != E; ++I) {
2234 const FunctionDecl *NextFD = *I;
2235 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2236 MI = SPCache.find(NextFD->getCanonicalDecl());
2237 if (MI != SPCache.end()) {
2238 llvm::Value *V = MI->second;
2239 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2240 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2241 return SP;
2242 }
2243 }
2244 return llvm::DISubprogram();
2245}
2246
2247// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2248// implicit parameter "this".
2249llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2250 QualType FnType,
2251 llvm::DIFile F) {
2252
2253 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2254 return getOrCreateMethodType(Method, F);
2255 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2256 // Add "self" and "_cmd"
2257 SmallVector<llvm::Value *, 16> Elts;
2258
2259 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002260 QualType ResultTy = OMethod->hasRelatedResultType()
2261 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2262 : OMethod->getResultType();
2263 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002264 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002265 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2266 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2267 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002268 // "_cmd" pointer is always second argument.
2269 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2270 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2271 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002272 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002273 PE = OMethod->param_end(); PI != PE; ++PI)
2274 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2275
2276 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2277 return DBuilder.createSubroutineType(F, EltTypeArray);
2278 }
2279 return getOrCreateType(FnType, F);
2280}
2281
2282/// EmitFunctionStart - Constructs the debug code for entering a function.
2283void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2284 llvm::Function *Fn,
2285 CGBuilderTy &Builder) {
2286
2287 StringRef Name;
2288 StringRef LinkageName;
2289
2290 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2291
2292 const Decl *D = GD.getDecl();
2293 // Function may lack declaration in source code if it is created by Clang
2294 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2295 bool HasDecl = (D != 0);
2296 // Use the location of the declaration.
2297 SourceLocation Loc;
2298 if (HasDecl)
2299 Loc = D->getLocation();
2300
2301 unsigned Flags = 0;
2302 llvm::DIFile Unit = getOrCreateFile(Loc);
2303 llvm::DIDescriptor FDContext(Unit);
2304 llvm::DIArray TParamsArray;
2305 if (!HasDecl) {
2306 // Use llvm function name.
2307 Name = Fn->getName();
2308 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2309 // If there is a DISubprogram for this function available then use it.
2310 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2311 FI = SPCache.find(FD->getCanonicalDecl());
2312 if (FI != SPCache.end()) {
2313 llvm::Value *V = FI->second;
2314 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2315 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2316 llvm::MDNode *SPN = SP;
2317 LexicalBlockStack.push_back(SPN);
2318 RegionMap[D] = llvm::WeakVH(SP);
2319 return;
2320 }
2321 }
2322 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002323 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002324 if (FD->hasPrototype()) {
2325 LinkageName = CGM.getMangledName(GD);
2326 Flags |= llvm::DIDescriptor::FlagPrototyped;
2327 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002328 // No need to replicate the linkage name if it isn't different from the
2329 // subprogram name, no need to have it at all unless coverage is enabled or
2330 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002331 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002332 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2333 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002334 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002335 LinkageName = StringRef();
2336
Eric Christopher13c97672013-05-16 00:45:23 +00002337 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002338 if (const NamespaceDecl *NSDecl =
2339 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2340 FDContext = getOrCreateNameSpace(NSDecl);
2341 else if (const RecordDecl *RDecl =
2342 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2343 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2344
2345 // Collect template parameters.
2346 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2347 }
2348 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2349 Name = getObjCMethodName(OMD);
2350 Flags |= llvm::DIDescriptor::FlagPrototyped;
2351 } else {
2352 // Use llvm function name.
2353 Name = Fn->getName();
2354 Flags |= llvm::DIDescriptor::FlagPrototyped;
2355 }
2356 if (!Name.empty() && Name[0] == '\01')
2357 Name = Name.substr(1);
2358
2359 unsigned LineNo = getLineNumber(Loc);
2360 if (!HasDecl || D->isImplicit())
2361 Flags |= llvm::DIDescriptor::FlagArtificial;
2362
2363 llvm::DIType DIFnType;
2364 llvm::DISubprogram SPDecl;
2365 if (HasDecl &&
Eric Christopher13c97672013-05-16 00:45:23 +00002366 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002367 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2368 SPDecl = getFunctionDeclaration(D);
2369 } else {
2370 // Create fake but valid subroutine type. Otherwise
2371 // llvm::DISubprogram::Verify() would return false, and
2372 // subprogram DIE will miss DW_AT_decl_file and
2373 // DW_AT_decl_line fields.
2374 SmallVector<llvm::Value*, 16> Elts;
2375 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2376 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2377 }
2378 llvm::DISubprogram SP;
2379 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2380 LineNo, DIFnType,
2381 Fn->hasInternalLinkage(), true/*definition*/,
2382 getLineNumber(CurLoc), Flags,
2383 CGM.getLangOpts().Optimize,
2384 Fn, TParamsArray, SPDecl);
David Blaikie9faebd22013-05-20 04:58:53 +00002385 if (HasDecl)
2386 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002387
2388 // Push function on region stack.
2389 llvm::MDNode *SPN = SP;
2390 LexicalBlockStack.push_back(SPN);
2391 if (HasDecl)
2392 RegionMap[D] = llvm::WeakVH(SP);
2393}
2394
2395/// EmitLocation - Emit metadata to indicate a change in line/column
2396/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002397void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2398 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002399
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002400 // Update our current location
2401 setLocation(Loc);
2402
2403 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2404
2405 // Don't bother if things are the same as last time.
2406 SourceManager &SM = CGM.getContext().getSourceManager();
2407 if (CurLoc == PrevLoc ||
2408 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2409 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002410 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2411 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2412 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002413 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002414
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002415 // Update last state.
2416 PrevLoc = CurLoc;
2417
2418 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002419 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2420 (getLineNumber(CurLoc),
2421 getColumnNumber(CurLoc, ForceColumnInfo),
2422 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002423}
2424
2425/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2426/// the stack.
2427void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2428 llvm::DIDescriptor D =
2429 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2430 llvm::DIDescriptor() :
2431 llvm::DIDescriptor(LexicalBlockStack.back()),
2432 getOrCreateFile(CurLoc),
2433 getLineNumber(CurLoc),
2434 getColumnNumber(CurLoc));
2435 llvm::MDNode *DN = D;
2436 LexicalBlockStack.push_back(DN);
2437}
2438
2439/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2440/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002441void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2442 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002443 // Set our current location.
2444 setLocation(Loc);
2445
2446 // Create a new lexical block and push it on the stack.
2447 CreateLexicalBlock(Loc);
2448
2449 // Emit a line table change for the current location inside the new scope.
2450 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2451 getColumnNumber(Loc),
2452 LexicalBlockStack.back()));
2453}
2454
2455/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2456/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002457void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2458 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002459 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2460
2461 // Provide an entry in the line table for the end of the block.
2462 EmitLocation(Builder, Loc);
2463
2464 LexicalBlockStack.pop_back();
2465}
2466
2467/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2468void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2469 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2470 unsigned RCount = FnBeginRegionCount.back();
2471 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2472
2473 // Pop all regions for this function.
2474 while (LexicalBlockStack.size() != RCount)
2475 EmitLexicalBlockEnd(Builder, CurLoc);
2476 FnBeginRegionCount.pop_back();
2477}
2478
Eric Christopher6537f082013-05-16 00:45:12 +00002479// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002480// See BuildByRefType.
2481llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2482 uint64_t *XOffset) {
2483
2484 SmallVector<llvm::Value *, 5> EltTys;
2485 QualType FType;
2486 uint64_t FieldSize, FieldOffset;
2487 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002488
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002489 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002490 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002491
2492 FieldOffset = 0;
2493 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2494 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2495 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2496 FType = CGM.getContext().IntTy;
2497 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2498 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2499
2500 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2501 if (HasCopyAndDispose) {
2502 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2503 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2504 &FieldOffset));
2505 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2506 &FieldOffset));
2507 }
2508 bool HasByrefExtendedLayout;
2509 Qualifiers::ObjCLifetime Lifetime;
2510 if (CGM.getContext().getByrefLifetime(Type,
2511 Lifetime, HasByrefExtendedLayout)
2512 && HasByrefExtendedLayout)
2513 EltTys.push_back(CreateMemberType(Unit, FType,
2514 "__byref_variable_layout",
2515 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002516
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002517 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2518 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002519 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002520 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002521 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2522 CharUnits AlignedOffsetInBytes
2523 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2524 CharUnits NumPaddingBytes
2525 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002526
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002527 if (NumPaddingBytes.isPositive()) {
2528 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2529 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2530 pad, ArrayType::Normal, 0);
2531 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2532 }
2533 }
Eric Christopher6537f082013-05-16 00:45:12 +00002534
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002535 FType = Type;
2536 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2537 FieldSize = CGM.getContext().getTypeSize(FType);
2538 FieldAlign = CGM.getContext().toBits(Align);
2539
Eric Christopher6537f082013-05-16 00:45:12 +00002540 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002541 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2542 0, FieldSize, FieldAlign,
2543 FieldOffset, 0, FieldTy);
2544 EltTys.push_back(FieldTy);
2545 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002546
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002547 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002548
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002549 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002550
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002551 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002552 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002553}
2554
2555/// EmitDeclare - Emit local variable declaration debug info.
2556void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002557 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002558 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002559 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002560 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2561
2562 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2563 llvm::DIType Ty;
2564 uint64_t XOffset = 0;
2565 if (VD->hasAttr<BlocksAttr>())
2566 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002567 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002568 Ty = getOrCreateType(VD->getType(), Unit);
2569
2570 // If there is no debug info for this type then do not emit debug info
2571 // for this variable.
2572 if (!Ty)
2573 return;
2574
2575 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2576 // If Storage is an aggregate returned as 'sret' then let debugger know
2577 // about this.
2578 if (Arg->hasStructRetAttr())
2579 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2580 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2581 // If an aggregate variable has non trivial destructor or non trivial copy
2582 // constructor than it is pass indirectly. Let debug info know about this
2583 // by using reference of the aggregate type as a argument type.
2584 if (Record->hasNonTrivialCopyConstructor() ||
2585 !Record->hasTrivialDestructor())
Eric Christopherf0890c42013-05-16 00:52:20 +00002586 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type,
2587 Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002588 }
2589 }
Eric Christopher6537f082013-05-16 00:45:12 +00002590
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002591 // Get location information.
2592 unsigned Line = getLineNumber(VD->getLocation());
2593 unsigned Column = getColumnNumber(VD->getLocation());
2594 unsigned Flags = 0;
2595 if (VD->isImplicit())
2596 Flags |= llvm::DIDescriptor::FlagArtificial;
2597 // If this is the first argument and it is implicit then
2598 // give it an object pointer flag.
2599 // FIXME: There has to be a better way to do this, but for static
2600 // functions there won't be an implicit param at arg1 and
2601 // otherwise it is 'self' or 'this'.
2602 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2603 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2604
2605 llvm::MDNode *Scope = LexicalBlockStack.back();
2606
2607 StringRef Name = VD->getName();
2608 if (!Name.empty()) {
2609 if (VD->hasAttr<BlocksAttr>()) {
2610 CharUnits offset = CharUnits::fromQuantity(32);
2611 SmallVector<llvm::Value *, 9> addr;
2612 llvm::Type *Int64Ty = CGM.Int64Ty;
2613 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2614 // offset of __forwarding field
2615 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002616 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2618 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2619 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2620 // offset of x field
2621 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2622 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2623
2624 // Create the descriptor for the variable.
2625 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002626 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002627 llvm::DIDescriptor(Scope),
2628 VD->getName(), Unit, Line, Ty,
2629 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002630
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002631 // Insert an llvm.dbg.declare into the current block.
2632 llvm::Instruction *Call =
2633 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2634 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2635 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002636 } else if (isa<VariableArrayType>(VD->getType())) {
2637 // These are "complex" variables in that they need an op_deref.
2638 // Create the descriptor for the variable.
2639 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2640 llvm::DIBuilder::OpDeref);
2641 llvm::DIVariable D =
2642 DBuilder.createComplexVariable(Tag,
2643 llvm::DIDescriptor(Scope),
2644 Name, Unit, Line, Ty,
2645 Addr, ArgNo);
2646
2647 // Insert an llvm.dbg.declare into the current block.
2648 llvm::Instruction *Call =
2649 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2650 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2651 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002652 }
David Blaikie436653b2013-01-05 05:58:35 +00002653 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2654 // If VD is an anonymous union then Storage represents value for
2655 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002656 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002657 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002658 for (RecordDecl::field_iterator I = RD->field_begin(),
2659 E = RD->field_end();
2660 I != E; ++I) {
2661 FieldDecl *Field = *I;
2662 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2663 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002664
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 // Ignore unnamed fields. Do not ignore unnamed records.
2666 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2667 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002668
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002669 // Use VarDecl's Tag, Scope and Line number.
2670 llvm::DIVariable D =
2671 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002672 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002673 CGM.getLangOpts().Optimize, Flags,
2674 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002675
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002676 // Insert an llvm.dbg.declare into the current block.
2677 llvm::Instruction *Call =
2678 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2679 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2680 }
David Blaikied8180cf2013-01-05 20:03:07 +00002681 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002682 }
2683 }
David Blaikie436653b2013-01-05 05:58:35 +00002684
2685 // Create the descriptor for the variable.
2686 llvm::DIVariable D =
2687 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2688 Name, Unit, Line, Ty,
2689 CGM.getLangOpts().Optimize, Flags, ArgNo);
2690
2691 // Insert an llvm.dbg.declare into the current block.
2692 llvm::Instruction *Call =
2693 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2694 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002695}
2696
2697void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2698 llvm::Value *Storage,
2699 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002700 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002701 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2702}
2703
Adrian Prantle86fcc42013-03-29 19:20:29 +00002704/// Look up the completed type for a self pointer in the TypeCache and
2705/// create a copy of it with the ObjectPointer and Artificial flags
2706/// set. If the type is not cached, a new one is created. This should
2707/// never happen though, since creating a type for the implicit self
2708/// argument implies that we already parsed the interface definition
2709/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002710llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2711 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002712 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2713 if (CachedTy.Verify()) Ty = CachedTy;
2714 else DEBUG(llvm::dbgs() << "No cached type for self.");
2715 return DBuilder.createObjectPointerType(Ty);
2716}
2717
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002718void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2719 llvm::Value *Storage,
2720 CGBuilderTy &Builder,
2721 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002722 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002723 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002724
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002725 if (Builder.GetInsertBlock() == 0)
2726 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002727
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002729
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002730 uint64_t XOffset = 0;
2731 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2732 llvm::DIType Ty;
2733 if (isByRef)
2734 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002735 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002736 Ty = getOrCreateType(VD->getType(), Unit);
2737
2738 // Self is passed along as an implicit non-arg variable in a
2739 // block. Mark it as the object pointer.
2740 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002741 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002742
2743 // Get location information.
2744 unsigned Line = getLineNumber(VD->getLocation());
2745 unsigned Column = getColumnNumber(VD->getLocation());
2746
2747 const llvm::DataLayout &target = CGM.getDataLayout();
2748
2749 CharUnits offset = CharUnits::fromQuantity(
2750 target.getStructLayout(blockInfo.StructureType)
2751 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2752
2753 SmallVector<llvm::Value *, 9> addr;
2754 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002755 if (isa<llvm::AllocaInst>(Storage))
2756 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002757 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2758 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2759 if (isByRef) {
2760 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2761 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2762 // offset of __forwarding field
2763 offset = CGM.getContext()
2764 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2765 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2766 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2767 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2768 // offset of x field
2769 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2770 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2771 }
2772
2773 // Create the descriptor for the variable.
2774 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002775 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002776 llvm::DIDescriptor(LexicalBlockStack.back()),
2777 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002778
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002779 // Insert an llvm.dbg.declare into the current block.
2780 llvm::Instruction *Call =
2781 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2782 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2783 LexicalBlockStack.back()));
2784}
2785
2786/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2787/// variable declaration.
2788void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2789 unsigned ArgNo,
2790 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002791 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002792 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2793}
2794
2795namespace {
2796 struct BlockLayoutChunk {
2797 uint64_t OffsetInBits;
2798 const BlockDecl::Capture *Capture;
2799 };
2800 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2801 return l.OffsetInBits < r.OffsetInBits;
2802 }
2803}
2804
2805void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002806 llvm::Value *Arg,
2807 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002808 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002809 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002810 ASTContext &C = CGM.getContext();
2811 const BlockDecl *blockDecl = block.getBlockDecl();
2812
2813 // Collect some general information about the block's location.
2814 SourceLocation loc = blockDecl->getCaretLocation();
2815 llvm::DIFile tunit = getOrCreateFile(loc);
2816 unsigned line = getLineNumber(loc);
2817 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002818
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002819 // Build the debug-info type for the block literal.
2820 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2821
2822 const llvm::StructLayout *blockLayout =
2823 CGM.getDataLayout().getStructLayout(block.StructureType);
2824
2825 SmallVector<llvm::Value*, 16> fields;
2826 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2827 blockLayout->getElementOffsetInBits(0),
2828 tunit, tunit));
2829 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2830 blockLayout->getElementOffsetInBits(1),
2831 tunit, tunit));
2832 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2833 blockLayout->getElementOffsetInBits(2),
2834 tunit, tunit));
2835 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2836 blockLayout->getElementOffsetInBits(3),
2837 tunit, tunit));
2838 fields.push_back(createFieldType("__descriptor",
2839 C.getPointerType(block.NeedsCopyDispose ?
2840 C.getBlockDescriptorExtendedType() :
2841 C.getBlockDescriptorType()),
2842 0, loc, AS_public,
2843 blockLayout->getElementOffsetInBits(4),
2844 tunit, tunit));
2845
2846 // We want to sort the captures by offset, not because DWARF
2847 // requires this, but because we're paranoid about debuggers.
2848 SmallVector<BlockLayoutChunk, 8> chunks;
2849
2850 // 'this' capture.
2851 if (blockDecl->capturesCXXThis()) {
2852 BlockLayoutChunk chunk;
2853 chunk.OffsetInBits =
2854 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2855 chunk.Capture = 0;
2856 chunks.push_back(chunk);
2857 }
2858
2859 // Variable captures.
2860 for (BlockDecl::capture_const_iterator
2861 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2862 i != e; ++i) {
2863 const BlockDecl::Capture &capture = *i;
2864 const VarDecl *variable = capture.getVariable();
2865 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2866
2867 // Ignore constant captures.
2868 if (captureInfo.isConstant())
2869 continue;
2870
2871 BlockLayoutChunk chunk;
2872 chunk.OffsetInBits =
2873 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2874 chunk.Capture = &capture;
2875 chunks.push_back(chunk);
2876 }
2877
2878 // Sort by offset.
2879 llvm::array_pod_sort(chunks.begin(), chunks.end());
2880
2881 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2882 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2883 uint64_t offsetInBits = i->OffsetInBits;
2884 const BlockDecl::Capture *capture = i->Capture;
2885
2886 // If we have a null capture, this must be the C++ 'this' capture.
2887 if (!capture) {
2888 const CXXMethodDecl *method =
2889 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2890 QualType type = method->getThisType(C);
2891
2892 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2893 offsetInBits, tunit, tunit));
2894 continue;
2895 }
2896
2897 const VarDecl *variable = capture->getVariable();
2898 StringRef name = variable->getName();
2899
2900 llvm::DIType fieldType;
2901 if (capture->isByRef()) {
2902 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2903
2904 // FIXME: this creates a second copy of this type!
2905 uint64_t xoffset;
2906 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2907 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2908 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2909 ptrInfo.first, ptrInfo.second,
2910 offsetInBits, 0, fieldType);
2911 } else {
2912 fieldType = createFieldType(name, variable->getType(), 0,
2913 loc, AS_public, offsetInBits, tunit, tunit);
2914 }
2915 fields.push_back(fieldType);
2916 }
2917
2918 SmallString<36> typeName;
2919 llvm::raw_svector_ostream(typeName)
2920 << "__block_literal_" << CGM.getUniqueBlockCount();
2921
2922 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2923
2924 llvm::DIType type =
2925 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2926 CGM.getContext().toBits(block.BlockSize),
2927 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002928 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002929 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2930
2931 // Get overall information about the block.
2932 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2933 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002934
2935 // Create the descriptor for the parameter.
2936 llvm::DIVariable debugVar =
2937 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002938 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002939 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002940 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002941 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2942
Adrian Prantlbea407c2013-03-14 21:52:59 +00002943 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002944 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002945 llvm::Instruction *DbgVal =
2946 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002947 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002948 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2949 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002950
Adrian Prantlbea407c2013-03-14 21:52:59 +00002951 // Insert an llvm.dbg.declare into the current block.
2952 llvm::Instruction *DbgDecl =
2953 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2954 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002955}
2956
Eric Christopher0395de32013-01-16 01:22:32 +00002957/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2958/// a static data member of a class, find its corresponding in-class
2959/// declaration.
2960llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2961 if (cast<VarDecl>(D)->isStaticDataMember()) {
2962 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2963 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2964 if (MI != StaticDataMemberCache.end())
2965 // Verify the info still exists.
2966 if (llvm::Value *V = MI->second)
2967 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2968 }
2969 return llvm::DIDerivedType();
2970}
2971
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002972/// EmitGlobalVariable - Emit information about a global variable.
2973void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2974 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00002975 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002976 // Create global variable debug descriptor.
2977 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2978 unsigned LineNo = getLineNumber(D->getLocation());
2979
2980 setLocation(D->getLocation());
2981
2982 QualType T = D->getType();
2983 if (T->isIncompleteArrayType()) {
2984
2985 // CodeGen turns int[] into int[1] so we'll do the same here.
2986 llvm::APInt ConstVal(32, 1);
2987 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2988
2989 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2990 ArrayType::Normal, 0);
2991 }
2992 StringRef DeclName = D->getName();
2993 StringRef LinkageName;
2994 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2995 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2996 LinkageName = Var->getName();
2997 if (LinkageName == DeclName)
2998 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00002999 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003000 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie9faebd22013-05-20 04:58:53 +00003001 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003002 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00003003 Var->hasInternalLinkage(), Var,
3004 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003005 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003006}
3007
3008/// EmitGlobalVariable - Emit information about an objective-c interface.
3009void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3010 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003011 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003012 // Create global variable debug descriptor.
3013 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3014 unsigned LineNo = getLineNumber(ID->getLocation());
3015
3016 StringRef Name = ID->getName();
3017
3018 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3019 if (T->isIncompleteArrayType()) {
3020
3021 // CodeGen turns int[] into int[1] so we'll do the same here.
3022 llvm::APInt ConstVal(32, 1);
3023 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3024
3025 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3026 ArrayType::Normal, 0);
3027 }
3028
3029 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3030 getOrCreateType(T, Unit),
3031 Var->hasInternalLinkage(), Var);
3032}
3033
3034/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003035void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003036 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003037 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003038 // Create the descriptor for the variable.
3039 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3040 StringRef Name = VD->getName();
3041 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3042 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3043 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3044 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3045 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3046 }
3047 // Do not use DIGlobalVariable for enums.
3048 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3049 return;
David Blaikie9faebd22013-05-20 04:58:53 +00003050 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003051 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003052 Ty, true, Init,
3053 getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003054 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3055}
3056
3057llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3058 if (!LexicalBlockStack.empty())
3059 return llvm::DIScope(LexicalBlockStack.back());
3060 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003061}
3062
David Blaikie957dac52013-04-22 06:13:21 +00003063void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003064 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3065 return;
David Blaikie957dac52013-04-22 06:13:21 +00003066 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003067 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3068 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003069 getLineNumber(UD.getLocation()));
3070}
3071
David Blaikie9faebd22013-05-20 04:58:53 +00003072void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3073 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3074 return;
3075 assert(UD.shadow_size() &&
3076 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3077 // Emitting one decl is sufficient - debuggers can detect that this is an
3078 // overloaded name & provide lookup for all the overloads.
3079 const UsingShadowDecl &USD = **UD.shadow_begin();
3080 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3081 DBuilder.createImportedDeclaration(
3082 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3083 getLineNumber(USD.getLocation()));
3084}
3085
David Blaikiefc46ebc2013-05-20 22:50:41 +00003086llvm::DIImportedEntity
3087CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3088 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3089 return llvm::DIImportedEntity(0);
3090 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3091 if (VH)
3092 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3093 llvm::DIImportedEntity R(0);
3094 if (const NamespaceAliasDecl *Underlying =
3095 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3096 // This could cache & dedup here rather than relying on metadata deduping.
3097 R = DBuilder.createImportedModule(
3098 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3099 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3100 NA.getName());
3101 else
3102 R = DBuilder.createImportedModule(
3103 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3104 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3105 getLineNumber(NA.getLocation()), NA.getName());
3106 VH = R;
3107 return R;
3108}
3109
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003110/// getOrCreateNamesSpace - Return namespace descriptor for the given
3111/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003112llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003113CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003114 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003115 NameSpaceCache.find(NSDecl);
3116 if (I != NameSpaceCache.end())
3117 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003118
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003119 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3120 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003121 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003122 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3123 llvm::DINameSpace NS =
3124 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3125 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3126 return NS;
3127}
3128
3129void CGDebugInfo::finalize() {
3130 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3131 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3132 llvm::DIType Ty, RepTy;
3133 // Verify that the debug info still exists.
3134 if (llvm::Value *V = VI->second)
3135 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003136
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003137 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3138 TypeCache.find(VI->first);
3139 if (it != TypeCache.end()) {
3140 // Verify that the debug info still exists.
3141 if (llvm::Value *V = it->second)
3142 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3143 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003144
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003145 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003146 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003147 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003148
3149 // We keep our own list of retained types, because we need to look
3150 // up the final type in the type cache.
3151 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3152 RE = RetainedTypes.end(); RI != RE; ++RI)
3153 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3154
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003155 DBuilder.finalize();
3156}