blob: 563faa4f7804bd2a93cbdb1b065871efadf361ed [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.
Eric Christopher56b108a2013-06-07 22:54:39 +0000504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
505 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000506 QualifierCollector Qc;
507 const Type *T = Qc.strip(Ty);
508
509 // Ignore these qualifiers for now.
510 Qc.removeObjCGCAttr();
511 Qc.removeAddressSpace();
512 Qc.removeObjCLifetime();
513
514 // We will create one Derived type for one qualifier and recurse to handle any
515 // additional ones.
516 unsigned Tag;
517 if (Qc.hasConst()) {
518 Tag = llvm::dwarf::DW_TAG_const_type;
519 Qc.removeConst();
520 } else if (Qc.hasVolatile()) {
521 Tag = llvm::dwarf::DW_TAG_volatile_type;
522 Qc.removeVolatile();
523 } else if (Qc.hasRestrict()) {
524 Tag = llvm::dwarf::DW_TAG_restrict_type;
525 Qc.removeRestrict();
526 } else {
527 assert(Qc.empty() && "Unknown type qualifier for debug info");
528 return getOrCreateType(QualType(T, 0), Unit);
529 }
530
Eric Christopher56b108a2013-06-07 22:54:39 +0000531 llvm::DIType FromTy =
532 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000533
534 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
535 // CVR derived types.
536 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000537
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000538 return DbgTy;
539}
540
541llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
542 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000543
544 // The frontend treats 'id' as a typedef to an ObjCObjectType,
545 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
546 // debug info, we want to emit 'id' in both cases.
547 if (Ty->isObjCQualifiedIdType())
548 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
549
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000550 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000551 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000552 Ty->getPointeeType(), Unit);
553 return DbgTy;
554}
555
556llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
557 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000558 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000559 Ty->getPointeeType(), Unit);
560}
561
562// Creates a forward declaration for a RecordDecl in the given context.
563llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
564 llvm::DIDescriptor Ctx) {
565 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
566 unsigned Line = getLineNumber(RD->getLocation());
567 StringRef RDName = getClassName(RD);
568
569 unsigned Tag = 0;
570 if (RD->isStruct() || RD->isInterface())
571 Tag = llvm::dwarf::DW_TAG_structure_type;
572 else if (RD->isUnion())
573 Tag = llvm::dwarf::DW_TAG_union_type;
574 else {
575 assert(RD->isClass());
576 Tag = llvm::dwarf::DW_TAG_class_type;
577 }
578
579 // Create the type.
580 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
581}
582
583// Walk up the context chain and create forward decls for record decls,
584// and normal descriptors for namespaces.
585llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
586 if (!Context)
587 return TheCU;
588
589 // See if we already have the parent.
590 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
591 I = RegionMap.find(Context);
592 if (I != RegionMap.end()) {
593 llvm::Value *V = I->second;
594 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
595 }
Eric Christopher6537f082013-05-16 00:45:12 +0000596
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000597 // Check namespace.
598 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
599 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
600
601 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
602 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000603 llvm::DIType Ty =
604 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
605 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000606 return llvm::DIDescriptor(Ty);
607 }
608 }
609 return TheCU;
610}
611
David Blaikieb0f77b02013-05-24 21:33:22 +0000612/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000613/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000614llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
615 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000616 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000617 return getOrCreateType(PointeeTy, Unit);
David Blaikie5f6e2f42013-06-05 05:32:23 +0000618 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000619}
620
621llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000622 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000623 QualType PointeeTy,
624 llvm::DIFile Unit) {
625 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
626 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000627 return DBuilder.createReferenceType(
628 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000629
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000630 // Bit size, align and offset of the type.
631 // Size is always the size of a pointer. We can't use getTypeSize here
632 // because that does not return the correct value for references.
633 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000634 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000635 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
636
David Blaikieb0f77b02013-05-24 21:33:22 +0000637 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000638 Size, Align);
639}
640
Eric Christopherf0890c42013-05-16 00:52:20 +0000641llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
642 llvm::DIType &Cache) {
David Blaikie1e97c1e2013-05-21 17:58:54 +0000643 if (Cache.Verify())
Guy Benyeib13621d2012-12-18 14:38:23 +0000644 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000645 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
646 TheCU, getOrCreateMainFile(), 0);
647 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
648 Cache = DBuilder.createPointerType(Cache, Size);
649 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000650}
651
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000652llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
653 llvm::DIFile Unit) {
654 if (BlockLiteralGenericSet)
655 return BlockLiteralGeneric;
656
657 SmallVector<llvm::Value *, 8> EltTys;
658 llvm::DIType FieldTy;
659 QualType FType;
660 uint64_t FieldSize, FieldOffset;
661 unsigned FieldAlign;
662 llvm::DIArray Elements;
663 llvm::DIType EltTy, DescTy;
664
665 FieldOffset = 0;
666 FType = CGM.getContext().UnsignedLongTy;
667 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
668 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
669
670 Elements = DBuilder.getOrCreateArray(EltTys);
671 EltTys.clear();
672
673 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
674 unsigned LineNo = getLineNumber(CurLoc);
675
676 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
677 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000678 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000679
680 // Bit size, align and offset of the type.
681 uint64_t Size = CGM.getContext().getTypeSize(Ty);
682
683 DescTy = DBuilder.createPointerType(EltTy, Size);
684
685 FieldOffset = 0;
686 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
687 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
688 FType = CGM.getContext().IntTy;
689 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
690 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
691 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
692 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
693
694 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
695 FieldTy = DescTy;
696 FieldSize = CGM.getContext().getTypeSize(Ty);
697 FieldAlign = CGM.getContext().getTypeAlign(Ty);
698 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
699 LineNo, FieldSize, FieldAlign,
700 FieldOffset, 0, FieldTy);
701 EltTys.push_back(FieldTy);
702
703 FieldOffset += FieldSize;
704 Elements = DBuilder.getOrCreateArray(EltTys);
705
706 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
707 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000708 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000709
710 BlockLiteralGenericSet = true;
711 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
712 return BlockLiteralGeneric;
713}
714
David Blaikie5f6e2f42013-06-05 05:32:23 +0000715llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
716 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000717 // Typedefs are derived from some other type. If we have a typedef of a
718 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000719 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000720 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000721 if (!Src.Verify())
722 return llvm::DIType();
723 // We don't set size information, but do specify where the typedef was
724 // declared.
725 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
726 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000727
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000728 llvm::DIDescriptor TypedefContext =
729 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000730
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000731 return
732 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
733}
734
735llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
736 llvm::DIFile Unit) {
737 SmallVector<llvm::Value *, 16> EltTys;
738
739 // Add the result type at least.
740 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
741
742 // Set up remainder of arguments if there is a prototype.
743 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
744 if (isa<FunctionNoProtoType>(Ty))
745 EltTys.push_back(DBuilder.createUnspecifiedParameter());
746 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
747 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
748 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
749 }
750
751 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
752 return DBuilder.createSubroutineType(Unit, EltTypeArray);
753}
754
755
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000756llvm::DIType CGDebugInfo::createFieldType(StringRef name,
757 QualType type,
758 uint64_t sizeInBitsOverride,
759 SourceLocation loc,
760 AccessSpecifier AS,
761 uint64_t offsetInBits,
762 llvm::DIFile tunit,
763 llvm::DIDescriptor scope) {
764 llvm::DIType debugType = getOrCreateType(type, tunit);
765
766 // Get the location for the field.
767 llvm::DIFile file = getOrCreateFile(loc);
768 unsigned line = getLineNumber(loc);
769
770 uint64_t sizeInBits = 0;
771 unsigned alignInBits = 0;
772 if (!type->isIncompleteArrayType()) {
773 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
774
775 if (sizeInBitsOverride)
776 sizeInBits = sizeInBitsOverride;
777 }
778
779 unsigned flags = 0;
780 if (AS == clang::AS_private)
781 flags |= llvm::DIDescriptor::FlagPrivate;
782 else if (AS == clang::AS_protected)
783 flags |= llvm::DIDescriptor::FlagProtected;
784
785 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
786 alignInBits, offsetInBits, flags, debugType);
787}
788
Eric Christopher0395de32013-01-16 01:22:32 +0000789/// CollectRecordLambdaFields - Helper for CollectRecordFields.
790void CGDebugInfo::
791CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
792 SmallVectorImpl<llvm::Value *> &elements,
793 llvm::DIType RecordTy) {
794 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
795 // has the name and the location of the variable so we should iterate over
796 // both concurrently.
797 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
798 RecordDecl::field_iterator Field = CXXDecl->field_begin();
799 unsigned fieldno = 0;
800 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
801 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
802 const LambdaExpr::Capture C = *I;
803 if (C.capturesVariable()) {
804 VarDecl *V = C.getCapturedVar();
805 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
806 StringRef VName = V->getName();
807 uint64_t SizeInBitsOverride = 0;
808 if (Field->isBitField()) {
809 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
810 assert(SizeInBitsOverride && "found named 0-width bitfield");
811 }
812 llvm::DIType fieldType
813 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
814 C.getLocation(), Field->getAccess(),
815 layout.getFieldOffset(fieldno), VUnit, RecordTy);
816 elements.push_back(fieldType);
817 } else {
818 // TODO: Need to handle 'this' in some way by probably renaming the
819 // this of the lambda class and having a field member of 'this' or
820 // by using AT_object_pointer for the function and having that be
821 // used as 'this' for semantic references.
822 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
823 FieldDecl *f = *Field;
824 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
825 QualType type = f->getType();
826 llvm::DIType fieldType
827 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
828 layout.getFieldOffset(fieldno), VUnit, RecordTy);
829
830 elements.push_back(fieldType);
831 }
832 }
833}
834
835/// CollectRecordStaticField - Helper for CollectRecordFields.
836void CGDebugInfo::
837CollectRecordStaticField(const VarDecl *Var,
838 SmallVectorImpl<llvm::Value *> &elements,
839 llvm::DIType RecordTy) {
840 // Create the descriptor for the static variable, with or without
841 // constant initializers.
842 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
843 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
844
845 // Do not describe enums as static members.
846 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
847 return;
848
849 unsigned LineNumber = getLineNumber(Var->getLocation());
850 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000851 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000852 if (Var->getInit()) {
853 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000854 if (Value) {
855 if (Value->isInt())
856 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
857 if (Value->isFloat())
858 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
859 }
Eric Christopher0395de32013-01-16 01:22:32 +0000860 }
861
862 unsigned Flags = 0;
863 AccessSpecifier Access = Var->getAccess();
864 if (Access == clang::AS_private)
865 Flags |= llvm::DIDescriptor::FlagPrivate;
866 else if (Access == clang::AS_protected)
867 Flags |= llvm::DIDescriptor::FlagProtected;
868
869 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000870 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000871 elements.push_back(GV);
872 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
873}
874
875/// CollectRecordNormalField - Helper for CollectRecordFields.
876void CGDebugInfo::
877CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
878 llvm::DIFile tunit,
879 SmallVectorImpl<llvm::Value *> &elements,
880 llvm::DIType RecordTy) {
881 StringRef name = field->getName();
882 QualType type = field->getType();
883
884 // Ignore unnamed fields unless they're anonymous structs/unions.
885 if (name.empty() && !type->isRecordType())
886 return;
887
888 uint64_t SizeInBitsOverride = 0;
889 if (field->isBitField()) {
890 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
891 assert(SizeInBitsOverride && "found named 0-width bitfield");
892 }
893
894 llvm::DIType fieldType
895 = createFieldType(name, type, SizeInBitsOverride,
896 field->getLocation(), field->getAccess(),
897 OffsetInBits, tunit, RecordTy);
898
899 elements.push_back(fieldType);
900}
901
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000902/// CollectRecordFields - A helper function to collect debug info for
903/// record fields. This is used while creating debug info entry for a Record.
904void CGDebugInfo::
905CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
906 SmallVectorImpl<llvm::Value *> &elements,
907 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000908 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
909
Eric Christopher0395de32013-01-16 01:22:32 +0000910 if (CXXDecl && CXXDecl->isLambda())
911 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
912 else {
913 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000914
Eric Christopher0395de32013-01-16 01:22:32 +0000915 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000916 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000917
918 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000919 bool IsMsStruct = record->isMsStruct(CGM.getContext());
920 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000921
Eric Christopher0395de32013-01-16 01:22:32 +0000922 // Static and non-static members should appear in the same order as
923 // the corresponding declarations in the source program.
924 for (RecordDecl::decl_iterator I = record->decls_begin(),
925 E = record->decls_end(); I != E; ++I)
926 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
927 CollectRecordStaticField(V, elements, RecordTy);
928 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
929 if (IsMsStruct) {
930 // Zero-length bitfields following non-bitfield members are
931 // completely ignored; we don't even count them.
932 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
933 continue;
934 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 }
Eric Christopher0395de32013-01-16 01:22:32 +0000936 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
937 tunit, elements, RecordTy);
938
939 // Bump field number for next field.
940 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000941 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000942 }
943}
944
945/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
946/// function type is not updated to include implicit "this" pointer. Use this
947/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000948llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
950 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000951 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000952 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000953 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000954 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
955 Func, Unit);
956}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000957
David Blaikie9a845292013-05-22 23:22:42 +0000958llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000959 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000960 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000961 llvm::DIArray Args = llvm::DICompositeType(
962 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000963 assert (Args.getNumElements() && "Invalid number of arguments!");
964
965 SmallVector<llvm::Value *, 16> Elts;
966
967 // First element is always return type. For 'void' functions it is NULL.
968 Elts.push_back(Args.getElement(0));
969
David Blaikie67f8b5e2013-01-07 22:24:59 +0000970 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000971 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000972 if (isa<ClassTemplateSpecializationDecl>(RD)) {
973 // Create pointer type directly in this case.
974 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
975 QualType PointeeTy = ThisPtrTy->getPointeeType();
976 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000977 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000978 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
979 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000980 llvm::DIType ThisPtrType =
981 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000982 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
983 // TODO: This and the artificial type below are misleading, the
984 // types aren't artificial the argument is, but the current
985 // metadata doesn't represent that.
986 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
987 Elts.push_back(ThisPtrType);
988 } else {
989 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
990 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
991 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
992 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000993 }
994
995 // Copy rest of the arguments.
996 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
997 Elts.push_back(Args.getElement(i));
998
999 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1000
1001 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1002}
1003
Eric Christopher6537f082013-05-16 00:45:12 +00001004/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001005/// inside a function.
1006static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1007 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1008 return isFunctionLocalClass(NRD);
1009 if (isa<FunctionDecl>(RD->getDeclContext()))
1010 return true;
1011 return false;
1012}
1013
1014/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1015/// a single member function GlobalDecl.
1016llvm::DISubprogram
1017CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1018 llvm::DIFile Unit,
1019 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001020 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001021 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001022
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001023 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001024 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001025
1026 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1027 // make sense to give a single ctor/dtor a linkage name.
1028 StringRef MethodLinkageName;
1029 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1030 MethodLinkageName = CGM.getMangledName(Method);
1031
1032 // Get the location for the method.
1033 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1034 unsigned MethodLine = getLineNumber(Method->getLocation());
1035
1036 // Collect virtual method info.
1037 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001038 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001039 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001040
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041 if (Method->isVirtual()) {
1042 if (Method->isPure())
1043 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1044 else
1045 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001047 // It doesn't make sense to give a virtual destructor a vtable index,
1048 // since a single destructor has two entries in the vtable.
1049 if (!isa<CXXDestructorDecl>(Method))
1050 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1051 ContainingType = RecordTy;
1052 }
1053
1054 unsigned Flags = 0;
1055 if (Method->isImplicit())
1056 Flags |= llvm::DIDescriptor::FlagArtificial;
1057 AccessSpecifier Access = Method->getAccess();
1058 if (Access == clang::AS_private)
1059 Flags |= llvm::DIDescriptor::FlagPrivate;
1060 else if (Access == clang::AS_protected)
1061 Flags |= llvm::DIDescriptor::FlagProtected;
1062 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1063 if (CXXC->isExplicit())
1064 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001065 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001066 dyn_cast<CXXConversionDecl>(Method)) {
1067 if (CXXC->isExplicit())
1068 Flags |= llvm::DIDescriptor::FlagExplicit;
1069 }
1070 if (Method->hasPrototype())
1071 Flags |= llvm::DIDescriptor::FlagPrototyped;
1072
1073 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1074 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001075 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001076 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001077 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001078 /* isDefinition=*/ false,
1079 Virtuality, VIndex, ContainingType,
1080 Flags, CGM.getLangOpts().Optimize, NULL,
1081 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001082
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001083 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1084
1085 return SP;
1086}
1087
1088/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001089/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001090/// a Record.
1091void CGDebugInfo::
1092CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1093 SmallVectorImpl<llvm::Value *> &EltTys,
1094 llvm::DIType RecordTy) {
1095
1096 // Since we want more than just the individual member decls if we
1097 // have templated functions iterate over every declaration to gather
1098 // the functions.
1099 for(DeclContext::decl_iterator I = RD->decls_begin(),
1100 E = RD->decls_end(); I != E; ++I) {
1101 Decl *D = *I;
1102 if (D->isImplicit() && !D->isUsed())
1103 continue;
1104
1105 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1106 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1107 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1108 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1109 SE = FTD->spec_end(); SI != SE; ++SI)
1110 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1111 RecordTy));
1112 }
Eric Christopher6537f082013-05-16 00:45:12 +00001113}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001114
1115/// CollectCXXFriends - A helper function to collect debug info for
1116/// C++ base classes. This is used while creating debug info entry for
1117/// a Record.
1118void CGDebugInfo::
1119CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1120 SmallVectorImpl<llvm::Value *> &EltTys,
1121 llvm::DIType RecordTy) {
1122 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1123 BE = RD->friend_end(); BI != BE; ++BI) {
1124 if ((*BI)->isUnsupportedFriend())
1125 continue;
1126 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001127 EltTys.push_back(DBuilder.createFriend(RecordTy,
1128 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001129 Unit)));
1130 }
1131}
1132
1133/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001134/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001135/// a Record.
1136void CGDebugInfo::
1137CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1138 SmallVectorImpl<llvm::Value *> &EltTys,
1139 llvm::DIType RecordTy) {
1140
1141 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1142 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1143 BE = RD->bases_end(); BI != BE; ++BI) {
1144 unsigned BFlags = 0;
1145 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001146
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001147 const CXXRecordDecl *Base =
1148 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001149
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001150 if (BI->isVirtual()) {
1151 // virtual base offset offset is -ve. The code generator emits dwarf
1152 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001153 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001154 0 - CGM.getVTableContext()
1155 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1156 BFlags = llvm::DIDescriptor::FlagVirtual;
1157 } else
1158 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1159 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1160 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001161
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001162 AccessSpecifier Access = BI->getAccessSpecifier();
1163 if (Access == clang::AS_private)
1164 BFlags |= llvm::DIDescriptor::FlagPrivate;
1165 else if (Access == clang::AS_protected)
1166 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001167
1168 llvm::DIType DTy =
1169 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170 getOrCreateType(BI->getType(), Unit),
1171 BaseOffset, BFlags);
1172 EltTys.push_back(DTy);
1173 }
1174}
1175
1176/// CollectTemplateParams - A helper function to collect template parameters.
1177llvm::DIArray CGDebugInfo::
1178CollectTemplateParams(const TemplateParameterList *TPList,
1179 const TemplateArgumentList &TAList,
1180 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001181 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001182 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1183 const TemplateArgument &TA = TAList[i];
1184 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001185 switch (TA.getKind()) {
1186 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1188 llvm::DITemplateTypeParameter TTP =
1189 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1190 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001191 } break;
1192 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001193 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1194 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001195 DBuilder.createTemplateValueParameter(
1196 TheCU, ND->getName(), TTy,
1197 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1198 TemplateParams.push_back(TVP);
1199 } break;
1200 case TemplateArgument::Declaration: {
1201 const ValueDecl *D = TA.getAsDecl();
1202 bool InstanceMember = D->isCXXInstanceMember();
1203 QualType T = InstanceMember
1204 ? CGM.getContext().getMemberPointerType(
1205 D->getType(), cast<RecordDecl>(D->getDeclContext())
1206 ->getTypeForDecl())
1207 : CGM.getContext().getPointerType(D->getType());
1208 llvm::DIType TTy = getOrCreateType(T, Unit);
1209 llvm::Value *V = 0;
1210 // Variable pointer template parameters have a value that is the address
1211 // of the variable.
1212 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1213 V = CGM.GetAddrOfGlobalVar(VD);
1214 // Member function pointers have special support for building them, though
1215 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001216 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001217 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1218 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001219 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1220 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001221 // Member data pointers have special handling too to compute the fixed
1222 // offset within the object.
1223 if (isa<FieldDecl>(D)) {
1224 // These five lines (& possibly the above member function pointer
1225 // handling) might be able to be refactored to use similar code in
1226 // CodeGenModule::getMemberPointerConstant
1227 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1228 CharUnits chars =
1229 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1230 V = CGM.getCXXABI().EmitMemberDataPointer(
1231 cast<MemberPointerType>(T.getTypePtr()), chars);
1232 }
1233 llvm::DITemplateValueParameter TVP =
1234 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1235 TemplateParams.push_back(TVP);
1236 } break;
1237 case TemplateArgument::NullPtr: {
1238 QualType T = TA.getNullPtrType();
1239 llvm::DIType TTy = getOrCreateType(T, Unit);
1240 llvm::Value *V = 0;
1241 // Special case member data pointer null values since they're actually -1
1242 // instead of zero.
1243 if (const MemberPointerType *MPT =
1244 dyn_cast<MemberPointerType>(T.getTypePtr()))
1245 // But treat member function pointers as simple zero integers because
1246 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1247 // CodeGen grows handling for values of non-null member function
1248 // pointers then perhaps we could remove this special case and rely on
1249 // EmitNullMemberPointer for member function pointers.
1250 if (MPT->isMemberDataPointer())
1251 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1252 if (!V)
1253 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1254 llvm::DITemplateValueParameter TVP =
1255 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1256 TemplateParams.push_back(TVP);
1257 } break;
1258 case TemplateArgument::Template:
1259 // We could support this with the GCC extension
1260 // DW_TAG_GNU_template_template_param
1261 break;
David Blaikie776a3642013-05-10 22:53:25 +00001262 case TemplateArgument::Pack:
1263 // And this with DW_TAG_GNU_template_parameter_pack
1264 break;
David Blaikiee8065122013-05-10 23:36:06 +00001265 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001266 case TemplateArgument::Expression:
1267 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001268 case TemplateArgument::Null:
1269 llvm_unreachable(
1270 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001271 }
1272 }
1273 return DBuilder.getOrCreateArray(TemplateParams);
1274}
1275
1276/// CollectFunctionTemplateParams - A helper function to collect debug
1277/// info for function template parameters.
1278llvm::DIArray CGDebugInfo::
1279CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1280 if (FD->getTemplatedKind() ==
1281 FunctionDecl::TK_FunctionTemplateSpecialization) {
1282 const TemplateParameterList *TList =
1283 FD->getTemplateSpecializationInfo()->getTemplate()
1284 ->getTemplateParameters();
Eric Christopher6537f082013-05-16 00:45:12 +00001285 return
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001286 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1287 }
1288 return llvm::DIArray();
1289}
1290
1291/// CollectCXXTemplateParams - A helper function to collect debug info for
1292/// template parameters.
1293llvm::DIArray CGDebugInfo::
1294CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1295 llvm::DIFile Unit) {
1296 llvm::PointerUnion<ClassTemplateDecl *,
1297 ClassTemplatePartialSpecializationDecl *>
1298 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001299
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001300 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1301 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1302 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1303 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1304 return CollectTemplateParams(TPList, TAList, Unit);
1305}
1306
1307/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1308llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1309 if (VTablePtrType.isValid())
1310 return VTablePtrType;
1311
1312 ASTContext &Context = CGM.getContext();
1313
1314 /* Function type */
1315 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1316 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1317 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1318 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1319 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1320 "__vtbl_ptr_type");
1321 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1322 return VTablePtrType;
1323}
1324
1325/// getVTableName - Get vtable name for the given Class.
1326StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1327 // Construct gdb compatible name name.
1328 std::string Name = "_vptr$" + RD->getNameAsString();
1329
1330 // Copy this name on the side and use its reference.
1331 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1332 memcpy(StrPtr, Name.data(), Name.length());
1333 return StringRef(StrPtr, Name.length());
1334}
1335
1336
1337/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1338/// debug info entry in EltTys vector.
1339void CGDebugInfo::
1340CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1341 SmallVectorImpl<llvm::Value *> &EltTys) {
1342 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1343
1344 // If there is a primary base then it will hold vtable info.
1345 if (RL.getPrimaryBase())
1346 return;
1347
1348 // If this class is not dynamic then there is not any vtable info to collect.
1349 if (!RD->isDynamicClass())
1350 return;
1351
1352 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1353 llvm::DIType VPTR
1354 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001355 0, Size, 0, 0,
1356 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001357 getOrCreateVTablePtrType(Unit));
1358 EltTys.push_back(VPTR);
1359}
1360
Eric Christopher6537f082013-05-16 00:45:12 +00001361/// getOrCreateRecordType - Emit record type's standalone debug info.
1362llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001363 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001364 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001365 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1366 return T;
1367}
1368
1369/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1370/// debug info.
1371llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001372 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001373 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001374 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001375 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001376 return T;
1377}
1378
1379/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001380llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001381 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001382 // Limited debug info should only remove struct definitions that can
1383 // safely be replaced by a forward declaration in the source code.
Adrian Prantl14c1a132013-06-18 23:01:56 +00001384 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001385 // FIXME: This implementation is problematic; there are some test
1386 // cases where we violate the above principle, such as
1387 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001388 llvm::DIDescriptor FDContext =
1389 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1390 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1391 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1392 return RetTy;
1393 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001394
1395 // Get overall information about the record type for the debug info.
1396 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1397
1398 // Records and classes and unions can all be recursive. To handle them, we
1399 // first generate a debug descriptor for the struct as a forward declaration.
1400 // Then (if it is a definition) we go through and get debug info for all of
1401 // its members. Finally, we create a descriptor for the complete type (which
1402 // may refer to the forward decl if the struct is recursive) and replace all
1403 // uses of the forward declaration with the final definition.
1404
Eric Christopherf068c922013-04-02 22:59:11 +00001405 llvm::DICompositeType FwdDecl(
1406 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1407 assert(FwdDecl.Verify() &&
David Blaikie9a845292013-05-22 23:22:42 +00001408 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001409
1410 if (FwdDecl.isForwardDecl())
1411 return FwdDecl;
1412
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001413 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001414 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001415 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1416
Adrian Prantl4919de62013-03-06 22:03:30 +00001417 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001418 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1419
1420 // Convert all the elements.
1421 SmallVector<llvm::Value *, 16> EltTys;
1422
1423 // Note: The split of CXXDecl information here is intentional, the
1424 // gdb tests will depend on a certain ordering at printout. The debug
1425 // information offsets are still correct if we merge them all together
1426 // though.
1427 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1428 if (CXXDecl) {
1429 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1430 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1431 }
1432
Eric Christopher0395de32013-01-16 01:22:32 +00001433 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001434 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1435 llvm::DIArray TParamsArray;
1436 if (CXXDecl) {
1437 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1438 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1439 if (const ClassTemplateSpecializationDecl *TSpecial
1440 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1441 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1442 }
1443
1444 LexicalBlockStack.pop_back();
1445 RegionMap.erase(Ty->getDecl());
1446
1447 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001448 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001449
Eric Christopherf068c922013-04-02 22:59:11 +00001450 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1451 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001452}
1453
1454/// CreateType - get objective-c object type.
1455llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1456 llvm::DIFile Unit) {
1457 // Ignore protocols.
1458 return getOrCreateType(Ty->getBaseType(), Unit);
1459}
1460
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001461
1462/// \return true if Getter has the default name for the property PD.
1463static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1464 const ObjCMethodDecl *Getter) {
1465 assert(PD);
1466 if (!Getter)
1467 return true;
1468
1469 assert(Getter->getDeclName().isObjCZeroArgSelector());
1470 return PD->getName() ==
1471 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1472}
1473
1474/// \return true if Setter has the default name for the property PD.
1475static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1476 const ObjCMethodDecl *Setter) {
1477 assert(PD);
1478 if (!Setter)
1479 return true;
1480
1481 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001482 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001483 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1484}
1485
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001486/// CreateType - get objective-c interface type.
1487llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1488 llvm::DIFile Unit) {
1489 ObjCInterfaceDecl *ID = Ty->getDecl();
1490 if (!ID)
1491 return llvm::DIType();
1492
1493 // Get overall information about the record type for the debug info.
1494 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1495 unsigned Line = getLineNumber(ID->getLocation());
1496 unsigned RuntimeLang = TheCU.getLanguage();
1497
1498 // If this is just a forward declaration return a special forward-declaration
1499 // debug type since we won't be able to lay out the entire type.
1500 ObjCInterfaceDecl *Def = ID->getDefinition();
1501 if (!Def) {
1502 llvm::DIType FwdDecl =
1503 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001504 ID->getName(), TheCU, DefUnit, Line,
1505 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001506 return FwdDecl;
1507 }
1508
1509 ID = Def;
1510
1511 // Bit size, align and offset of the type.
1512 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1513 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1514
1515 unsigned Flags = 0;
1516 if (ID->getImplementation())
1517 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1518
Eric Christopherf068c922013-04-02 22:59:11 +00001519 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001520 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1521 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001522 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001523
1524 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1525 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001526 QualType QualTy = QualType(Ty, 0);
1527 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001529
Eric Christopherf068c922013-04-02 22:59:11 +00001530 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001531 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1532
1533 // Convert all the elements.
1534 SmallVector<llvm::Value *, 16> EltTys;
1535
1536 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1537 if (SClass) {
1538 llvm::DIType SClassTy =
1539 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1540 if (!SClassTy.isValid())
1541 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001542
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001543 llvm::DIType InhTag =
1544 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1545 EltTys.push_back(InhTag);
1546 }
1547
1548 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1549 E = ID->prop_end(); I != E; ++I) {
1550 const ObjCPropertyDecl *PD = *I;
1551 SourceLocation Loc = PD->getLocation();
1552 llvm::DIFile PUnit = getOrCreateFile(Loc);
1553 unsigned PLine = getLineNumber(Loc);
1554 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1555 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1556 llvm::MDNode *PropertyNode =
1557 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001558 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001559 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001560 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001561 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001562 getSelectorName(PD->getSetterName()),
1563 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001564 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001565 EltTys.push_back(PropertyNode);
1566 }
1567
1568 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1569 unsigned FieldNo = 0;
1570 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1571 Field = Field->getNextIvar(), ++FieldNo) {
1572 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1573 if (!FieldTy.isValid())
1574 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001575
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001576 StringRef FieldName = Field->getName();
1577
1578 // Ignore unnamed fields.
1579 if (FieldName.empty())
1580 continue;
1581
1582 // Get the location for the field.
1583 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1584 unsigned FieldLine = getLineNumber(Field->getLocation());
1585 QualType FType = Field->getType();
1586 uint64_t FieldSize = 0;
1587 unsigned FieldAlign = 0;
1588
1589 if (!FType->isIncompleteArrayType()) {
1590
1591 // Bit size, align and offset of the type.
1592 FieldSize = Field->isBitField()
1593 ? Field->getBitWidthValue(CGM.getContext())
1594 : CGM.getContext().getTypeSize(FType);
1595 FieldAlign = CGM.getContext().getTypeAlign(FType);
1596 }
1597
1598 uint64_t FieldOffset;
1599 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1600 // We don't know the runtime offset of an ivar if we're using the
1601 // non-fragile ABI. For bitfields, use the bit offset into the first
1602 // byte of storage of the bitfield. For other fields, use zero.
1603 if (Field->isBitField()) {
1604 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1605 CGM, ID, Field);
1606 FieldOffset %= CGM.getContext().getCharWidth();
1607 } else {
1608 FieldOffset = 0;
1609 }
1610 } else {
1611 FieldOffset = RL.getFieldOffset(FieldNo);
1612 }
1613
1614 unsigned Flags = 0;
1615 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1616 Flags = llvm::DIDescriptor::FlagProtected;
1617 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1618 Flags = llvm::DIDescriptor::FlagPrivate;
1619
1620 llvm::MDNode *PropertyNode = NULL;
1621 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001622 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001623 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1624 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001625 SourceLocation Loc = PD->getLocation();
1626 llvm::DIFile PUnit = getOrCreateFile(Loc);
1627 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001628 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1629 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1630 PropertyNode =
1631 DBuilder.createObjCProperty(PD->getName(),
1632 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001633 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001634 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001635 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001636 getSelectorName(PD->getSetterName()),
1637 PD->getPropertyAttributes(),
1638 getOrCreateType(PD->getType(), PUnit));
1639 }
1640 }
1641 }
1642 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1643 FieldLine, FieldSize, FieldAlign,
1644 FieldOffset, Flags, FieldTy,
1645 PropertyNode);
1646 EltTys.push_back(FieldTy);
1647 }
1648
1649 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001650 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001651
1652 // If the implementation is not yet set, we do not want to mark it
1653 // as complete. An implementation may declare additional
1654 // private ivars that we would miss otherwise.
1655 if (ID->getImplementation() == 0)
1656 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001657
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001658 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001659 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001660}
1661
1662llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1663 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1664 int64_t Count = Ty->getNumElements();
1665 if (Count == 0)
1666 // If number of elements are not known then this is an unbounded array.
1667 // Use Count == -1 to express such arrays.
1668 Count = -1;
1669
1670 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1671 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1672
1673 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1674 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1675
1676 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1677}
1678
1679llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1680 llvm::DIFile Unit) {
1681 uint64_t Size;
1682 uint64_t Align;
1683
1684 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1685 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1686 Size = 0;
1687 Align =
1688 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1689 } else if (Ty->isIncompleteArrayType()) {
1690 Size = 0;
1691 if (Ty->getElementType()->isIncompleteType())
1692 Align = 0;
1693 else
1694 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001695 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001696 Size = 0;
1697 Align = 0;
1698 } else {
1699 // Size and align of the whole array, not the element type.
1700 Size = CGM.getContext().getTypeSize(Ty);
1701 Align = CGM.getContext().getTypeAlign(Ty);
1702 }
1703
1704 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1705 // interior arrays, do we care? Why aren't nested arrays represented the
1706 // obvious/recursive way?
1707 SmallVector<llvm::Value *, 8> Subscripts;
1708 QualType EltTy(Ty, 0);
1709 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1710 // If the number of elements is known, then count is that number. Otherwise,
1711 // it's -1. This allows us to represent a subrange with an array of 0
1712 // elements, like this:
1713 //
1714 // struct foo {
1715 // int x[0];
1716 // };
1717 int64_t Count = -1; // Count == -1 is an unbounded array.
1718 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1719 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001720
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001721 // FIXME: Verify this is right for VLAs.
1722 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1723 EltTy = Ty->getElementType();
1724 }
1725
1726 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1727
Eric Christopher6537f082013-05-16 00:45:12 +00001728 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001729 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1730 SubscriptArray);
1731 return DbgTy;
1732}
1733
Eric Christopher6537f082013-05-16 00:45:12 +00001734llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001735 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001736 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001737 Ty, Ty->getPointeeType(), Unit);
1738}
1739
Eric Christopher6537f082013-05-16 00:45:12 +00001740llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001741 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001742 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001743 Ty, Ty->getPointeeType(), Unit);
1744}
1745
Eric Christopher6537f082013-05-16 00:45:12 +00001746llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001747 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001748 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1749 if (!Ty->getPointeeType()->isFunctionType())
1750 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001751 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001752 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1753 CGM.getContext().getPointerType(
1754 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1755 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1756 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001757}
1758
Eric Christopher6537f082013-05-16 00:45:12 +00001759llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001760 llvm::DIFile U) {
1761 // Ignore the atomic wrapping
1762 // FIXME: What is the correct representation?
1763 return getOrCreateType(Ty->getValueType(), U);
1764}
1765
1766/// CreateEnumType - get enumeration type.
1767llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1768 uint64_t Size = 0;
1769 uint64_t Align = 0;
1770 if (!ED->getTypeForDecl()->isIncompleteType()) {
1771 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1772 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1773 }
1774
1775 // If this is just a forward declaration, construct an appropriately
1776 // marked node and just return it.
1777 if (!ED->getDefinition()) {
1778 llvm::DIDescriptor EDContext;
1779 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1780 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1781 unsigned Line = getLineNumber(ED->getLocation());
1782 StringRef EDName = ED->getName();
1783 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1784 EDName, EDContext, DefUnit, Line, 0,
1785 Size, Align);
1786 }
1787
1788 // Create DIEnumerator elements for each enumerator.
1789 SmallVector<llvm::Value *, 16> Enumerators;
1790 ED = ED->getDefinition();
1791 for (EnumDecl::enumerator_iterator
1792 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1793 Enum != EnumEnd; ++Enum) {
1794 Enumerators.push_back(
1795 DBuilder.createEnumerator(Enum->getName(),
1796 Enum->getInitVal().getZExtValue()));
1797 }
1798
1799 // Return a CompositeType for the enum itself.
1800 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1801
1802 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1803 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001804 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001805 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001806 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001808 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001809 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1810 Size, Align, EltArray,
1811 ClassTy);
1812 return DbgTy;
1813}
1814
David Blaikie4b12be62013-01-21 04:37:12 +00001815static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1816 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001818 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001819 QualType LastT = T;
1820 switch (T->getTypeClass()) {
1821 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001822 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001823 case Type::TemplateSpecialization:
1824 T = cast<TemplateSpecializationType>(T)->desugar();
1825 break;
1826 case Type::TypeOfExpr:
1827 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1828 break;
1829 case Type::TypeOf:
1830 T = cast<TypeOfType>(T)->getUnderlyingType();
1831 break;
1832 case Type::Decltype:
1833 T = cast<DecltypeType>(T)->getUnderlyingType();
1834 break;
1835 case Type::UnaryTransform:
1836 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1837 break;
1838 case Type::Attributed:
1839 T = cast<AttributedType>(T)->getEquivalentType();
1840 break;
1841 case Type::Elaborated:
1842 T = cast<ElaboratedType>(T)->getNamedType();
1843 break;
1844 case Type::Paren:
1845 T = cast<ParenType>(T)->getInnerType();
1846 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001847 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001848 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001849 break;
1850 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001851 QualType DT = cast<AutoType>(T)->getDeducedType();
1852 if (DT.isNull())
1853 return T;
1854 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001855 break;
1856 }
Eric Christopher6537f082013-05-16 00:45:12 +00001857
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001859 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001860 } while (true);
1861}
1862
Eric Christopherf0890c42013-05-16 00:52:20 +00001863/// getType - Get the type from the cache or return null type if it doesn't
1864/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001865llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1866
1867 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001868 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001869
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001870 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001871 if (Ty->getTypeClass() == Type::ObjCInterface) {
1872 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1873 if (V)
1874 return llvm::DIType(cast<llvm::MDNode>(V));
1875 else return llvm::DIType();
1876 }
1877
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001878 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1879 TypeCache.find(Ty.getAsOpaquePtr());
1880 if (it != TypeCache.end()) {
1881 // Verify that the debug info still exists.
1882 if (llvm::Value *V = it->second)
1883 return llvm::DIType(cast<llvm::MDNode>(V));
1884 }
1885
1886 return llvm::DIType();
1887}
1888
1889/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1890/// doesn't exist.
1891llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1892
1893 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001894 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001895
1896 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001897 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001898 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1899 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001900 if (it != CompletedTypeCache.end())
1901 V = it->second;
1902 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001903 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001904 }
1905
Adrian Prantl4919de62013-03-06 22:03:30 +00001906 // Verify that any cached debug info still exists.
1907 if (V != 0)
1908 return llvm::DIType(cast<llvm::MDNode>(V));
1909
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001910 return llvm::DIType();
1911}
1912
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001913/// getCachedInterfaceTypeOrNull - Get the type from the interface
1914/// cache, unless it needs to regenerated. Otherwise return null.
1915llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1916 // Is there a cached interface that hasn't changed?
1917 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1918 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1919
1920 if (it1 != ObjCInterfaceCache.end())
1921 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1922 if (Checksum(Decl) == it1->second.second)
1923 // Return cached forward declaration.
1924 return it1->second.first;
1925
1926 return 0;
1927}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001928
1929/// getOrCreateType - Get the type from the cache or create a new
1930/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001931llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1932 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001933 if (Ty.isNull())
1934 return llvm::DIType();
1935
1936 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001937 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001938
1939 llvm::DIType T = getCompletedTypeOrNull(Ty);
1940
1941 if (T.Verify())
1942 return T;
1943
1944 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001945 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001946 void* TyPtr = Ty.getAsOpaquePtr();
1947
1948 // And update the type cache.
1949 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001950
1951 llvm::DIType TC = getTypeOrNull(Ty);
1952 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001953 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1954 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1955 // Interface types may have elements added to them by a
1956 // subsequent implementation or extension, so we keep them in
1957 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001958 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001959 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001960 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1961 if (V.first)
1962 return llvm::DIType(cast<llvm::MDNode>(V.first));
1963 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1964 Decl->getName(), TheCU, Unit,
1965 getLineNumber(Decl->getLocation()),
1966 TheCU.getLanguage());
1967 // Store the forward declaration in the cache.
1968 V.first = TC;
1969 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001970
David Blaikiee2eb89a2013-05-21 18:29:40 +00001971 // Register the type for replacement in finalize().
1972 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1973
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001974 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001975 }
1976
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001977 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001978 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001979
1980 return Res;
1981}
1982
Adrian Prantlb5a50072013-06-07 01:10:41 +00001983/// Currently the checksum of an interface includes the number of
1984/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00001985unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00001986 // The assumption is that the number of ivars can only increase
1987 // monotonically, so it is safe to just use their current number as
1988 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00001989 unsigned Sum = 0;
1990 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
1991 Ivar != 0; Ivar = Ivar->getNextIvar())
1992 ++Sum;
1993
1994 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00001995}
1996
1997ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1998 switch (Ty->getTypeClass()) {
1999 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002000 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2001 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002002 case Type::ObjCInterface:
2003 return cast<ObjCInterfaceType>(Ty)->getDecl();
2004 default:
2005 return 0;
2006 }
2007}
2008
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002009/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002010llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2011 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002012 // Handle qualifiers, which recursively handles what they refer to.
2013 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002014 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002015
2016 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002017
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002018 // Work out details of type.
2019 switch (Ty->getTypeClass()) {
2020#define TYPE(Class, Base)
2021#define ABSTRACT_TYPE(Class, Base)
2022#define NON_CANONICAL_TYPE(Class, Base)
2023#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2024#include "clang/AST/TypeNodes.def"
2025 llvm_unreachable("Dependent types cannot show up in debug information");
2026
2027 case Type::ExtVector:
2028 case Type::Vector:
2029 return CreateType(cast<VectorType>(Ty), Unit);
2030 case Type::ObjCObjectPointer:
2031 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2032 case Type::ObjCObject:
2033 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2034 case Type::ObjCInterface:
2035 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2036 case Type::Builtin:
2037 return CreateType(cast<BuiltinType>(Ty));
2038 case Type::Complex:
2039 return CreateType(cast<ComplexType>(Ty));
2040 case Type::Pointer:
2041 return CreateType(cast<PointerType>(Ty), Unit);
2042 case Type::BlockPointer:
2043 return CreateType(cast<BlockPointerType>(Ty), Unit);
2044 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002045 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002046 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002047 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002048 case Type::Enum:
2049 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2050 case Type::FunctionProto:
2051 case Type::FunctionNoProto:
2052 return CreateType(cast<FunctionType>(Ty), Unit);
2053 case Type::ConstantArray:
2054 case Type::VariableArray:
2055 case Type::IncompleteArray:
2056 return CreateType(cast<ArrayType>(Ty), Unit);
2057
2058 case Type::LValueReference:
2059 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2060 case Type::RValueReference:
2061 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2062
2063 case Type::MemberPointer:
2064 return CreateType(cast<MemberPointerType>(Ty), Unit);
2065
2066 case Type::Atomic:
2067 return CreateType(cast<AtomicType>(Ty), Unit);
2068
2069 case Type::Attributed:
2070 case Type::TemplateSpecialization:
2071 case Type::Elaborated:
2072 case Type::Paren:
2073 case Type::SubstTemplateTypeParm:
2074 case Type::TypeOfExpr:
2075 case Type::TypeOf:
2076 case Type::Decltype:
2077 case Type::UnaryTransform:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002078 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002079 case Type::Auto:
2080 Diag = "auto";
2081 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002082 }
Eric Christopher6537f082013-05-16 00:45:12 +00002083
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002084 assert(Diag && "Fall through without a diagnostic?");
2085 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2086 "debug information for %0 is not yet supported");
2087 CGM.getDiags().Report(DiagID)
2088 << Diag;
2089 return llvm::DIType();
2090}
2091
2092/// getOrCreateLimitedType - Get the type from the cache or create a new
2093/// limited type if necessary.
2094llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002095 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002096 if (Ty.isNull())
2097 return llvm::DIType();
2098
2099 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002100 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002101
2102 llvm::DIType T = getTypeOrNull(Ty);
2103
2104 // We may have cached a forward decl when we could have created
2105 // a non-forward decl. Go ahead and create a non-forward decl
2106 // now.
2107 if (T.Verify() && !T.isForwardDecl()) return T;
2108
2109 // Otherwise create the type.
2110 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2111
2112 if (T.Verify() && T.isForwardDecl())
2113 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2114 static_cast<llvm::Value*>(T)));
2115
2116 // And update the type cache.
2117 TypeCache[Ty.getAsOpaquePtr()] = Res;
2118 return Res;
2119}
2120
2121// TODO: Currently used for context chains when limiting debug info.
2122llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2123 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002124
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002125 // Get overall information about the record type for the debug info.
2126 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2127 unsigned Line = getLineNumber(RD->getLocation());
2128 StringRef RDName = getClassName(RD);
2129
2130 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002131 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002132 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2133 else
2134 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2135
2136 // If this is just a forward declaration, construct an appropriately
2137 // marked node and just return it.
2138 if (!RD->getDefinition())
2139 return createRecordFwdDecl(RD, RDContext);
2140
2141 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2142 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2143 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002144 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002145
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002146 if (RD->isUnion())
2147 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002148 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002149 else if (RD->isClass()) {
2150 // FIXME: This could be a struct type giving a default visibility different
2151 // than C++ class type, but needs llvm metadata changes first.
2152 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002153 Size, Align, 0, 0, llvm::DIType(),
2154 llvm::DIArray(), llvm::DIType(),
2155 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002156 } else
2157 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002158 Size, Align, 0, llvm::DIType(),
2159 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002160
2161 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002162 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002163
2164 if (CXXDecl) {
2165 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002166 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002167 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2168 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2169 // Seek non virtual primary base root.
2170 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002171 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2172 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2173 if (PBT && !BRL.isPrimaryBaseVirtual())
2174 PBase = PBT;
2175 else
2176 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002177 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002178 ContainingType = llvm::DICompositeType(
2179 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2180 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002181 ContainingType = RealDecl;
2182
David Blaikie2fcadbe2013-03-26 23:47:35 +00002183 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002184 }
2185 return llvm::DIType(RealDecl);
2186}
2187
2188/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2189/// declare composite types that haven't been processed yet.
2190llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2191
2192 // Work out details of type.
2193 switch (Ty->getTypeClass()) {
2194#define TYPE(Class, Base)
2195#define ABSTRACT_TYPE(Class, Base)
2196#define NON_CANONICAL_TYPE(Class, Base)
2197#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2198 #include "clang/AST/TypeNodes.def"
2199 llvm_unreachable("Dependent types cannot show up in debug information");
2200
2201 case Type::Record:
2202 return CreateLimitedType(cast<RecordType>(Ty));
2203 default:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002204 return CreateTypeNode(Ty, Unit, false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002205 }
2206}
2207
2208/// CreateMemberType - Create new member and increase Offset by FType's size.
2209llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2210 StringRef Name,
2211 uint64_t *Offset) {
2212 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2213 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2214 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2215 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2216 FieldSize, FieldAlign,
2217 *Offset, 0, FieldTy);
2218 *Offset += FieldSize;
2219 return Ty;
2220}
2221
David Blaikie9faebd22013-05-20 04:58:53 +00002222llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2223 // We only need a declaration (not a definition) of the type - so use whatever
2224 // we would otherwise do to get a type for a pointee. (forward declarations in
2225 // limited debug info, full definitions (if the type definition is available)
2226 // in unlimited debug info)
2227 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2228 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002229 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2230 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002231 }
2232 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2233 // This doesn't handle providing declarations (for functions or variables) for
2234 // entities without definitions in this TU, nor when the definition proceeds
2235 // the call to this function.
2236 // FIXME: This should be split out into more specific maps with support for
2237 // emitting forward declarations and merging definitions with declarations,
2238 // the same way as we do for types.
2239 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2240 DeclCache.find(D->getCanonicalDecl());
2241 if (I == DeclCache.end())
2242 return llvm::DIDescriptor();
2243 llvm::Value *V = I->second;
2244 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2245}
2246
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002247/// getFunctionDeclaration - Return debug info descriptor to describe method
2248/// declaration for the given method definition.
2249llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2250 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2251 if (!FD) return llvm::DISubprogram();
2252
2253 // Setup context.
2254 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2255
2256 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2257 MI = SPCache.find(FD->getCanonicalDecl());
2258 if (MI != SPCache.end()) {
2259 llvm::Value *V = MI->second;
2260 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2261 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2262 return SP;
2263 }
2264
2265 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2266 E = FD->redecls_end(); I != E; ++I) {
2267 const FunctionDecl *NextFD = *I;
2268 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2269 MI = SPCache.find(NextFD->getCanonicalDecl());
2270 if (MI != SPCache.end()) {
2271 llvm::Value *V = MI->second;
2272 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2273 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2274 return SP;
2275 }
2276 }
2277 return llvm::DISubprogram();
2278}
2279
2280// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2281// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002282llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2283 QualType FnType,
2284 llvm::DIFile F) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002285
2286 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2287 return getOrCreateMethodType(Method, F);
2288 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2289 // Add "self" and "_cmd"
2290 SmallVector<llvm::Value *, 16> Elts;
2291
2292 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002293 QualType ResultTy = OMethod->getResultType();
2294
2295 // Replace the instancetype keyword with the actual type.
2296 if (ResultTy == CGM.getContext().getObjCInstanceType())
2297 ResultTy = CGM.getContext().getPointerType(
2298 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2299
Adrian Prantl566a9c32013-05-10 21:08:31 +00002300 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002301 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002302 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2303 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2304 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002305 // "_cmd" pointer is always second argument.
2306 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2307 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2308 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002309 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002310 PE = OMethod->param_end(); PI != PE; ++PI)
2311 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2312
2313 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2314 return DBuilder.createSubroutineType(F, EltTypeArray);
2315 }
David Blaikie9a845292013-05-22 23:22:42 +00002316 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002317}
2318
2319/// EmitFunctionStart - Constructs the debug code for entering a function.
2320void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2321 llvm::Function *Fn,
2322 CGBuilderTy &Builder) {
2323
2324 StringRef Name;
2325 StringRef LinkageName;
2326
2327 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2328
2329 const Decl *D = GD.getDecl();
2330 // Function may lack declaration in source code if it is created by Clang
2331 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2332 bool HasDecl = (D != 0);
2333 // Use the location of the declaration.
2334 SourceLocation Loc;
2335 if (HasDecl)
2336 Loc = D->getLocation();
2337
2338 unsigned Flags = 0;
2339 llvm::DIFile Unit = getOrCreateFile(Loc);
2340 llvm::DIDescriptor FDContext(Unit);
2341 llvm::DIArray TParamsArray;
2342 if (!HasDecl) {
2343 // Use llvm function name.
2344 Name = Fn->getName();
2345 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2346 // If there is a DISubprogram for this function available then use it.
2347 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2348 FI = SPCache.find(FD->getCanonicalDecl());
2349 if (FI != SPCache.end()) {
2350 llvm::Value *V = FI->second;
2351 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2352 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2353 llvm::MDNode *SPN = SP;
2354 LexicalBlockStack.push_back(SPN);
2355 RegionMap[D] = llvm::WeakVH(SP);
2356 return;
2357 }
2358 }
2359 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002360 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002361 if (FD->hasPrototype()) {
2362 LinkageName = CGM.getMangledName(GD);
2363 Flags |= llvm::DIDescriptor::FlagPrototyped;
2364 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002365 // No need to replicate the linkage name if it isn't different from the
2366 // subprogram name, no need to have it at all unless coverage is enabled or
2367 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002368 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002369 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2370 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002371 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002372 LinkageName = StringRef();
2373
Eric Christopher13c97672013-05-16 00:45:23 +00002374 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002375 if (const NamespaceDecl *NSDecl =
2376 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2377 FDContext = getOrCreateNameSpace(NSDecl);
2378 else if (const RecordDecl *RDecl =
2379 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2380 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2381
2382 // Collect template parameters.
2383 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2384 }
2385 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2386 Name = getObjCMethodName(OMD);
2387 Flags |= llvm::DIDescriptor::FlagPrototyped;
2388 } else {
2389 // Use llvm function name.
2390 Name = Fn->getName();
2391 Flags |= llvm::DIDescriptor::FlagPrototyped;
2392 }
2393 if (!Name.empty() && Name[0] == '\01')
2394 Name = Name.substr(1);
2395
2396 unsigned LineNo = getLineNumber(Loc);
2397 if (!HasDecl || D->isImplicit())
2398 Flags |= llvm::DIDescriptor::FlagArtificial;
2399
David Blaikie9a845292013-05-22 23:22:42 +00002400 llvm::DICompositeType DIFnType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002401 llvm::DISubprogram SPDecl;
2402 if (HasDecl &&
Eric Christopher13c97672013-05-16 00:45:23 +00002403 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002404 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2405 SPDecl = getFunctionDeclaration(D);
2406 } else {
2407 // Create fake but valid subroutine type. Otherwise
2408 // llvm::DISubprogram::Verify() would return false, and
2409 // subprogram DIE will miss DW_AT_decl_file and
2410 // DW_AT_decl_line fields.
2411 SmallVector<llvm::Value*, 16> Elts;
2412 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2413 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2414 }
2415 llvm::DISubprogram SP;
2416 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2417 LineNo, DIFnType,
2418 Fn->hasInternalLinkage(), true/*definition*/,
2419 getLineNumber(CurLoc), Flags,
2420 CGM.getLangOpts().Optimize,
2421 Fn, TParamsArray, SPDecl);
David Blaikie9faebd22013-05-20 04:58:53 +00002422 if (HasDecl)
2423 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002424
2425 // Push function on region stack.
2426 llvm::MDNode *SPN = SP;
2427 LexicalBlockStack.push_back(SPN);
2428 if (HasDecl)
2429 RegionMap[D] = llvm::WeakVH(SP);
2430}
2431
2432/// EmitLocation - Emit metadata to indicate a change in line/column
2433/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002434void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2435 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002436
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002437 // Update our current location
2438 setLocation(Loc);
2439
2440 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2441
2442 // Don't bother if things are the same as last time.
2443 SourceManager &SM = CGM.getContext().getSourceManager();
2444 if (CurLoc == PrevLoc ||
2445 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2446 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002447 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2448 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2449 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002450 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002451
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002452 // Update last state.
2453 PrevLoc = CurLoc;
2454
2455 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002456 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2457 (getLineNumber(CurLoc),
2458 getColumnNumber(CurLoc, ForceColumnInfo),
2459 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002460}
2461
2462/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2463/// the stack.
2464void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2465 llvm::DIDescriptor D =
2466 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2467 llvm::DIDescriptor() :
2468 llvm::DIDescriptor(LexicalBlockStack.back()),
2469 getOrCreateFile(CurLoc),
2470 getLineNumber(CurLoc),
2471 getColumnNumber(CurLoc));
2472 llvm::MDNode *DN = D;
2473 LexicalBlockStack.push_back(DN);
2474}
2475
2476/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2477/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002478void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2479 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002480 // Set our current location.
2481 setLocation(Loc);
2482
2483 // Create a new lexical block and push it on the stack.
2484 CreateLexicalBlock(Loc);
2485
2486 // Emit a line table change for the current location inside the new scope.
2487 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2488 getColumnNumber(Loc),
2489 LexicalBlockStack.back()));
2490}
2491
2492/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2493/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002494void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2495 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002496 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2497
2498 // Provide an entry in the line table for the end of the block.
2499 EmitLocation(Builder, Loc);
2500
2501 LexicalBlockStack.pop_back();
2502}
2503
2504/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2505void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2506 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2507 unsigned RCount = FnBeginRegionCount.back();
2508 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2509
2510 // Pop all regions for this function.
2511 while (LexicalBlockStack.size() != RCount)
2512 EmitLexicalBlockEnd(Builder, CurLoc);
2513 FnBeginRegionCount.pop_back();
2514}
2515
Eric Christopher6537f082013-05-16 00:45:12 +00002516// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002517// See BuildByRefType.
2518llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2519 uint64_t *XOffset) {
2520
2521 SmallVector<llvm::Value *, 5> EltTys;
2522 QualType FType;
2523 uint64_t FieldSize, FieldOffset;
2524 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002525
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002526 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002527 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002528
2529 FieldOffset = 0;
2530 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2531 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2532 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2533 FType = CGM.getContext().IntTy;
2534 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2535 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2536
2537 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2538 if (HasCopyAndDispose) {
2539 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2540 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2541 &FieldOffset));
2542 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2543 &FieldOffset));
2544 }
2545 bool HasByrefExtendedLayout;
2546 Qualifiers::ObjCLifetime Lifetime;
2547 if (CGM.getContext().getByrefLifetime(Type,
2548 Lifetime, HasByrefExtendedLayout)
2549 && HasByrefExtendedLayout)
2550 EltTys.push_back(CreateMemberType(Unit, FType,
2551 "__byref_variable_layout",
2552 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002553
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002554 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2555 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002556 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002557 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002558 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2559 CharUnits AlignedOffsetInBytes
2560 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2561 CharUnits NumPaddingBytes
2562 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002563
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002564 if (NumPaddingBytes.isPositive()) {
2565 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2566 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2567 pad, ArrayType::Normal, 0);
2568 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2569 }
2570 }
Eric Christopher6537f082013-05-16 00:45:12 +00002571
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002572 FType = Type;
2573 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2574 FieldSize = CGM.getContext().getTypeSize(FType);
2575 FieldAlign = CGM.getContext().toBits(Align);
2576
Eric Christopher6537f082013-05-16 00:45:12 +00002577 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002578 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2579 0, FieldSize, FieldAlign,
2580 FieldOffset, 0, FieldTy);
2581 EltTys.push_back(FieldTy);
2582 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002583
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002584 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002585
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002586 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002587
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002588 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002589 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002590}
2591
2592/// EmitDeclare - Emit local variable declaration debug info.
2593void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002594 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002595 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002596 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002597 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2598
2599 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2600 llvm::DIType Ty;
2601 uint64_t XOffset = 0;
2602 if (VD->hasAttr<BlocksAttr>())
2603 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002604 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002605 Ty = getOrCreateType(VD->getType(), Unit);
2606
2607 // If there is no debug info for this type then do not emit debug info
2608 // for this variable.
2609 if (!Ty)
2610 return;
2611
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002612 // Get location information.
2613 unsigned Line = getLineNumber(VD->getLocation());
2614 unsigned Column = getColumnNumber(VD->getLocation());
2615 unsigned Flags = 0;
2616 if (VD->isImplicit())
2617 Flags |= llvm::DIDescriptor::FlagArtificial;
2618 // If this is the first argument and it is implicit then
2619 // give it an object pointer flag.
2620 // FIXME: There has to be a better way to do this, but for static
2621 // functions there won't be an implicit param at arg1 and
2622 // otherwise it is 'self' or 'this'.
2623 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2624 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2625
2626 llvm::MDNode *Scope = LexicalBlockStack.back();
2627
2628 StringRef Name = VD->getName();
2629 if (!Name.empty()) {
2630 if (VD->hasAttr<BlocksAttr>()) {
2631 CharUnits offset = CharUnits::fromQuantity(32);
2632 SmallVector<llvm::Value *, 9> addr;
2633 llvm::Type *Int64Ty = CGM.Int64Ty;
2634 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2635 // offset of __forwarding field
2636 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002637 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002638 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2639 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2640 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2641 // offset of x field
2642 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2643 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2644
2645 // Create the descriptor for the variable.
2646 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002647 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002648 llvm::DIDescriptor(Scope),
2649 VD->getName(), Unit, Line, Ty,
2650 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002651
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002652 // Insert an llvm.dbg.declare into the current block.
2653 llvm::Instruction *Call =
2654 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2655 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2656 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002657 } else if (isa<VariableArrayType>(VD->getType())) {
2658 // These are "complex" variables in that they need an op_deref.
2659 // Create the descriptor for the variable.
2660 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2661 llvm::DIBuilder::OpDeref);
2662 llvm::DIVariable D =
2663 DBuilder.createComplexVariable(Tag,
2664 llvm::DIDescriptor(Scope),
2665 Name, Unit, Line, Ty,
2666 Addr, ArgNo);
2667
2668 // Insert an llvm.dbg.declare into the current block.
2669 llvm::Instruction *Call =
2670 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2671 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2672 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002673 }
David Blaikie436653b2013-01-05 05:58:35 +00002674 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2675 // If VD is an anonymous union then Storage represents value for
2676 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002677 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002678 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 for (RecordDecl::field_iterator I = RD->field_begin(),
2680 E = RD->field_end();
2681 I != E; ++I) {
2682 FieldDecl *Field = *I;
2683 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2684 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002685
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002686 // Ignore unnamed fields. Do not ignore unnamed records.
2687 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2688 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002689
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002690 // Use VarDecl's Tag, Scope and Line number.
2691 llvm::DIVariable D =
2692 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002693 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002694 CGM.getLangOpts().Optimize, Flags,
2695 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002696
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002697 // Insert an llvm.dbg.declare into the current block.
2698 llvm::Instruction *Call =
2699 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2700 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2701 }
David Blaikied8180cf2013-01-05 20:03:07 +00002702 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002703 }
2704 }
David Blaikie436653b2013-01-05 05:58:35 +00002705
2706 // Create the descriptor for the variable.
2707 llvm::DIVariable D =
2708 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2709 Name, Unit, Line, Ty,
2710 CGM.getLangOpts().Optimize, Flags, ArgNo);
2711
2712 // Insert an llvm.dbg.declare into the current block.
2713 llvm::Instruction *Call =
2714 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2715 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002716}
2717
2718void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2719 llvm::Value *Storage,
2720 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002721 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002722 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2723}
2724
Adrian Prantle86fcc42013-03-29 19:20:29 +00002725/// Look up the completed type for a self pointer in the TypeCache and
2726/// create a copy of it with the ObjectPointer and Artificial flags
2727/// set. If the type is not cached, a new one is created. This should
2728/// never happen though, since creating a type for the implicit self
2729/// argument implies that we already parsed the interface definition
2730/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002731llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2732 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002733 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2734 if (CachedTy.Verify()) Ty = CachedTy;
2735 else DEBUG(llvm::dbgs() << "No cached type for self.");
2736 return DBuilder.createObjectPointerType(Ty);
2737}
2738
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2740 llvm::Value *Storage,
2741 CGBuilderTy &Builder,
2742 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002743 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002744 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002745
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002746 if (Builder.GetInsertBlock() == 0)
2747 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002748
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002749 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002750
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002751 uint64_t XOffset = 0;
2752 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2753 llvm::DIType Ty;
2754 if (isByRef)
2755 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002756 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002757 Ty = getOrCreateType(VD->getType(), Unit);
2758
2759 // Self is passed along as an implicit non-arg variable in a
2760 // block. Mark it as the object pointer.
2761 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002762 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002763
2764 // Get location information.
2765 unsigned Line = getLineNumber(VD->getLocation());
2766 unsigned Column = getColumnNumber(VD->getLocation());
2767
2768 const llvm::DataLayout &target = CGM.getDataLayout();
2769
2770 CharUnits offset = CharUnits::fromQuantity(
2771 target.getStructLayout(blockInfo.StructureType)
2772 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2773
2774 SmallVector<llvm::Value *, 9> addr;
2775 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002776 if (isa<llvm::AllocaInst>(Storage))
2777 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002778 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2779 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2780 if (isByRef) {
2781 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2782 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2783 // offset of __forwarding field
2784 offset = CGM.getContext()
2785 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2786 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2787 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2788 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2789 // offset of x field
2790 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2791 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2792 }
2793
2794 // Create the descriptor for the variable.
2795 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002796 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002797 llvm::DIDescriptor(LexicalBlockStack.back()),
2798 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002799
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002800 // Insert an llvm.dbg.declare into the current block.
2801 llvm::Instruction *Call =
2802 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2803 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2804 LexicalBlockStack.back()));
2805}
2806
2807/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2808/// variable declaration.
2809void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2810 unsigned ArgNo,
2811 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002812 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002813 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2814}
2815
2816namespace {
2817 struct BlockLayoutChunk {
2818 uint64_t OffsetInBits;
2819 const BlockDecl::Capture *Capture;
2820 };
2821 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2822 return l.OffsetInBits < r.OffsetInBits;
2823 }
2824}
2825
2826void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002827 llvm::Value *Arg,
2828 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002829 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002830 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002831 ASTContext &C = CGM.getContext();
2832 const BlockDecl *blockDecl = block.getBlockDecl();
2833
2834 // Collect some general information about the block's location.
2835 SourceLocation loc = blockDecl->getCaretLocation();
2836 llvm::DIFile tunit = getOrCreateFile(loc);
2837 unsigned line = getLineNumber(loc);
2838 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002839
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002840 // Build the debug-info type for the block literal.
2841 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2842
2843 const llvm::StructLayout *blockLayout =
2844 CGM.getDataLayout().getStructLayout(block.StructureType);
2845
2846 SmallVector<llvm::Value*, 16> fields;
2847 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2848 blockLayout->getElementOffsetInBits(0),
2849 tunit, tunit));
2850 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2851 blockLayout->getElementOffsetInBits(1),
2852 tunit, tunit));
2853 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2854 blockLayout->getElementOffsetInBits(2),
2855 tunit, tunit));
2856 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2857 blockLayout->getElementOffsetInBits(3),
2858 tunit, tunit));
2859 fields.push_back(createFieldType("__descriptor",
2860 C.getPointerType(block.NeedsCopyDispose ?
2861 C.getBlockDescriptorExtendedType() :
2862 C.getBlockDescriptorType()),
2863 0, loc, AS_public,
2864 blockLayout->getElementOffsetInBits(4),
2865 tunit, tunit));
2866
2867 // We want to sort the captures by offset, not because DWARF
2868 // requires this, but because we're paranoid about debuggers.
2869 SmallVector<BlockLayoutChunk, 8> chunks;
2870
2871 // 'this' capture.
2872 if (blockDecl->capturesCXXThis()) {
2873 BlockLayoutChunk chunk;
2874 chunk.OffsetInBits =
2875 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2876 chunk.Capture = 0;
2877 chunks.push_back(chunk);
2878 }
2879
2880 // Variable captures.
2881 for (BlockDecl::capture_const_iterator
2882 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2883 i != e; ++i) {
2884 const BlockDecl::Capture &capture = *i;
2885 const VarDecl *variable = capture.getVariable();
2886 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2887
2888 // Ignore constant captures.
2889 if (captureInfo.isConstant())
2890 continue;
2891
2892 BlockLayoutChunk chunk;
2893 chunk.OffsetInBits =
2894 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2895 chunk.Capture = &capture;
2896 chunks.push_back(chunk);
2897 }
2898
2899 // Sort by offset.
2900 llvm::array_pod_sort(chunks.begin(), chunks.end());
2901
2902 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2903 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2904 uint64_t offsetInBits = i->OffsetInBits;
2905 const BlockDecl::Capture *capture = i->Capture;
2906
2907 // If we have a null capture, this must be the C++ 'this' capture.
2908 if (!capture) {
2909 const CXXMethodDecl *method =
2910 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2911 QualType type = method->getThisType(C);
2912
2913 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2914 offsetInBits, tunit, tunit));
2915 continue;
2916 }
2917
2918 const VarDecl *variable = capture->getVariable();
2919 StringRef name = variable->getName();
2920
2921 llvm::DIType fieldType;
2922 if (capture->isByRef()) {
2923 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2924
2925 // FIXME: this creates a second copy of this type!
2926 uint64_t xoffset;
2927 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2928 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2929 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2930 ptrInfo.first, ptrInfo.second,
2931 offsetInBits, 0, fieldType);
2932 } else {
2933 fieldType = createFieldType(name, variable->getType(), 0,
2934 loc, AS_public, offsetInBits, tunit, tunit);
2935 }
2936 fields.push_back(fieldType);
2937 }
2938
2939 SmallString<36> typeName;
2940 llvm::raw_svector_ostream(typeName)
2941 << "__block_literal_" << CGM.getUniqueBlockCount();
2942
2943 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2944
2945 llvm::DIType type =
2946 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2947 CGM.getContext().toBits(block.BlockSize),
2948 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002949 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002950 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2951
2952 // Get overall information about the block.
2953 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2954 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002955
2956 // Create the descriptor for the parameter.
2957 llvm::DIVariable debugVar =
2958 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002959 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002960 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002961 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002962 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2963
Adrian Prantlbea407c2013-03-14 21:52:59 +00002964 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002965 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002966 llvm::Instruction *DbgVal =
2967 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002968 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002969 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2970 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002971
Adrian Prantlbea407c2013-03-14 21:52:59 +00002972 // Insert an llvm.dbg.declare into the current block.
2973 llvm::Instruction *DbgDecl =
2974 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2975 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002976}
2977
Eric Christopher0395de32013-01-16 01:22:32 +00002978/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2979/// a static data member of a class, find its corresponding in-class
2980/// declaration.
2981llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2982 if (cast<VarDecl>(D)->isStaticDataMember()) {
2983 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2984 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2985 if (MI != StaticDataMemberCache.end())
2986 // Verify the info still exists.
2987 if (llvm::Value *V = MI->second)
2988 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2989 }
2990 return llvm::DIDerivedType();
2991}
2992
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002993/// EmitGlobalVariable - Emit information about a global variable.
2994void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2995 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00002996 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002997 // Create global variable debug descriptor.
2998 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2999 unsigned LineNo = getLineNumber(D->getLocation());
3000
3001 setLocation(D->getLocation());
3002
3003 QualType T = D->getType();
3004 if (T->isIncompleteArrayType()) {
3005
3006 // CodeGen turns int[] into int[1] so we'll do the same here.
3007 llvm::APInt ConstVal(32, 1);
3008 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3009
3010 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3011 ArrayType::Normal, 0);
3012 }
3013 StringRef DeclName = D->getName();
3014 StringRef LinkageName;
3015 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3016 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3017 LinkageName = Var->getName();
3018 if (LinkageName == DeclName)
3019 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003020 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003021 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003022 llvm::DIGlobalVariable GV =
3023 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3024 LineNo, getOrCreateType(T, Unit),
3025 Var->hasInternalLinkage(), Var,
3026 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003027 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003028}
3029
3030/// EmitGlobalVariable - Emit information about an objective-c interface.
3031void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3032 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003033 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003034 // Create global variable debug descriptor.
3035 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3036 unsigned LineNo = getLineNumber(ID->getLocation());
3037
3038 StringRef Name = ID->getName();
3039
3040 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3041 if (T->isIncompleteArrayType()) {
3042
3043 // CodeGen turns int[] into int[1] so we'll do the same here.
3044 llvm::APInt ConstVal(32, 1);
3045 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3046
3047 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3048 ArrayType::Normal, 0);
3049 }
3050
3051 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3052 getOrCreateType(T, Unit),
3053 Var->hasInternalLinkage(), Var);
3054}
3055
3056/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003057void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003058 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003059 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003060 // Create the descriptor for the variable.
3061 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3062 StringRef Name = VD->getName();
3063 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3064 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3065 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3066 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3067 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3068 }
3069 // Do not use DIGlobalVariable for enums.
3070 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3071 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003072 llvm::DIGlobalVariable GV =
3073 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3074 getLineNumber(VD->getLocation()), Ty, true,
3075 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003076 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3077}
3078
3079llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3080 if (!LexicalBlockStack.empty())
3081 return llvm::DIScope(LexicalBlockStack.back());
3082 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003083}
3084
David Blaikie957dac52013-04-22 06:13:21 +00003085void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003086 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3087 return;
David Blaikie957dac52013-04-22 06:13:21 +00003088 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003089 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3090 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003091 getLineNumber(UD.getLocation()));
3092}
3093
David Blaikie9faebd22013-05-20 04:58:53 +00003094void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3095 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3096 return;
3097 assert(UD.shadow_size() &&
3098 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3099 // Emitting one decl is sufficient - debuggers can detect that this is an
3100 // overloaded name & provide lookup for all the overloads.
3101 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003102 if (llvm::DIDescriptor Target =
3103 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003104 DBuilder.createImportedDeclaration(
3105 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3106 getLineNumber(USD.getLocation()));
3107}
3108
David Blaikiefc46ebc2013-05-20 22:50:41 +00003109llvm::DIImportedEntity
3110CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3111 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3112 return llvm::DIImportedEntity(0);
3113 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3114 if (VH)
3115 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3116 llvm::DIImportedEntity R(0);
3117 if (const NamespaceAliasDecl *Underlying =
3118 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3119 // This could cache & dedup here rather than relying on metadata deduping.
3120 R = DBuilder.createImportedModule(
3121 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3122 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3123 NA.getName());
3124 else
3125 R = DBuilder.createImportedModule(
3126 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3127 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3128 getLineNumber(NA.getLocation()), NA.getName());
3129 VH = R;
3130 return R;
3131}
3132
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003133/// getOrCreateNamesSpace - Return namespace descriptor for the given
3134/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003135llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003136CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003137 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003138 NameSpaceCache.find(NSDecl);
3139 if (I != NameSpaceCache.end())
3140 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003141
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003142 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3143 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003144 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003145 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3146 llvm::DINameSpace NS =
3147 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3148 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3149 return NS;
3150}
3151
3152void CGDebugInfo::finalize() {
3153 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3154 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3155 llvm::DIType Ty, RepTy;
3156 // Verify that the debug info still exists.
3157 if (llvm::Value *V = VI->second)
3158 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003159
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003160 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3161 TypeCache.find(VI->first);
3162 if (it != TypeCache.end()) {
3163 // Verify that the debug info still exists.
3164 if (llvm::Value *V = it->second)
3165 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3166 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003167
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003168 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003169 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003170 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003171
3172 // We keep our own list of retained types, because we need to look
3173 // up the final type in the type cache.
3174 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3175 RE = RetainedTypes.end(); RI != RE; ++RI)
3176 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3177
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003178 DBuilder.finalize();
3179}