blob: eff9d2284f02209d090fa42b654a541210555a96 [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) {
Guy Benyeib13621d2012-12-18 14:38:23 +0000661 if (Cache.Verify())
662 return Cache;
663 Cache =
664 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
665 Name, TheCU, getOrCreateMainFile(),
666 0);
667 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
668 Cache = DBuilder.createPointerType(Cache, Size);
669 return Cache;
670}
671
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000672llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
673 llvm::DIFile Unit) {
674 if (BlockLiteralGenericSet)
675 return BlockLiteralGeneric;
676
677 SmallVector<llvm::Value *, 8> EltTys;
678 llvm::DIType FieldTy;
679 QualType FType;
680 uint64_t FieldSize, FieldOffset;
681 unsigned FieldAlign;
682 llvm::DIArray Elements;
683 llvm::DIType EltTy, DescTy;
684
685 FieldOffset = 0;
686 FType = CGM.getContext().UnsignedLongTy;
687 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
688 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
689
690 Elements = DBuilder.getOrCreateArray(EltTys);
691 EltTys.clear();
692
693 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
694 unsigned LineNo = getLineNumber(CurLoc);
695
696 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
697 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000698 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000699
700 // Bit size, align and offset of the type.
701 uint64_t Size = CGM.getContext().getTypeSize(Ty);
702
703 DescTy = DBuilder.createPointerType(EltTy, Size);
704
705 FieldOffset = 0;
706 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
707 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
708 FType = CGM.getContext().IntTy;
709 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
710 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
712 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
713
714 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
715 FieldTy = DescTy;
716 FieldSize = CGM.getContext().getTypeSize(Ty);
717 FieldAlign = CGM.getContext().getTypeAlign(Ty);
718 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
719 LineNo, FieldSize, FieldAlign,
720 FieldOffset, 0, FieldTy);
721 EltTys.push_back(FieldTy);
722
723 FieldOffset += FieldSize;
724 Elements = DBuilder.getOrCreateArray(EltTys);
725
726 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
727 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000728 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000729
730 BlockLiteralGenericSet = true;
731 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
732 return BlockLiteralGeneric;
733}
734
735llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
736 // Typedefs are derived from some other type. If we have a typedef of a
737 // typedef, make sure to emit the whole chain.
David Blaikie9faebd22013-05-20 04:58:53 +0000738 llvm::DIType Src = CreatePointeeType(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000739 if (!Src.Verify())
740 return llvm::DIType();
741 // We don't set size information, but do specify where the typedef was
742 // declared.
743 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
744 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000745
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000746 llvm::DIDescriptor TypedefContext =
747 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000748
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000749 return
750 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
751}
752
753llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
754 llvm::DIFile Unit) {
755 SmallVector<llvm::Value *, 16> EltTys;
756
757 // Add the result type at least.
758 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
759
760 // Set up remainder of arguments if there is a prototype.
761 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
762 if (isa<FunctionNoProtoType>(Ty))
763 EltTys.push_back(DBuilder.createUnspecifiedParameter());
764 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
765 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
766 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
767 }
768
769 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
770 return DBuilder.createSubroutineType(Unit, EltTypeArray);
771}
772
773
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000774llvm::DIType CGDebugInfo::createFieldType(StringRef name,
775 QualType type,
776 uint64_t sizeInBitsOverride,
777 SourceLocation loc,
778 AccessSpecifier AS,
779 uint64_t offsetInBits,
780 llvm::DIFile tunit,
781 llvm::DIDescriptor scope) {
782 llvm::DIType debugType = getOrCreateType(type, tunit);
783
784 // Get the location for the field.
785 llvm::DIFile file = getOrCreateFile(loc);
786 unsigned line = getLineNumber(loc);
787
788 uint64_t sizeInBits = 0;
789 unsigned alignInBits = 0;
790 if (!type->isIncompleteArrayType()) {
791 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
792
793 if (sizeInBitsOverride)
794 sizeInBits = sizeInBitsOverride;
795 }
796
797 unsigned flags = 0;
798 if (AS == clang::AS_private)
799 flags |= llvm::DIDescriptor::FlagPrivate;
800 else if (AS == clang::AS_protected)
801 flags |= llvm::DIDescriptor::FlagProtected;
802
803 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
804 alignInBits, offsetInBits, flags, debugType);
805}
806
Eric Christopher0395de32013-01-16 01:22:32 +0000807/// CollectRecordLambdaFields - Helper for CollectRecordFields.
808void CGDebugInfo::
809CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
810 SmallVectorImpl<llvm::Value *> &elements,
811 llvm::DIType RecordTy) {
812 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
813 // has the name and the location of the variable so we should iterate over
814 // both concurrently.
815 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
816 RecordDecl::field_iterator Field = CXXDecl->field_begin();
817 unsigned fieldno = 0;
818 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
819 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
820 const LambdaExpr::Capture C = *I;
821 if (C.capturesVariable()) {
822 VarDecl *V = C.getCapturedVar();
823 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
824 StringRef VName = V->getName();
825 uint64_t SizeInBitsOverride = 0;
826 if (Field->isBitField()) {
827 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
828 assert(SizeInBitsOverride && "found named 0-width bitfield");
829 }
830 llvm::DIType fieldType
831 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
832 C.getLocation(), Field->getAccess(),
833 layout.getFieldOffset(fieldno), VUnit, RecordTy);
834 elements.push_back(fieldType);
835 } else {
836 // TODO: Need to handle 'this' in some way by probably renaming the
837 // this of the lambda class and having a field member of 'this' or
838 // by using AT_object_pointer for the function and having that be
839 // used as 'this' for semantic references.
840 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
841 FieldDecl *f = *Field;
842 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
843 QualType type = f->getType();
844 llvm::DIType fieldType
845 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
846 layout.getFieldOffset(fieldno), VUnit, RecordTy);
847
848 elements.push_back(fieldType);
849 }
850 }
851}
852
853/// CollectRecordStaticField - Helper for CollectRecordFields.
854void CGDebugInfo::
855CollectRecordStaticField(const VarDecl *Var,
856 SmallVectorImpl<llvm::Value *> &elements,
857 llvm::DIType RecordTy) {
858 // Create the descriptor for the static variable, with or without
859 // constant initializers.
860 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
861 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
862
863 // Do not describe enums as static members.
864 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
865 return;
866
867 unsigned LineNumber = getLineNumber(Var->getLocation());
868 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000869 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000870 if (Var->getInit()) {
871 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000872 if (Value) {
873 if (Value->isInt())
874 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
875 if (Value->isFloat())
876 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
877 }
Eric Christopher0395de32013-01-16 01:22:32 +0000878 }
879
880 unsigned Flags = 0;
881 AccessSpecifier Access = Var->getAccess();
882 if (Access == clang::AS_private)
883 Flags |= llvm::DIDescriptor::FlagPrivate;
884 else if (Access == clang::AS_protected)
885 Flags |= llvm::DIDescriptor::FlagProtected;
886
887 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000888 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000889 elements.push_back(GV);
890 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
891}
892
893/// CollectRecordNormalField - Helper for CollectRecordFields.
894void CGDebugInfo::
895CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
896 llvm::DIFile tunit,
897 SmallVectorImpl<llvm::Value *> &elements,
898 llvm::DIType RecordTy) {
899 StringRef name = field->getName();
900 QualType type = field->getType();
901
902 // Ignore unnamed fields unless they're anonymous structs/unions.
903 if (name.empty() && !type->isRecordType())
904 return;
905
906 uint64_t SizeInBitsOverride = 0;
907 if (field->isBitField()) {
908 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
909 assert(SizeInBitsOverride && "found named 0-width bitfield");
910 }
911
912 llvm::DIType fieldType
913 = createFieldType(name, type, SizeInBitsOverride,
914 field->getLocation(), field->getAccess(),
915 OffsetInBits, tunit, RecordTy);
916
917 elements.push_back(fieldType);
918}
919
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000920/// CollectRecordFields - A helper function to collect debug info for
921/// record fields. This is used while creating debug info entry for a Record.
922void CGDebugInfo::
923CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
924 SmallVectorImpl<llvm::Value *> &elements,
925 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000926 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
927
Eric Christopher0395de32013-01-16 01:22:32 +0000928 if (CXXDecl && CXXDecl->isLambda())
929 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
930 else {
931 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000932
Eric Christopher0395de32013-01-16 01:22:32 +0000933 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000934 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000935
936 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937 bool IsMsStruct = record->isMsStruct(CGM.getContext());
938 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000939
Eric Christopher0395de32013-01-16 01:22:32 +0000940 // Static and non-static members should appear in the same order as
941 // the corresponding declarations in the source program.
942 for (RecordDecl::decl_iterator I = record->decls_begin(),
943 E = record->decls_end(); I != E; ++I)
944 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
945 CollectRecordStaticField(V, elements, RecordTy);
946 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
947 if (IsMsStruct) {
948 // Zero-length bitfields following non-bitfield members are
949 // completely ignored; we don't even count them.
950 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
951 continue;
952 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000953 }
Eric Christopher0395de32013-01-16 01:22:32 +0000954 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
955 tunit, elements, RecordTy);
956
957 // Bump field number for next field.
958 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000959 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000960 }
961}
962
963/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
964/// function type is not updated to include implicit "this" pointer. Use this
965/// routine to get a method type which includes "this" pointer.
966llvm::DIType
967CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
968 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000969 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000970 if (Method->isStatic())
David Blaikie9c78f9b2013-01-07 23:06:35 +0000971 return getOrCreateType(QualType(Func, 0), Unit);
972 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
973 Func, Unit);
974}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000975
David Blaikie9c78f9b2013-01-07 23:06:35 +0000976llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
977 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000978 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 llvm::DIArray Args = llvm::DICompositeType(
980 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000981 assert (Args.getNumElements() && "Invalid number of arguments!");
982
983 SmallVector<llvm::Value *, 16> Elts;
984
985 // First element is always return type. For 'void' functions it is NULL.
986 Elts.push_back(Args.getElement(0));
987
David Blaikie67f8b5e2013-01-07 22:24:59 +0000988 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000989 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000990 if (isa<ClassTemplateSpecializationDecl>(RD)) {
991 // Create pointer type directly in this case.
992 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
993 QualType PointeeTy = ThisPtrTy->getPointeeType();
994 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000995 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000996 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
997 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000998 llvm::DIType ThisPtrType =
999 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001000 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1001 // TODO: This and the artificial type below are misleading, the
1002 // types aren't artificial the argument is, but the current
1003 // metadata doesn't represent that.
1004 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1005 Elts.push_back(ThisPtrType);
1006 } else {
1007 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1008 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1009 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1010 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001011 }
1012
1013 // Copy rest of the arguments.
1014 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1015 Elts.push_back(Args.getElement(i));
1016
1017 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1018
1019 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1020}
1021
Eric Christopher6537f082013-05-16 00:45:12 +00001022/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001023/// inside a function.
1024static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1025 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1026 return isFunctionLocalClass(NRD);
1027 if (isa<FunctionDecl>(RD->getDeclContext()))
1028 return true;
1029 return false;
1030}
1031
1032/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1033/// a single member function GlobalDecl.
1034llvm::DISubprogram
1035CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1036 llvm::DIFile Unit,
1037 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001038 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001039 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001040
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041 StringRef MethodName = getFunctionName(Method);
1042 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1043
1044 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1045 // make sense to give a single ctor/dtor a linkage name.
1046 StringRef MethodLinkageName;
1047 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1048 MethodLinkageName = CGM.getMangledName(Method);
1049
1050 // Get the location for the method.
1051 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1052 unsigned MethodLine = getLineNumber(Method->getLocation());
1053
1054 // Collect virtual method info.
1055 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001056 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001057 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001058
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001059 if (Method->isVirtual()) {
1060 if (Method->isPure())
1061 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1062 else
1063 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001065 // It doesn't make sense to give a virtual destructor a vtable index,
1066 // since a single destructor has two entries in the vtable.
1067 if (!isa<CXXDestructorDecl>(Method))
1068 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1069 ContainingType = RecordTy;
1070 }
1071
1072 unsigned Flags = 0;
1073 if (Method->isImplicit())
1074 Flags |= llvm::DIDescriptor::FlagArtificial;
1075 AccessSpecifier Access = Method->getAccess();
1076 if (Access == clang::AS_private)
1077 Flags |= llvm::DIDescriptor::FlagPrivate;
1078 else if (Access == clang::AS_protected)
1079 Flags |= llvm::DIDescriptor::FlagProtected;
1080 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1081 if (CXXC->isExplicit())
1082 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001083 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001084 dyn_cast<CXXConversionDecl>(Method)) {
1085 if (CXXC->isExplicit())
1086 Flags |= llvm::DIDescriptor::FlagExplicit;
1087 }
1088 if (Method->hasPrototype())
1089 Flags |= llvm::DIDescriptor::FlagPrototyped;
1090
1091 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1092 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001093 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001094 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001095 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001096 /* isDefinition=*/ false,
1097 Virtuality, VIndex, ContainingType,
1098 Flags, CGM.getLangOpts().Optimize, NULL,
1099 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001100
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001101 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1102
1103 return SP;
1104}
1105
1106/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001107/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001108/// a Record.
1109void CGDebugInfo::
1110CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1111 SmallVectorImpl<llvm::Value *> &EltTys,
1112 llvm::DIType RecordTy) {
1113
1114 // Since we want more than just the individual member decls if we
1115 // have templated functions iterate over every declaration to gather
1116 // the functions.
1117 for(DeclContext::decl_iterator I = RD->decls_begin(),
1118 E = RD->decls_end(); I != E; ++I) {
1119 Decl *D = *I;
1120 if (D->isImplicit() && !D->isUsed())
1121 continue;
1122
1123 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1124 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1125 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1126 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1127 SE = FTD->spec_end(); SI != SE; ++SI)
1128 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1129 RecordTy));
1130 }
Eric Christopher6537f082013-05-16 00:45:12 +00001131}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001132
1133/// CollectCXXFriends - A helper function to collect debug info for
1134/// C++ base classes. This is used while creating debug info entry for
1135/// a Record.
1136void CGDebugInfo::
1137CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1138 SmallVectorImpl<llvm::Value *> &EltTys,
1139 llvm::DIType RecordTy) {
1140 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1141 BE = RD->friend_end(); BI != BE; ++BI) {
1142 if ((*BI)->isUnsupportedFriend())
1143 continue;
1144 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001145 EltTys.push_back(DBuilder.createFriend(RecordTy,
1146 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001147 Unit)));
1148 }
1149}
1150
1151/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001152/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001153/// a Record.
1154void CGDebugInfo::
1155CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1156 SmallVectorImpl<llvm::Value *> &EltTys,
1157 llvm::DIType RecordTy) {
1158
1159 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1160 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1161 BE = RD->bases_end(); BI != BE; ++BI) {
1162 unsigned BFlags = 0;
1163 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001164
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001165 const CXXRecordDecl *Base =
1166 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001167
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001168 if (BI->isVirtual()) {
1169 // virtual base offset offset is -ve. The code generator emits dwarf
1170 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001171 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001172 0 - CGM.getVTableContext()
1173 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1174 BFlags = llvm::DIDescriptor::FlagVirtual;
1175 } else
1176 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1177 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1178 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001179
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 AccessSpecifier Access = BI->getAccessSpecifier();
1181 if (Access == clang::AS_private)
1182 BFlags |= llvm::DIDescriptor::FlagPrivate;
1183 else if (Access == clang::AS_protected)
1184 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001185
1186 llvm::DIType DTy =
1187 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001188 getOrCreateType(BI->getType(), Unit),
1189 BaseOffset, BFlags);
1190 EltTys.push_back(DTy);
1191 }
1192}
1193
1194/// CollectTemplateParams - A helper function to collect template parameters.
1195llvm::DIArray CGDebugInfo::
1196CollectTemplateParams(const TemplateParameterList *TPList,
1197 const TemplateArgumentList &TAList,
1198 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001199 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001200 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1201 const TemplateArgument &TA = TAList[i];
1202 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001203 switch (TA.getKind()) {
1204 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001205 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1206 llvm::DITemplateTypeParameter TTP =
1207 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1208 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001209 } break;
1210 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001211 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1212 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001213 DBuilder.createTemplateValueParameter(
1214 TheCU, ND->getName(), TTy,
1215 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1216 TemplateParams.push_back(TVP);
1217 } break;
1218 case TemplateArgument::Declaration: {
1219 const ValueDecl *D = TA.getAsDecl();
1220 bool InstanceMember = D->isCXXInstanceMember();
1221 QualType T = InstanceMember
1222 ? CGM.getContext().getMemberPointerType(
1223 D->getType(), cast<RecordDecl>(D->getDeclContext())
1224 ->getTypeForDecl())
1225 : CGM.getContext().getPointerType(D->getType());
1226 llvm::DIType TTy = getOrCreateType(T, Unit);
1227 llvm::Value *V = 0;
1228 // Variable pointer template parameters have a value that is the address
1229 // of the variable.
1230 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1231 V = CGM.GetAddrOfGlobalVar(VD);
1232 // Member function pointers have special support for building them, though
1233 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001234 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001235 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1236 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001237 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1238 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001239 // Member data pointers have special handling too to compute the fixed
1240 // offset within the object.
1241 if (isa<FieldDecl>(D)) {
1242 // These five lines (& possibly the above member function pointer
1243 // handling) might be able to be refactored to use similar code in
1244 // CodeGenModule::getMemberPointerConstant
1245 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1246 CharUnits chars =
1247 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1248 V = CGM.getCXXABI().EmitMemberDataPointer(
1249 cast<MemberPointerType>(T.getTypePtr()), chars);
1250 }
1251 llvm::DITemplateValueParameter TVP =
1252 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1253 TemplateParams.push_back(TVP);
1254 } break;
1255 case TemplateArgument::NullPtr: {
1256 QualType T = TA.getNullPtrType();
1257 llvm::DIType TTy = getOrCreateType(T, Unit);
1258 llvm::Value *V = 0;
1259 // Special case member data pointer null values since they're actually -1
1260 // instead of zero.
1261 if (const MemberPointerType *MPT =
1262 dyn_cast<MemberPointerType>(T.getTypePtr()))
1263 // But treat member function pointers as simple zero integers because
1264 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1265 // CodeGen grows handling for values of non-null member function
1266 // pointers then perhaps we could remove this special case and rely on
1267 // EmitNullMemberPointer for member function pointers.
1268 if (MPT->isMemberDataPointer())
1269 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1270 if (!V)
1271 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1272 llvm::DITemplateValueParameter TVP =
1273 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1274 TemplateParams.push_back(TVP);
1275 } break;
1276 case TemplateArgument::Template:
1277 // We could support this with the GCC extension
1278 // DW_TAG_GNU_template_template_param
1279 break;
David Blaikie776a3642013-05-10 22:53:25 +00001280 case TemplateArgument::Pack:
1281 // And this with DW_TAG_GNU_template_parameter_pack
1282 break;
David Blaikiee8065122013-05-10 23:36:06 +00001283 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001284 case TemplateArgument::Expression:
1285 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001286 case TemplateArgument::Null:
1287 llvm_unreachable(
1288 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001289 }
1290 }
1291 return DBuilder.getOrCreateArray(TemplateParams);
1292}
1293
1294/// CollectFunctionTemplateParams - A helper function to collect debug
1295/// info for function template parameters.
1296llvm::DIArray CGDebugInfo::
1297CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1298 if (FD->getTemplatedKind() ==
1299 FunctionDecl::TK_FunctionTemplateSpecialization) {
1300 const TemplateParameterList *TList =
1301 FD->getTemplateSpecializationInfo()->getTemplate()
1302 ->getTemplateParameters();
Eric Christopher6537f082013-05-16 00:45:12 +00001303 return
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001304 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1305 }
1306 return llvm::DIArray();
1307}
1308
1309/// CollectCXXTemplateParams - A helper function to collect debug info for
1310/// template parameters.
1311llvm::DIArray CGDebugInfo::
1312CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1313 llvm::DIFile Unit) {
1314 llvm::PointerUnion<ClassTemplateDecl *,
1315 ClassTemplatePartialSpecializationDecl *>
1316 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001317
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001318 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1319 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1320 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1321 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1322 return CollectTemplateParams(TPList, TAList, Unit);
1323}
1324
1325/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1326llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1327 if (VTablePtrType.isValid())
1328 return VTablePtrType;
1329
1330 ASTContext &Context = CGM.getContext();
1331
1332 /* Function type */
1333 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1334 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1335 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1336 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1337 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1338 "__vtbl_ptr_type");
1339 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1340 return VTablePtrType;
1341}
1342
1343/// getVTableName - Get vtable name for the given Class.
1344StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1345 // Construct gdb compatible name name.
1346 std::string Name = "_vptr$" + RD->getNameAsString();
1347
1348 // Copy this name on the side and use its reference.
1349 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1350 memcpy(StrPtr, Name.data(), Name.length());
1351 return StringRef(StrPtr, Name.length());
1352}
1353
1354
1355/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1356/// debug info entry in EltTys vector.
1357void CGDebugInfo::
1358CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1359 SmallVectorImpl<llvm::Value *> &EltTys) {
1360 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1361
1362 // If there is a primary base then it will hold vtable info.
1363 if (RL.getPrimaryBase())
1364 return;
1365
1366 // If this class is not dynamic then there is not any vtable info to collect.
1367 if (!RD->isDynamicClass())
1368 return;
1369
1370 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1371 llvm::DIType VPTR
1372 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001373 0, Size, 0, 0,
1374 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001375 getOrCreateVTablePtrType(Unit));
1376 EltTys.push_back(VPTR);
1377}
1378
Eric Christopher6537f082013-05-16 00:45:12 +00001379/// getOrCreateRecordType - Emit record type's standalone debug info.
1380llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001381 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001382 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001383 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1384 return T;
1385}
1386
1387/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1388/// debug info.
1389llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001390 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001391 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001393 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001394 return T;
1395}
1396
1397/// CreateType - get structure or union type.
1398llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1399 RecordDecl *RD = Ty->getDecl();
1400
1401 // Get overall information about the record type for the debug info.
1402 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1403
1404 // Records and classes and unions can all be recursive. To handle them, we
1405 // first generate a debug descriptor for the struct as a forward declaration.
1406 // Then (if it is a definition) we go through and get debug info for all of
1407 // its members. Finally, we create a descriptor for the complete type (which
1408 // may refer to the forward decl if the struct is recursive) and replace all
1409 // uses of the forward declaration with the final definition.
1410
Eric Christopherf068c922013-04-02 22:59:11 +00001411 llvm::DICompositeType FwdDecl(
1412 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1413 assert(FwdDecl.Verify() &&
1414 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001415
1416 if (FwdDecl.isForwardDecl())
1417 return FwdDecl;
1418
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001419 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001420 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001421 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1422
Adrian Prantl4919de62013-03-06 22:03:30 +00001423 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001424 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1425
1426 // Convert all the elements.
1427 SmallVector<llvm::Value *, 16> EltTys;
1428
1429 // Note: The split of CXXDecl information here is intentional, the
1430 // gdb tests will depend on a certain ordering at printout. The debug
1431 // information offsets are still correct if we merge them all together
1432 // though.
1433 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1434 if (CXXDecl) {
1435 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1436 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1437 }
1438
Eric Christopher0395de32013-01-16 01:22:32 +00001439 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001440 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1441 llvm::DIArray TParamsArray;
1442 if (CXXDecl) {
1443 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1444 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1445 if (const ClassTemplateSpecializationDecl *TSpecial
1446 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1447 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1448 }
1449
1450 LexicalBlockStack.pop_back();
1451 RegionMap.erase(Ty->getDecl());
1452
1453 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001454 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001455
Eric Christopherf068c922013-04-02 22:59:11 +00001456 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1457 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001458}
1459
1460/// CreateType - get objective-c object type.
1461llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1462 llvm::DIFile Unit) {
1463 // Ignore protocols.
1464 return getOrCreateType(Ty->getBaseType(), Unit);
1465}
1466
1467/// CreateType - get objective-c interface type.
1468llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1469 llvm::DIFile Unit) {
1470 ObjCInterfaceDecl *ID = Ty->getDecl();
1471 if (!ID)
1472 return llvm::DIType();
1473
1474 // Get overall information about the record type for the debug info.
1475 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1476 unsigned Line = getLineNumber(ID->getLocation());
1477 unsigned RuntimeLang = TheCU.getLanguage();
1478
1479 // If this is just a forward declaration return a special forward-declaration
1480 // debug type since we won't be able to lay out the entire type.
1481 ObjCInterfaceDecl *Def = ID->getDefinition();
1482 if (!Def) {
1483 llvm::DIType FwdDecl =
1484 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001485 ID->getName(), TheCU, DefUnit, Line,
1486 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001487 return FwdDecl;
1488 }
1489
1490 ID = Def;
1491
1492 // Bit size, align and offset of the type.
1493 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1494 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1495
1496 unsigned Flags = 0;
1497 if (ID->getImplementation())
1498 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1499
Eric Christopherf068c922013-04-02 22:59:11 +00001500 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001501 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1502 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001503 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001504
1505 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1506 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001507 QualType QualTy = QualType(Ty, 0);
1508 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001509 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001510
Eric Christopherf068c922013-04-02 22:59:11 +00001511 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001512 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1513
1514 // Convert all the elements.
1515 SmallVector<llvm::Value *, 16> EltTys;
1516
1517 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1518 if (SClass) {
1519 llvm::DIType SClassTy =
1520 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1521 if (!SClassTy.isValid())
1522 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001523
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001524 llvm::DIType InhTag =
1525 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1526 EltTys.push_back(InhTag);
1527 }
1528
1529 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1530 E = ID->prop_end(); I != E; ++I) {
1531 const ObjCPropertyDecl *PD = *I;
1532 SourceLocation Loc = PD->getLocation();
1533 llvm::DIFile PUnit = getOrCreateFile(Loc);
1534 unsigned PLine = getLineNumber(Loc);
1535 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1536 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1537 llvm::MDNode *PropertyNode =
1538 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001539 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001540 (Getter && Getter->isImplicit()) ? "" :
1541 getSelectorName(PD->getGetterName()),
1542 (Setter && Setter->isImplicit()) ? "" :
1543 getSelectorName(PD->getSetterName()),
1544 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001545 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001546 EltTys.push_back(PropertyNode);
1547 }
1548
1549 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1550 unsigned FieldNo = 0;
1551 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1552 Field = Field->getNextIvar(), ++FieldNo) {
1553 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1554 if (!FieldTy.isValid())
1555 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001556
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001557 StringRef FieldName = Field->getName();
1558
1559 // Ignore unnamed fields.
1560 if (FieldName.empty())
1561 continue;
1562
1563 // Get the location for the field.
1564 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1565 unsigned FieldLine = getLineNumber(Field->getLocation());
1566 QualType FType = Field->getType();
1567 uint64_t FieldSize = 0;
1568 unsigned FieldAlign = 0;
1569
1570 if (!FType->isIncompleteArrayType()) {
1571
1572 // Bit size, align and offset of the type.
1573 FieldSize = Field->isBitField()
1574 ? Field->getBitWidthValue(CGM.getContext())
1575 : CGM.getContext().getTypeSize(FType);
1576 FieldAlign = CGM.getContext().getTypeAlign(FType);
1577 }
1578
1579 uint64_t FieldOffset;
1580 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1581 // We don't know the runtime offset of an ivar if we're using the
1582 // non-fragile ABI. For bitfields, use the bit offset into the first
1583 // byte of storage of the bitfield. For other fields, use zero.
1584 if (Field->isBitField()) {
1585 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1586 CGM, ID, Field);
1587 FieldOffset %= CGM.getContext().getCharWidth();
1588 } else {
1589 FieldOffset = 0;
1590 }
1591 } else {
1592 FieldOffset = RL.getFieldOffset(FieldNo);
1593 }
1594
1595 unsigned Flags = 0;
1596 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1597 Flags = llvm::DIDescriptor::FlagProtected;
1598 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1599 Flags = llvm::DIDescriptor::FlagPrivate;
1600
1601 llvm::MDNode *PropertyNode = NULL;
1602 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001603 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001604 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1605 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001606 SourceLocation Loc = PD->getLocation();
1607 llvm::DIFile PUnit = getOrCreateFile(Loc);
1608 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001609 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1610 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1611 PropertyNode =
1612 DBuilder.createObjCProperty(PD->getName(),
1613 PUnit, PLine,
1614 (Getter && Getter->isImplicit()) ? "" :
1615 getSelectorName(PD->getGetterName()),
1616 (Setter && Setter->isImplicit()) ? "" :
1617 getSelectorName(PD->getSetterName()),
1618 PD->getPropertyAttributes(),
1619 getOrCreateType(PD->getType(), PUnit));
1620 }
1621 }
1622 }
1623 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1624 FieldLine, FieldSize, FieldAlign,
1625 FieldOffset, Flags, FieldTy,
1626 PropertyNode);
1627 EltTys.push_back(FieldTy);
1628 }
1629
1630 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001631 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001632
1633 // If the implementation is not yet set, we do not want to mark it
1634 // as complete. An implementation may declare additional
1635 // private ivars that we would miss otherwise.
1636 if (ID->getImplementation() == 0)
1637 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001638
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001640 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001641}
1642
1643llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1644 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1645 int64_t Count = Ty->getNumElements();
1646 if (Count == 0)
1647 // If number of elements are not known then this is an unbounded array.
1648 // Use Count == -1 to express such arrays.
1649 Count = -1;
1650
1651 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1652 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1653
1654 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1655 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1656
1657 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1658}
1659
1660llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1661 llvm::DIFile Unit) {
1662 uint64_t Size;
1663 uint64_t Align;
1664
1665 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1666 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1667 Size = 0;
1668 Align =
1669 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1670 } else if (Ty->isIncompleteArrayType()) {
1671 Size = 0;
1672 if (Ty->getElementType()->isIncompleteType())
1673 Align = 0;
1674 else
1675 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001676 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001677 Size = 0;
1678 Align = 0;
1679 } else {
1680 // Size and align of the whole array, not the element type.
1681 Size = CGM.getContext().getTypeSize(Ty);
1682 Align = CGM.getContext().getTypeAlign(Ty);
1683 }
1684
1685 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1686 // interior arrays, do we care? Why aren't nested arrays represented the
1687 // obvious/recursive way?
1688 SmallVector<llvm::Value *, 8> Subscripts;
1689 QualType EltTy(Ty, 0);
1690 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1691 // If the number of elements is known, then count is that number. Otherwise,
1692 // it's -1. This allows us to represent a subrange with an array of 0
1693 // elements, like this:
1694 //
1695 // struct foo {
1696 // int x[0];
1697 // };
1698 int64_t Count = -1; // Count == -1 is an unbounded array.
1699 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1700 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001701
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001702 // FIXME: Verify this is right for VLAs.
1703 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1704 EltTy = Ty->getElementType();
1705 }
1706
1707 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1708
Eric Christopher6537f082013-05-16 00:45:12 +00001709 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001710 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1711 SubscriptArray);
1712 return DbgTy;
1713}
1714
Eric Christopher6537f082013-05-16 00:45:12 +00001715llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001716 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001717 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001718 Ty, Ty->getPointeeType(), Unit);
1719}
1720
Eric Christopher6537f082013-05-16 00:45:12 +00001721llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001722 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001723 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001724 Ty, Ty->getPointeeType(), Unit);
1725}
1726
Eric Christopher6537f082013-05-16 00:45:12 +00001727llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001728 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001729 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1730 if (!Ty->getPointeeType()->isFunctionType())
1731 return DBuilder.createMemberPointerType(
1732 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1733 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1734 CGM.getContext().getPointerType(
1735 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1736 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1737 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001738}
1739
Eric Christopher6537f082013-05-16 00:45:12 +00001740llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001741 llvm::DIFile U) {
1742 // Ignore the atomic wrapping
1743 // FIXME: What is the correct representation?
1744 return getOrCreateType(Ty->getValueType(), U);
1745}
1746
1747/// CreateEnumType - get enumeration type.
1748llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1749 uint64_t Size = 0;
1750 uint64_t Align = 0;
1751 if (!ED->getTypeForDecl()->isIncompleteType()) {
1752 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1753 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1754 }
1755
1756 // If this is just a forward declaration, construct an appropriately
1757 // marked node and just return it.
1758 if (!ED->getDefinition()) {
1759 llvm::DIDescriptor EDContext;
1760 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1761 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1762 unsigned Line = getLineNumber(ED->getLocation());
1763 StringRef EDName = ED->getName();
1764 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1765 EDName, EDContext, DefUnit, Line, 0,
1766 Size, Align);
1767 }
1768
1769 // Create DIEnumerator elements for each enumerator.
1770 SmallVector<llvm::Value *, 16> Enumerators;
1771 ED = ED->getDefinition();
1772 for (EnumDecl::enumerator_iterator
1773 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1774 Enum != EnumEnd; ++Enum) {
1775 Enumerators.push_back(
1776 DBuilder.createEnumerator(Enum->getName(),
1777 Enum->getInitVal().getZExtValue()));
1778 }
1779
1780 // Return a CompositeType for the enum itself.
1781 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1782
1783 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1784 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001785 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001787 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001788 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001789 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001790 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1791 Size, Align, EltArray,
1792 ClassTy);
1793 return DbgTy;
1794}
1795
David Blaikie4b12be62013-01-21 04:37:12 +00001796static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1797 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001798 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001799 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001800 QualType LastT = T;
1801 switch (T->getTypeClass()) {
1802 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001803 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001804 case Type::TemplateSpecialization:
1805 T = cast<TemplateSpecializationType>(T)->desugar();
1806 break;
1807 case Type::TypeOfExpr:
1808 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1809 break;
1810 case Type::TypeOf:
1811 T = cast<TypeOfType>(T)->getUnderlyingType();
1812 break;
1813 case Type::Decltype:
1814 T = cast<DecltypeType>(T)->getUnderlyingType();
1815 break;
1816 case Type::UnaryTransform:
1817 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1818 break;
1819 case Type::Attributed:
1820 T = cast<AttributedType>(T)->getEquivalentType();
1821 break;
1822 case Type::Elaborated:
1823 T = cast<ElaboratedType>(T)->getNamedType();
1824 break;
1825 case Type::Paren:
1826 T = cast<ParenType>(T)->getInnerType();
1827 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001828 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001830 break;
1831 case Type::Auto:
1832 T = cast<AutoType>(T)->getDeducedType();
1833 break;
1834 }
Eric Christopher6537f082013-05-16 00:45:12 +00001835
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001836 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001837 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001838 } while (true);
1839}
1840
Eric Christopherf0890c42013-05-16 00:52:20 +00001841/// getType - Get the type from the cache or return null type if it doesn't
1842/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001843llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1844
1845 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001846 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001847
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001848 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001849 if (Ty->getTypeClass() == Type::ObjCInterface) {
1850 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1851 if (V)
1852 return llvm::DIType(cast<llvm::MDNode>(V));
1853 else return llvm::DIType();
1854 }
1855
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001856 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1857 TypeCache.find(Ty.getAsOpaquePtr());
1858 if (it != TypeCache.end()) {
1859 // Verify that the debug info still exists.
1860 if (llvm::Value *V = it->second)
1861 return llvm::DIType(cast<llvm::MDNode>(V));
1862 }
1863
1864 return llvm::DIType();
1865}
1866
1867/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1868/// doesn't exist.
1869llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1870
1871 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001872 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001873
1874 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001875 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001876 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1877 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001878 if (it != CompletedTypeCache.end())
1879 V = it->second;
1880 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001881 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001882 }
1883
Adrian Prantl4919de62013-03-06 22:03:30 +00001884 // Verify that any cached debug info still exists.
1885 if (V != 0)
1886 return llvm::DIType(cast<llvm::MDNode>(V));
1887
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001888 return llvm::DIType();
1889}
1890
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001891/// getCachedInterfaceTypeOrNull - Get the type from the interface
1892/// cache, unless it needs to regenerated. Otherwise return null.
1893llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1894 // Is there a cached interface that hasn't changed?
1895 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1896 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1897
1898 if (it1 != ObjCInterfaceCache.end())
1899 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1900 if (Checksum(Decl) == it1->second.second)
1901 // Return cached forward declaration.
1902 return it1->second.first;
1903
1904 return 0;
1905}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001906
1907/// getOrCreateType - Get the type from the cache or create a new
1908/// one if necessary.
1909llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1910 if (Ty.isNull())
1911 return llvm::DIType();
1912
1913 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001914 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001915
1916 llvm::DIType T = getCompletedTypeOrNull(Ty);
1917
1918 if (T.Verify())
1919 return T;
1920
1921 // Otherwise create the type.
1922 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001923 void* TyPtr = Ty.getAsOpaquePtr();
1924
1925 // And update the type cache.
1926 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001927
1928 llvm::DIType TC = getTypeOrNull(Ty);
1929 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001930 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1931 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1932 // Interface types may have elements added to them by a
1933 // subsequent implementation or extension, so we keep them in
1934 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001935 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001936 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1937 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1938 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1939 if (it != ObjCInterfaceCache.end())
1940 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1941 else
1942 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001943 Decl->getName(), TheCU, Unit,
1944 getLineNumber(Decl->getLocation()),
1945 TheCU.getLanguage());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001946 // Store the forward declaration in the cache.
1947 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1948
1949 // Register the type for replacement in finalize().
1950 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1951 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001952 }
1953
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001954 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001955 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001956
1957 return Res;
1958}
1959
Adrian Prantl4919de62013-03-06 22:03:30 +00001960/// Currently the checksum merely consists of the number of ivars.
1961unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001962 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001963 unsigned IvarNo = 0;
1964 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1965 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1966 return IvarNo;
1967}
1968
1969ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1970 switch (Ty->getTypeClass()) {
1971 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00001972 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1973 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00001974 case Type::ObjCInterface:
1975 return cast<ObjCInterfaceType>(Ty)->getDecl();
1976 default:
1977 return 0;
1978 }
1979}
1980
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001981/// CreateTypeNode - Create a new debug type node.
1982llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1983 // Handle qualifiers, which recursively handles what they refer to.
1984 if (Ty.hasLocalQualifiers())
1985 return CreateQualifiedType(Ty, Unit);
1986
1987 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001988
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001989 // Work out details of type.
1990 switch (Ty->getTypeClass()) {
1991#define TYPE(Class, Base)
1992#define ABSTRACT_TYPE(Class, Base)
1993#define NON_CANONICAL_TYPE(Class, Base)
1994#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1995#include "clang/AST/TypeNodes.def"
1996 llvm_unreachable("Dependent types cannot show up in debug information");
1997
1998 case Type::ExtVector:
1999 case Type::Vector:
2000 return CreateType(cast<VectorType>(Ty), Unit);
2001 case Type::ObjCObjectPointer:
2002 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2003 case Type::ObjCObject:
2004 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2005 case Type::ObjCInterface:
2006 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2007 case Type::Builtin:
2008 return CreateType(cast<BuiltinType>(Ty));
2009 case Type::Complex:
2010 return CreateType(cast<ComplexType>(Ty));
2011 case Type::Pointer:
2012 return CreateType(cast<PointerType>(Ty), Unit);
2013 case Type::BlockPointer:
2014 return CreateType(cast<BlockPointerType>(Ty), Unit);
2015 case Type::Typedef:
2016 return CreateType(cast<TypedefType>(Ty), Unit);
2017 case Type::Record:
2018 return CreateType(cast<RecordType>(Ty));
2019 case Type::Enum:
2020 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2021 case Type::FunctionProto:
2022 case Type::FunctionNoProto:
2023 return CreateType(cast<FunctionType>(Ty), Unit);
2024 case Type::ConstantArray:
2025 case Type::VariableArray:
2026 case Type::IncompleteArray:
2027 return CreateType(cast<ArrayType>(Ty), Unit);
2028
2029 case Type::LValueReference:
2030 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2031 case Type::RValueReference:
2032 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2033
2034 case Type::MemberPointer:
2035 return CreateType(cast<MemberPointerType>(Ty), Unit);
2036
2037 case Type::Atomic:
2038 return CreateType(cast<AtomicType>(Ty), Unit);
2039
2040 case Type::Attributed:
2041 case Type::TemplateSpecialization:
2042 case Type::Elaborated:
2043 case Type::Paren:
2044 case Type::SubstTemplateTypeParm:
2045 case Type::TypeOfExpr:
2046 case Type::TypeOf:
2047 case Type::Decltype:
2048 case Type::UnaryTransform:
2049 case Type::Auto:
2050 llvm_unreachable("type should have been unwrapped!");
2051 }
Eric Christopher6537f082013-05-16 00:45:12 +00002052
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002053 assert(Diag && "Fall through without a diagnostic?");
2054 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2055 "debug information for %0 is not yet supported");
2056 CGM.getDiags().Report(DiagID)
2057 << Diag;
2058 return llvm::DIType();
2059}
2060
2061/// getOrCreateLimitedType - Get the type from the cache or create a new
2062/// limited type if necessary.
2063llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002064 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002065 if (Ty.isNull())
2066 return llvm::DIType();
2067
2068 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002069 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002070
2071 llvm::DIType T = getTypeOrNull(Ty);
2072
2073 // We may have cached a forward decl when we could have created
2074 // a non-forward decl. Go ahead and create a non-forward decl
2075 // now.
2076 if (T.Verify() && !T.isForwardDecl()) return T;
2077
2078 // Otherwise create the type.
2079 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2080
2081 if (T.Verify() && T.isForwardDecl())
2082 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2083 static_cast<llvm::Value*>(T)));
2084
2085 // And update the type cache.
2086 TypeCache[Ty.getAsOpaquePtr()] = Res;
2087 return Res;
2088}
2089
2090// TODO: Currently used for context chains when limiting debug info.
2091llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2092 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002093
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002094 // Get overall information about the record type for the debug info.
2095 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2096 unsigned Line = getLineNumber(RD->getLocation());
2097 StringRef RDName = getClassName(RD);
2098
2099 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002100 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002101 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2102 else
2103 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2104
2105 // If this is just a forward declaration, construct an appropriately
2106 // marked node and just return it.
2107 if (!RD->getDefinition())
2108 return createRecordFwdDecl(RD, RDContext);
2109
2110 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2111 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2112 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002113 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002114
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002115 if (RD->isUnion())
2116 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002117 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002118 else if (RD->isClass()) {
2119 // FIXME: This could be a struct type giving a default visibility different
2120 // than C++ class type, but needs llvm metadata changes first.
2121 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002122 Size, Align, 0, 0, llvm::DIType(),
2123 llvm::DIArray(), llvm::DIType(),
2124 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002125 } else
2126 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002127 Size, Align, 0, llvm::DIType(),
2128 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002129
2130 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002131 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002132
2133 if (CXXDecl) {
2134 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002135 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2137 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2138 // Seek non virtual primary base root.
2139 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002140 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2141 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2142 if (PBT && !BRL.isPrimaryBaseVirtual())
2143 PBase = PBT;
2144 else
2145 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002146 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002147 ContainingType = llvm::DICompositeType(
2148 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2149 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002150 ContainingType = RealDecl;
2151
David Blaikie2fcadbe2013-03-26 23:47:35 +00002152 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002153 }
2154 return llvm::DIType(RealDecl);
2155}
2156
2157/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2158/// declare composite types that haven't been processed yet.
2159llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2160
2161 // Work out details of type.
2162 switch (Ty->getTypeClass()) {
2163#define TYPE(Class, Base)
2164#define ABSTRACT_TYPE(Class, Base)
2165#define NON_CANONICAL_TYPE(Class, Base)
2166#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2167 #include "clang/AST/TypeNodes.def"
2168 llvm_unreachable("Dependent types cannot show up in debug information");
2169
2170 case Type::Record:
2171 return CreateLimitedType(cast<RecordType>(Ty));
2172 default:
2173 return CreateTypeNode(Ty, Unit);
2174 }
2175}
2176
2177/// CreateMemberType - Create new member and increase Offset by FType's size.
2178llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2179 StringRef Name,
2180 uint64_t *Offset) {
2181 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2182 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2183 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2184 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2185 FieldSize, FieldAlign,
2186 *Offset, 0, FieldTy);
2187 *Offset += FieldSize;
2188 return Ty;
2189}
2190
David Blaikie9faebd22013-05-20 04:58:53 +00002191llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2192 // We only need a declaration (not a definition) of the type - so use whatever
2193 // we would otherwise do to get a type for a pointee. (forward declarations in
2194 // limited debug info, full definitions (if the type definition is available)
2195 // in unlimited debug info)
2196 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2197 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
2198 return CreatePointeeType(CGM.getContext().getTypeDeclType(TD), DefUnit);
2199 }
2200 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2201 // This doesn't handle providing declarations (for functions or variables) for
2202 // entities without definitions in this TU, nor when the definition proceeds
2203 // the call to this function.
2204 // FIXME: This should be split out into more specific maps with support for
2205 // emitting forward declarations and merging definitions with declarations,
2206 // the same way as we do for types.
2207 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2208 DeclCache.find(D->getCanonicalDecl());
2209 if (I == DeclCache.end())
2210 return llvm::DIDescriptor();
2211 llvm::Value *V = I->second;
2212 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2213}
2214
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002215/// getFunctionDeclaration - Return debug info descriptor to describe method
2216/// declaration for the given method definition.
2217llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2218 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2219 if (!FD) return llvm::DISubprogram();
2220
2221 // Setup context.
2222 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2223
2224 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2225 MI = SPCache.find(FD->getCanonicalDecl());
2226 if (MI != SPCache.end()) {
2227 llvm::Value *V = MI->second;
2228 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2229 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2230 return SP;
2231 }
2232
2233 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2234 E = FD->redecls_end(); I != E; ++I) {
2235 const FunctionDecl *NextFD = *I;
2236 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2237 MI = SPCache.find(NextFD->getCanonicalDecl());
2238 if (MI != SPCache.end()) {
2239 llvm::Value *V = MI->second;
2240 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2241 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2242 return SP;
2243 }
2244 }
2245 return llvm::DISubprogram();
2246}
2247
2248// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2249// implicit parameter "this".
2250llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2251 QualType FnType,
2252 llvm::DIFile F) {
2253
2254 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2255 return getOrCreateMethodType(Method, F);
2256 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2257 // Add "self" and "_cmd"
2258 SmallVector<llvm::Value *, 16> Elts;
2259
2260 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002261 QualType ResultTy = OMethod->hasRelatedResultType()
2262 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2263 : OMethod->getResultType();
2264 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002265 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002266 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2267 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2268 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002269 // "_cmd" pointer is always second argument.
2270 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2271 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2272 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002273 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002274 PE = OMethod->param_end(); PI != PE; ++PI)
2275 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2276
2277 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2278 return DBuilder.createSubroutineType(F, EltTypeArray);
2279 }
2280 return getOrCreateType(FnType, F);
2281}
2282
2283/// EmitFunctionStart - Constructs the debug code for entering a function.
2284void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2285 llvm::Function *Fn,
2286 CGBuilderTy &Builder) {
2287
2288 StringRef Name;
2289 StringRef LinkageName;
2290
2291 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2292
2293 const Decl *D = GD.getDecl();
2294 // Function may lack declaration in source code if it is created by Clang
2295 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2296 bool HasDecl = (D != 0);
2297 // Use the location of the declaration.
2298 SourceLocation Loc;
2299 if (HasDecl)
2300 Loc = D->getLocation();
2301
2302 unsigned Flags = 0;
2303 llvm::DIFile Unit = getOrCreateFile(Loc);
2304 llvm::DIDescriptor FDContext(Unit);
2305 llvm::DIArray TParamsArray;
2306 if (!HasDecl) {
2307 // Use llvm function name.
2308 Name = Fn->getName();
2309 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2310 // If there is a DISubprogram for this function available then use it.
2311 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2312 FI = SPCache.find(FD->getCanonicalDecl());
2313 if (FI != SPCache.end()) {
2314 llvm::Value *V = FI->second;
2315 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2316 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2317 llvm::MDNode *SPN = SP;
2318 LexicalBlockStack.push_back(SPN);
2319 RegionMap[D] = llvm::WeakVH(SP);
2320 return;
2321 }
2322 }
2323 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002324 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002325 if (FD->hasPrototype()) {
2326 LinkageName = CGM.getMangledName(GD);
2327 Flags |= llvm::DIDescriptor::FlagPrototyped;
2328 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002329 // No need to replicate the linkage name if it isn't different from the
2330 // subprogram name, no need to have it at all unless coverage is enabled or
2331 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002332 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002333 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2334 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002335 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002336 LinkageName = StringRef();
2337
Eric Christopher13c97672013-05-16 00:45:23 +00002338 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002339 if (const NamespaceDecl *NSDecl =
2340 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2341 FDContext = getOrCreateNameSpace(NSDecl);
2342 else if (const RecordDecl *RDecl =
2343 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2344 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2345
2346 // Collect template parameters.
2347 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2348 }
2349 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2350 Name = getObjCMethodName(OMD);
2351 Flags |= llvm::DIDescriptor::FlagPrototyped;
2352 } else {
2353 // Use llvm function name.
2354 Name = Fn->getName();
2355 Flags |= llvm::DIDescriptor::FlagPrototyped;
2356 }
2357 if (!Name.empty() && Name[0] == '\01')
2358 Name = Name.substr(1);
2359
2360 unsigned LineNo = getLineNumber(Loc);
2361 if (!HasDecl || D->isImplicit())
2362 Flags |= llvm::DIDescriptor::FlagArtificial;
2363
2364 llvm::DIType DIFnType;
2365 llvm::DISubprogram SPDecl;
2366 if (HasDecl &&
Eric Christopher13c97672013-05-16 00:45:23 +00002367 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002368 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2369 SPDecl = getFunctionDeclaration(D);
2370 } else {
2371 // Create fake but valid subroutine type. Otherwise
2372 // llvm::DISubprogram::Verify() would return false, and
2373 // subprogram DIE will miss DW_AT_decl_file and
2374 // DW_AT_decl_line fields.
2375 SmallVector<llvm::Value*, 16> Elts;
2376 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2377 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2378 }
2379 llvm::DISubprogram SP;
2380 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2381 LineNo, DIFnType,
2382 Fn->hasInternalLinkage(), true/*definition*/,
2383 getLineNumber(CurLoc), Flags,
2384 CGM.getLangOpts().Optimize,
2385 Fn, TParamsArray, SPDecl);
David Blaikie9faebd22013-05-20 04:58:53 +00002386 if (HasDecl)
2387 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002388
2389 // Push function on region stack.
2390 llvm::MDNode *SPN = SP;
2391 LexicalBlockStack.push_back(SPN);
2392 if (HasDecl)
2393 RegionMap[D] = llvm::WeakVH(SP);
2394}
2395
2396/// EmitLocation - Emit metadata to indicate a change in line/column
2397/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002398void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2399 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002400
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002401 // Update our current location
2402 setLocation(Loc);
2403
2404 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2405
2406 // Don't bother if things are the same as last time.
2407 SourceManager &SM = CGM.getContext().getSourceManager();
2408 if (CurLoc == PrevLoc ||
2409 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2410 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002411 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2412 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2413 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002414 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002415
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002416 // Update last state.
2417 PrevLoc = CurLoc;
2418
2419 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002420 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2421 (getLineNumber(CurLoc),
2422 getColumnNumber(CurLoc, ForceColumnInfo),
2423 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002424}
2425
2426/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2427/// the stack.
2428void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2429 llvm::DIDescriptor D =
2430 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2431 llvm::DIDescriptor() :
2432 llvm::DIDescriptor(LexicalBlockStack.back()),
2433 getOrCreateFile(CurLoc),
2434 getLineNumber(CurLoc),
2435 getColumnNumber(CurLoc));
2436 llvm::MDNode *DN = D;
2437 LexicalBlockStack.push_back(DN);
2438}
2439
2440/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2441/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002442void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2443 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002444 // Set our current location.
2445 setLocation(Loc);
2446
2447 // Create a new lexical block and push it on the stack.
2448 CreateLexicalBlock(Loc);
2449
2450 // Emit a line table change for the current location inside the new scope.
2451 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2452 getColumnNumber(Loc),
2453 LexicalBlockStack.back()));
2454}
2455
2456/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2457/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002458void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2459 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002460 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2461
2462 // Provide an entry in the line table for the end of the block.
2463 EmitLocation(Builder, Loc);
2464
2465 LexicalBlockStack.pop_back();
2466}
2467
2468/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2469void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2470 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2471 unsigned RCount = FnBeginRegionCount.back();
2472 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2473
2474 // Pop all regions for this function.
2475 while (LexicalBlockStack.size() != RCount)
2476 EmitLexicalBlockEnd(Builder, CurLoc);
2477 FnBeginRegionCount.pop_back();
2478}
2479
Eric Christopher6537f082013-05-16 00:45:12 +00002480// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002481// See BuildByRefType.
2482llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2483 uint64_t *XOffset) {
2484
2485 SmallVector<llvm::Value *, 5> EltTys;
2486 QualType FType;
2487 uint64_t FieldSize, FieldOffset;
2488 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002489
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002490 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002491 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002492
2493 FieldOffset = 0;
2494 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2495 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2496 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2497 FType = CGM.getContext().IntTy;
2498 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2499 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2500
2501 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2502 if (HasCopyAndDispose) {
2503 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2504 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2505 &FieldOffset));
2506 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2507 &FieldOffset));
2508 }
2509 bool HasByrefExtendedLayout;
2510 Qualifiers::ObjCLifetime Lifetime;
2511 if (CGM.getContext().getByrefLifetime(Type,
2512 Lifetime, HasByrefExtendedLayout)
2513 && HasByrefExtendedLayout)
2514 EltTys.push_back(CreateMemberType(Unit, FType,
2515 "__byref_variable_layout",
2516 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002517
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002518 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2519 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002520 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002521 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002522 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2523 CharUnits AlignedOffsetInBytes
2524 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2525 CharUnits NumPaddingBytes
2526 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002527
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002528 if (NumPaddingBytes.isPositive()) {
2529 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2530 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2531 pad, ArrayType::Normal, 0);
2532 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2533 }
2534 }
Eric Christopher6537f082013-05-16 00:45:12 +00002535
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002536 FType = Type;
2537 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2538 FieldSize = CGM.getContext().getTypeSize(FType);
2539 FieldAlign = CGM.getContext().toBits(Align);
2540
Eric Christopher6537f082013-05-16 00:45:12 +00002541 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002542 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2543 0, FieldSize, FieldAlign,
2544 FieldOffset, 0, FieldTy);
2545 EltTys.push_back(FieldTy);
2546 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002547
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002549
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002550 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002551
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002552 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002553 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002554}
2555
2556/// EmitDeclare - Emit local variable declaration debug info.
2557void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002558 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002559 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002560 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002561 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2562
2563 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2564 llvm::DIType Ty;
2565 uint64_t XOffset = 0;
2566 if (VD->hasAttr<BlocksAttr>())
2567 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002568 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002569 Ty = getOrCreateType(VD->getType(), Unit);
2570
2571 // If there is no debug info for this type then do not emit debug info
2572 // for this variable.
2573 if (!Ty)
2574 return;
2575
2576 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2577 // If Storage is an aggregate returned as 'sret' then let debugger know
2578 // about this.
2579 if (Arg->hasStructRetAttr())
2580 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2581 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2582 // If an aggregate variable has non trivial destructor or non trivial copy
2583 // constructor than it is pass indirectly. Let debug info know about this
2584 // by using reference of the aggregate type as a argument type.
2585 if (Record->hasNonTrivialCopyConstructor() ||
2586 !Record->hasTrivialDestructor())
Eric Christopherf0890c42013-05-16 00:52:20 +00002587 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type,
2588 Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002589 }
2590 }
Eric Christopher6537f082013-05-16 00:45:12 +00002591
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002592 // Get location information.
2593 unsigned Line = getLineNumber(VD->getLocation());
2594 unsigned Column = getColumnNumber(VD->getLocation());
2595 unsigned Flags = 0;
2596 if (VD->isImplicit())
2597 Flags |= llvm::DIDescriptor::FlagArtificial;
2598 // If this is the first argument and it is implicit then
2599 // give it an object pointer flag.
2600 // FIXME: There has to be a better way to do this, but for static
2601 // functions there won't be an implicit param at arg1 and
2602 // otherwise it is 'self' or 'this'.
2603 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2604 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2605
2606 llvm::MDNode *Scope = LexicalBlockStack.back();
2607
2608 StringRef Name = VD->getName();
2609 if (!Name.empty()) {
2610 if (VD->hasAttr<BlocksAttr>()) {
2611 CharUnits offset = CharUnits::fromQuantity(32);
2612 SmallVector<llvm::Value *, 9> addr;
2613 llvm::Type *Int64Ty = CGM.Int64Ty;
2614 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2615 // offset of __forwarding field
2616 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002617 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002618 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2619 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2620 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2621 // offset of x field
2622 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2623 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2624
2625 // Create the descriptor for the variable.
2626 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002627 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002628 llvm::DIDescriptor(Scope),
2629 VD->getName(), Unit, Line, Ty,
2630 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002631
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002632 // Insert an llvm.dbg.declare into the current block.
2633 llvm::Instruction *Call =
2634 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2635 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2636 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002637 } else if (isa<VariableArrayType>(VD->getType())) {
2638 // These are "complex" variables in that they need an op_deref.
2639 // Create the descriptor for the variable.
2640 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2641 llvm::DIBuilder::OpDeref);
2642 llvm::DIVariable D =
2643 DBuilder.createComplexVariable(Tag,
2644 llvm::DIDescriptor(Scope),
2645 Name, Unit, Line, Ty,
2646 Addr, ArgNo);
2647
2648 // Insert an llvm.dbg.declare into the current block.
2649 llvm::Instruction *Call =
2650 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2651 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2652 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002653 }
David Blaikie436653b2013-01-05 05:58:35 +00002654 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2655 // If VD is an anonymous union then Storage represents value for
2656 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002657 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002658 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002659 for (RecordDecl::field_iterator I = RD->field_begin(),
2660 E = RD->field_end();
2661 I != E; ++I) {
2662 FieldDecl *Field = *I;
2663 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2664 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002665
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002666 // Ignore unnamed fields. Do not ignore unnamed records.
2667 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2668 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002669
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002670 // Use VarDecl's Tag, Scope and Line number.
2671 llvm::DIVariable D =
2672 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002673 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002674 CGM.getLangOpts().Optimize, Flags,
2675 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002676
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002677 // Insert an llvm.dbg.declare into the current block.
2678 llvm::Instruction *Call =
2679 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2680 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2681 }
David Blaikied8180cf2013-01-05 20:03:07 +00002682 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683 }
2684 }
David Blaikie436653b2013-01-05 05:58:35 +00002685
2686 // Create the descriptor for the variable.
2687 llvm::DIVariable D =
2688 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2689 Name, Unit, Line, Ty,
2690 CGM.getLangOpts().Optimize, Flags, ArgNo);
2691
2692 // Insert an llvm.dbg.declare into the current block.
2693 llvm::Instruction *Call =
2694 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2695 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696}
2697
2698void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2699 llvm::Value *Storage,
2700 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002701 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002702 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2703}
2704
Adrian Prantle86fcc42013-03-29 19:20:29 +00002705/// Look up the completed type for a self pointer in the TypeCache and
2706/// create a copy of it with the ObjectPointer and Artificial flags
2707/// set. If the type is not cached, a new one is created. This should
2708/// never happen though, since creating a type for the implicit self
2709/// argument implies that we already parsed the interface definition
2710/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002711llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2712 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002713 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2714 if (CachedTy.Verify()) Ty = CachedTy;
2715 else DEBUG(llvm::dbgs() << "No cached type for self.");
2716 return DBuilder.createObjectPointerType(Ty);
2717}
2718
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2720 llvm::Value *Storage,
2721 CGBuilderTy &Builder,
2722 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002723 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002724 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002725
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002726 if (Builder.GetInsertBlock() == 0)
2727 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002728
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002729 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002730
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002731 uint64_t XOffset = 0;
2732 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2733 llvm::DIType Ty;
2734 if (isByRef)
2735 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002736 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002737 Ty = getOrCreateType(VD->getType(), Unit);
2738
2739 // Self is passed along as an implicit non-arg variable in a
2740 // block. Mark it as the object pointer.
2741 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002742 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002743
2744 // Get location information.
2745 unsigned Line = getLineNumber(VD->getLocation());
2746 unsigned Column = getColumnNumber(VD->getLocation());
2747
2748 const llvm::DataLayout &target = CGM.getDataLayout();
2749
2750 CharUnits offset = CharUnits::fromQuantity(
2751 target.getStructLayout(blockInfo.StructureType)
2752 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2753
2754 SmallVector<llvm::Value *, 9> addr;
2755 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002756 if (isa<llvm::AllocaInst>(Storage))
2757 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002758 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2759 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2760 if (isByRef) {
2761 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2762 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2763 // offset of __forwarding field
2764 offset = CGM.getContext()
2765 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2766 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2767 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2768 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2769 // offset of x field
2770 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2771 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2772 }
2773
2774 // Create the descriptor for the variable.
2775 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002776 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002777 llvm::DIDescriptor(LexicalBlockStack.back()),
2778 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002779
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002780 // Insert an llvm.dbg.declare into the current block.
2781 llvm::Instruction *Call =
2782 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2783 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2784 LexicalBlockStack.back()));
2785}
2786
2787/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2788/// variable declaration.
2789void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2790 unsigned ArgNo,
2791 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002792 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002793 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2794}
2795
2796namespace {
2797 struct BlockLayoutChunk {
2798 uint64_t OffsetInBits;
2799 const BlockDecl::Capture *Capture;
2800 };
2801 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2802 return l.OffsetInBits < r.OffsetInBits;
2803 }
2804}
2805
2806void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002807 llvm::Value *Arg,
2808 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002809 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002810 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002811 ASTContext &C = CGM.getContext();
2812 const BlockDecl *blockDecl = block.getBlockDecl();
2813
2814 // Collect some general information about the block's location.
2815 SourceLocation loc = blockDecl->getCaretLocation();
2816 llvm::DIFile tunit = getOrCreateFile(loc);
2817 unsigned line = getLineNumber(loc);
2818 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002819
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002820 // Build the debug-info type for the block literal.
2821 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2822
2823 const llvm::StructLayout *blockLayout =
2824 CGM.getDataLayout().getStructLayout(block.StructureType);
2825
2826 SmallVector<llvm::Value*, 16> fields;
2827 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2828 blockLayout->getElementOffsetInBits(0),
2829 tunit, tunit));
2830 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2831 blockLayout->getElementOffsetInBits(1),
2832 tunit, tunit));
2833 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2834 blockLayout->getElementOffsetInBits(2),
2835 tunit, tunit));
2836 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2837 blockLayout->getElementOffsetInBits(3),
2838 tunit, tunit));
2839 fields.push_back(createFieldType("__descriptor",
2840 C.getPointerType(block.NeedsCopyDispose ?
2841 C.getBlockDescriptorExtendedType() :
2842 C.getBlockDescriptorType()),
2843 0, loc, AS_public,
2844 blockLayout->getElementOffsetInBits(4),
2845 tunit, tunit));
2846
2847 // We want to sort the captures by offset, not because DWARF
2848 // requires this, but because we're paranoid about debuggers.
2849 SmallVector<BlockLayoutChunk, 8> chunks;
2850
2851 // 'this' capture.
2852 if (blockDecl->capturesCXXThis()) {
2853 BlockLayoutChunk chunk;
2854 chunk.OffsetInBits =
2855 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2856 chunk.Capture = 0;
2857 chunks.push_back(chunk);
2858 }
2859
2860 // Variable captures.
2861 for (BlockDecl::capture_const_iterator
2862 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2863 i != e; ++i) {
2864 const BlockDecl::Capture &capture = *i;
2865 const VarDecl *variable = capture.getVariable();
2866 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2867
2868 // Ignore constant captures.
2869 if (captureInfo.isConstant())
2870 continue;
2871
2872 BlockLayoutChunk chunk;
2873 chunk.OffsetInBits =
2874 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2875 chunk.Capture = &capture;
2876 chunks.push_back(chunk);
2877 }
2878
2879 // Sort by offset.
2880 llvm::array_pod_sort(chunks.begin(), chunks.end());
2881
2882 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2883 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2884 uint64_t offsetInBits = i->OffsetInBits;
2885 const BlockDecl::Capture *capture = i->Capture;
2886
2887 // If we have a null capture, this must be the C++ 'this' capture.
2888 if (!capture) {
2889 const CXXMethodDecl *method =
2890 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2891 QualType type = method->getThisType(C);
2892
2893 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2894 offsetInBits, tunit, tunit));
2895 continue;
2896 }
2897
2898 const VarDecl *variable = capture->getVariable();
2899 StringRef name = variable->getName();
2900
2901 llvm::DIType fieldType;
2902 if (capture->isByRef()) {
2903 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2904
2905 // FIXME: this creates a second copy of this type!
2906 uint64_t xoffset;
2907 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2908 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2909 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2910 ptrInfo.first, ptrInfo.second,
2911 offsetInBits, 0, fieldType);
2912 } else {
2913 fieldType = createFieldType(name, variable->getType(), 0,
2914 loc, AS_public, offsetInBits, tunit, tunit);
2915 }
2916 fields.push_back(fieldType);
2917 }
2918
2919 SmallString<36> typeName;
2920 llvm::raw_svector_ostream(typeName)
2921 << "__block_literal_" << CGM.getUniqueBlockCount();
2922
2923 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2924
2925 llvm::DIType type =
2926 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2927 CGM.getContext().toBits(block.BlockSize),
2928 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002929 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002930 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2931
2932 // Get overall information about the block.
2933 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2934 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002935
2936 // Create the descriptor for the parameter.
2937 llvm::DIVariable debugVar =
2938 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002939 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002940 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002941 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002942 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2943
Adrian Prantlbea407c2013-03-14 21:52:59 +00002944 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002945 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002946 llvm::Instruction *DbgVal =
2947 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002948 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002949 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2950 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002951
Adrian Prantlbea407c2013-03-14 21:52:59 +00002952 // Insert an llvm.dbg.declare into the current block.
2953 llvm::Instruction *DbgDecl =
2954 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2955 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002956}
2957
Eric Christopher0395de32013-01-16 01:22:32 +00002958/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2959/// a static data member of a class, find its corresponding in-class
2960/// declaration.
2961llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2962 if (cast<VarDecl>(D)->isStaticDataMember()) {
2963 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2964 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2965 if (MI != StaticDataMemberCache.end())
2966 // Verify the info still exists.
2967 if (llvm::Value *V = MI->second)
2968 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2969 }
2970 return llvm::DIDerivedType();
2971}
2972
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002973/// EmitGlobalVariable - Emit information about a global variable.
2974void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2975 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00002976 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002977 // Create global variable debug descriptor.
2978 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2979 unsigned LineNo = getLineNumber(D->getLocation());
2980
2981 setLocation(D->getLocation());
2982
2983 QualType T = D->getType();
2984 if (T->isIncompleteArrayType()) {
2985
2986 // CodeGen turns int[] into int[1] so we'll do the same here.
2987 llvm::APInt ConstVal(32, 1);
2988 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2989
2990 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2991 ArrayType::Normal, 0);
2992 }
2993 StringRef DeclName = D->getName();
2994 StringRef LinkageName;
2995 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2996 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2997 LinkageName = Var->getName();
2998 if (LinkageName == DeclName)
2999 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003000 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003001 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie9faebd22013-05-20 04:58:53 +00003002 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003003 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00003004 Var->hasInternalLinkage(), Var,
3005 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003006 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003007}
3008
3009/// EmitGlobalVariable - Emit information about an objective-c interface.
3010void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3011 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003012 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003013 // Create global variable debug descriptor.
3014 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3015 unsigned LineNo = getLineNumber(ID->getLocation());
3016
3017 StringRef Name = ID->getName();
3018
3019 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3020 if (T->isIncompleteArrayType()) {
3021
3022 // CodeGen turns int[] into int[1] so we'll do the same here.
3023 llvm::APInt ConstVal(32, 1);
3024 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3025
3026 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3027 ArrayType::Normal, 0);
3028 }
3029
3030 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3031 getOrCreateType(T, Unit),
3032 Var->hasInternalLinkage(), Var);
3033}
3034
3035/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003036void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003037 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003038 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003039 // Create the descriptor for the variable.
3040 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3041 StringRef Name = VD->getName();
3042 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3043 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3044 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3045 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3046 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3047 }
3048 // Do not use DIGlobalVariable for enums.
3049 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3050 return;
David Blaikie9faebd22013-05-20 04:58:53 +00003051 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003052 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003053 Ty, true, Init,
3054 getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003055 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3056}
3057
3058llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3059 if (!LexicalBlockStack.empty())
3060 return llvm::DIScope(LexicalBlockStack.back());
3061 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003062}
3063
David Blaikie957dac52013-04-22 06:13:21 +00003064void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003065 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3066 return;
David Blaikie957dac52013-04-22 06:13:21 +00003067 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003068 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3069 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003070 getLineNumber(UD.getLocation()));
3071}
3072
David Blaikie9faebd22013-05-20 04:58:53 +00003073void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3074 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3075 return;
3076 assert(UD.shadow_size() &&
3077 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3078 // Emitting one decl is sufficient - debuggers can detect that this is an
3079 // overloaded name & provide lookup for all the overloads.
3080 const UsingShadowDecl &USD = **UD.shadow_begin();
3081 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3082 DBuilder.createImportedDeclaration(
3083 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3084 getLineNumber(USD.getLocation()));
3085}
3086
David Blaikiefc46ebc2013-05-20 22:50:41 +00003087llvm::DIImportedEntity
3088CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3089 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3090 return llvm::DIImportedEntity(0);
3091 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3092 if (VH)
3093 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3094 llvm::DIImportedEntity R(0);
3095 if (const NamespaceAliasDecl *Underlying =
3096 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3097 // This could cache & dedup here rather than relying on metadata deduping.
3098 R = DBuilder.createImportedModule(
3099 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3100 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3101 NA.getName());
3102 else
3103 R = DBuilder.createImportedModule(
3104 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3105 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3106 getLineNumber(NA.getLocation()), NA.getName());
3107 VH = R;
3108 return R;
3109}
3110
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003111/// getOrCreateNamesSpace - Return namespace descriptor for the given
3112/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003113llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003114CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003115 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003116 NameSpaceCache.find(NSDecl);
3117 if (I != NameSpaceCache.end())
3118 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003119
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003120 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3121 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003122 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003123 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3124 llvm::DINameSpace NS =
3125 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3126 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3127 return NS;
3128}
3129
3130void CGDebugInfo::finalize() {
3131 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3132 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3133 llvm::DIType Ty, RepTy;
3134 // Verify that the debug info still exists.
3135 if (llvm::Value *V = VI->second)
3136 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003137
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003138 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3139 TypeCache.find(VI->first);
3140 if (it != TypeCache.end()) {
3141 // Verify that the debug info still exists.
3142 if (llvm::Value *V = it->second)
3143 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3144 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003145
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003146 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003147 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003148 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003149
3150 // We keep our own list of retained types, because we need to look
3151 // up the final type in the type cache.
3152 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3153 RE = RetainedTypes.end(); RI != RE; ++RI)
3154 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3155
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003156 DBuilder.finalize();
3157}