blob: 4bd0e779f4c9497ad58f1af2f90c5778106881b0 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclFriend.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/Basic/FileManager.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/Version.h"
28#include "clang/Frontend/CodeGenOptions.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "llvm/Support/Dwarf.h"
38#include "llvm/Support/FileSystem.h"
39using namespace clang;
40using namespace clang::CodeGen;
41
42CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43 : CGM(CGM), DBuilder(CGM.getModule()),
44 BlockLiteralGenericSet(false) {
45 CreateCompileUnit();
46}
47
48CGDebugInfo::~CGDebugInfo() {
49 assert(LexicalBlockStack.empty() &&
50 "Region stack mismatch, stack not empty!");
51}
52
53void CGDebugInfo::setLocation(SourceLocation Loc) {
54 // If the new location isn't valid return.
55 if (!Loc.isValid()) return;
56
57 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
58
59 // If we've changed files in the middle of a lexical scope go ahead
60 // and create a new lexical scope with file node if it's different
61 // from the one in the scope.
62 if (LexicalBlockStack.empty()) return;
63
64 SourceManager &SM = CGM.getContext().getSourceManager();
65 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
66 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
67
68 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
69 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
70 return;
71
72 llvm::MDNode *LB = LexicalBlockStack.back();
73 llvm::DIScope Scope = llvm::DIScope(LB);
74 if (Scope.isLexicalBlockFile()) {
75 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
76 llvm::DIDescriptor D
77 = DBuilder.createLexicalBlockFile(LBF.getScope(),
78 getOrCreateFile(CurLoc));
79 llvm::MDNode *N = D;
80 LexicalBlockStack.pop_back();
81 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +000082 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000083 llvm::DIDescriptor D
84 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
85 llvm::MDNode *N = D;
86 LexicalBlockStack.pop_back();
87 LexicalBlockStack.push_back(N);
88 }
89}
90
91/// getContextDescriptor - Get context info for the decl.
92llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
93 if (!Context)
94 return TheCU;
95
96 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97 I = RegionMap.find(Context);
98 if (I != RegionMap.end()) {
99 llvm::Value *V = I->second;
100 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
101 }
102
103 // Check namespace.
104 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
105 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
106
107 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
108 if (!RDecl->isDependentType()) {
109 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
110 getOrCreateMainFile());
111 return llvm::DIDescriptor(Ty);
112 }
113 }
114 return TheCU;
115}
116
117/// getFunctionName - Get function name for the given FunctionDecl. If the
118/// name is constructred on demand (e.g. C++ destructor) then the name
119/// is stored on the side.
120StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
121 assert (FD && "Invalid FunctionDecl!");
122 IdentifierInfo *FII = FD->getIdentifier();
123 FunctionTemplateSpecializationInfo *Info
124 = FD->getTemplateSpecializationInfo();
125 if (!Info && FII)
126 return FII->getName();
127
128 // Otherwise construct human readable name for debug info.
129 std::string NS = FD->getNameAsString();
130
131 // Add any template specialization args.
132 if (Info) {
133 const TemplateArgumentList *TArgs = Info->TemplateArguments;
134 const TemplateArgument *Args = TArgs->data();
135 unsigned NumArgs = TArgs->size();
136 PrintingPolicy Policy(CGM.getLangOpts());
137 NS += TemplateSpecializationType::PrintTemplateArgumentList(Args,
138 NumArgs,
139 Policy);
140 }
141
142 // Copy this name on the side and use its reference.
143 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
144 memcpy(StrPtr, NS.data(), NS.length());
145 return StringRef(StrPtr, NS.length());
146}
147
148StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
149 SmallString<256> MethodName;
150 llvm::raw_svector_ostream OS(MethodName);
151 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
152 const DeclContext *DC = OMD->getDeclContext();
153 if (const ObjCImplementationDecl *OID =
154 dyn_cast<const ObjCImplementationDecl>(DC)) {
155 OS << OID->getName();
156 } else if (const ObjCInterfaceDecl *OID =
157 dyn_cast<const ObjCInterfaceDecl>(DC)) {
158 OS << OID->getName();
159 } else if (const ObjCCategoryImplDecl *OCD =
160 dyn_cast<const ObjCCategoryImplDecl>(DC)){
161 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
162 OCD->getIdentifier()->getNameStart() << ')';
163 }
164 OS << ' ' << OMD->getSelector().getAsString() << ']';
165
166 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
167 memcpy(StrPtr, MethodName.begin(), OS.tell());
168 return StringRef(StrPtr, OS.tell());
169}
170
171/// getSelectorName - Return selector name. This is used for debugging
172/// info.
173StringRef CGDebugInfo::getSelectorName(Selector S) {
174 const std::string &SName = S.getAsString();
175 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
176 memcpy(StrPtr, SName.data(), SName.size());
177 return StringRef(StrPtr, SName.size());
178}
179
180/// getClassName - Get class name including template argument list.
181StringRef
182CGDebugInfo::getClassName(const RecordDecl *RD) {
183 const ClassTemplateSpecializationDecl *Spec
184 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
185 if (!Spec)
186 return RD->getName();
187
188 const TemplateArgument *Args;
189 unsigned NumArgs;
190 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
191 const TemplateSpecializationType *TST =
192 cast<TemplateSpecializationType>(TAW->getType());
193 Args = TST->getArgs();
194 NumArgs = TST->getNumArgs();
195 } else {
196 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
197 Args = TemplateArgs.data();
198 NumArgs = TemplateArgs.size();
199 }
200 StringRef Name = RD->getIdentifier()->getName();
201 PrintingPolicy Policy(CGM.getLangOpts());
202 std::string TemplateArgList =
203 TemplateSpecializationType::PrintTemplateArgumentList(Args, NumArgs, Policy);
204
205 // Copy this name on the side and use its reference.
206 size_t Length = Name.size() + TemplateArgList.size();
207 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
208 memcpy(StrPtr, Name.data(), Name.size());
209 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
210 return StringRef(StrPtr, Length);
211}
212
213/// getOrCreateFile - Get the file debug info descriptor for the input location.
214llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
215 if (!Loc.isValid())
216 // If Location is not valid then use main input file.
217 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
218
219 SourceManager &SM = CGM.getContext().getSourceManager();
220 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
221
222 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
223 // If the location is not valid then use main input file.
224 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
225
226 // Cache the results.
227 const char *fname = PLoc.getFilename();
228 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
229 DIFileCache.find(fname);
230
231 if (it != DIFileCache.end()) {
232 // Verify that the information still exists.
233 if (llvm::Value *V = it->second)
234 return llvm::DIFile(cast<llvm::MDNode>(V));
235 }
236
237 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
238
239 DIFileCache[fname] = F;
240 return F;
241}
242
243/// getOrCreateMainFile - Get the file info for main compile unit.
244llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
245 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
246}
247
248/// getLineNumber - Get line number for the location. If location is invalid
249/// then use current location.
250unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
251 if (Loc.isInvalid() && CurLoc.isInvalid())
252 return 0;
253 SourceManager &SM = CGM.getContext().getSourceManager();
254 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
255 return PLoc.isValid()? PLoc.getLine() : 0;
256}
257
258/// getColumnNumber - Get column number for the location.
259unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
260 // We may not want column information at all.
261 if (!CGM.getCodeGenOpts().DebugColumnInfo)
262 return 0;
263
264 // If the location is invalid then use the current column.
265 if (Loc.isInvalid() && CurLoc.isInvalid())
266 return 0;
267 SourceManager &SM = CGM.getContext().getSourceManager();
268 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
269 return PLoc.isValid()? PLoc.getColumn() : 0;
270}
271
272StringRef CGDebugInfo::getCurrentDirname() {
273 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
274 return CGM.getCodeGenOpts().DebugCompilationDir;
275
276 if (!CWDName.empty())
277 return CWDName;
278 SmallString<256> CWD;
279 llvm::sys::fs::current_path(CWD);
280 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
281 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
282 return CWDName = StringRef(CompDirnamePtr, CWD.size());
283}
284
285/// CreateCompileUnit - Create new compile unit.
286void CGDebugInfo::CreateCompileUnit() {
287
288 // Get absolute path name.
289 SourceManager &SM = CGM.getContext().getSourceManager();
290 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
291 if (MainFileName.empty())
292 MainFileName = "<unknown>";
293
294 // The main file name provided via the "-main-file-name" option contains just
295 // the file name itself with no path information. This file name may have had
296 // a relative path, so we look into the actual file entry for the main
297 // file to determine the real absolute path for the file.
298 std::string MainFileDir;
299 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
300 MainFileDir = MainFile->getDir()->getName();
301 if (MainFileDir != ".")
302 MainFileName = MainFileDir + "/" + MainFileName;
303 }
304
305 // Save filename string.
306 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
307 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
308 StringRef Filename(FilenamePtr, MainFileName.length());
309
310 unsigned LangTag;
311 const LangOptions &LO = CGM.getLangOpts();
312 if (LO.CPlusPlus) {
313 if (LO.ObjC1)
314 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
315 else
316 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
317 } else if (LO.ObjC1) {
318 LangTag = llvm::dwarf::DW_LANG_ObjC;
319 } else if (LO.C99) {
320 LangTag = llvm::dwarf::DW_LANG_C99;
321 } else {
322 LangTag = llvm::dwarf::DW_LANG_C89;
323 }
324
325 std::string Producer = getClangFullVersion();
326
327 // Figure out which version of the ObjC runtime we have.
328 unsigned RuntimeVers = 0;
329 if (LO.ObjC1)
330 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
331
332 // Create new compile unit.
Eric Christopherc0c5d462013-02-21 22:35:08 +0000333 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
334 Producer, LO.Optimize,
335 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
Guy Benyei11169dd2012-12-18 14:30:41 +0000336 // FIXME - Eliminate TheCU.
337 TheCU = llvm::DICompileUnit(DBuilder.getCU());
338}
339
340/// CreateType - Get the Basic type from the cache or create a new
341/// one if necessary.
342llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
343 unsigned Encoding = 0;
344 StringRef BTName;
345 switch (BT->getKind()) {
346#define BUILTIN_TYPE(Id, SingletonId)
347#define PLACEHOLDER_TYPE(Id, SingletonId) \
348 case BuiltinType::Id:
349#include "clang/AST/BuiltinTypes.def"
350 case BuiltinType::Dependent:
351 llvm_unreachable("Unexpected builtin type");
352 case BuiltinType::NullPtr:
353 return DBuilder.
354 createNullPtrType(BT->getName(CGM.getLangOpts()));
355 case BuiltinType::Void:
356 return llvm::DIType();
357 case BuiltinType::ObjCClass:
358 if (ClassTy.Verify())
359 return ClassTy;
360 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
361 "objc_class", TheCU,
362 getOrCreateMainFile(), 0);
363 return ClassTy;
364 case BuiltinType::ObjCId: {
365 // typedef struct objc_class *Class;
366 // typedef struct objc_object {
367 // Class isa;
368 // } *id;
369
370 if (ObjTy.Verify())
371 return ObjTy;
372
373 if (!ClassTy.Verify())
374 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
375 "objc_class", TheCU,
376 getOrCreateMainFile(), 0);
377
378 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
379
380 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
381
382 llvm::DIType FwdTy = DBuilder.createStructType(TheCU, "objc_object",
383 getOrCreateMainFile(),
384 0, 0, 0, 0,
385 llvm::DIArray());
386
387 llvm::TrackingVH<llvm::MDNode> ObjNode(FwdTy);
388 SmallVector<llvm::Value *, 1> EltTys;
389 llvm::DIType FieldTy =
390 DBuilder.createMemberType(llvm::DIDescriptor(ObjNode), "isa",
391 getOrCreateMainFile(), 0, Size,
392 0, 0, 0, ISATy);
393 EltTys.push_back(FieldTy);
394 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
395
396 ObjNode->replaceOperandWith(10, Elements);
397 ObjTy = llvm::DIType(ObjNode);
398 return ObjTy;
399 }
400 case BuiltinType::ObjCSel: {
401 if (SelTy.Verify())
402 return SelTy;
403 SelTy =
404 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
405 "objc_selector", TheCU, getOrCreateMainFile(),
406 0);
407 return SelTy;
408 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000409
410 case BuiltinType::OCLImage1d:
411 return getOrCreateStructPtrType("opencl_image1d_t",
412 OCLImage1dDITy);
413 case BuiltinType::OCLImage1dArray:
414 return getOrCreateStructPtrType("opencl_image1d_array_t",
415 OCLImage1dArrayDITy);
416 case BuiltinType::OCLImage1dBuffer:
417 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
418 OCLImage1dBufferDITy);
419 case BuiltinType::OCLImage2d:
420 return getOrCreateStructPtrType("opencl_image2d_t",
421 OCLImage2dDITy);
422 case BuiltinType::OCLImage2dArray:
423 return getOrCreateStructPtrType("opencl_image2d_array_t",
424 OCLImage2dArrayDITy);
425 case BuiltinType::OCLImage3d:
426 return getOrCreateStructPtrType("opencl_image3d_t",
427 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000428 case BuiltinType::OCLSampler:
429 return DBuilder.createBasicType("opencl_sampler_t",
430 CGM.getContext().getTypeSize(BT),
431 CGM.getContext().getTypeAlign(BT),
432 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000433 case BuiltinType::OCLEvent:
434 return getOrCreateStructPtrType("opencl_event_t",
435 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000436
Guy Benyei11169dd2012-12-18 14:30:41 +0000437 case BuiltinType::UChar:
438 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
439 case BuiltinType::Char_S:
440 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
441 case BuiltinType::Char16:
442 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
443 case BuiltinType::UShort:
444 case BuiltinType::UInt:
445 case BuiltinType::UInt128:
446 case BuiltinType::ULong:
447 case BuiltinType::WChar_U:
448 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
449 case BuiltinType::Short:
450 case BuiltinType::Int:
451 case BuiltinType::Int128:
452 case BuiltinType::Long:
453 case BuiltinType::WChar_S:
454 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
455 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
456 case BuiltinType::Half:
457 case BuiltinType::Float:
458 case BuiltinType::LongDouble:
459 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
460 }
461
462 switch (BT->getKind()) {
463 case BuiltinType::Long: BTName = "long int"; break;
464 case BuiltinType::LongLong: BTName = "long long int"; break;
465 case BuiltinType::ULong: BTName = "long unsigned int"; break;
466 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
467 default:
468 BTName = BT->getName(CGM.getLangOpts());
469 break;
470 }
471 // Bit size, align and offset of the type.
472 uint64_t Size = CGM.getContext().getTypeSize(BT);
473 uint64_t Align = CGM.getContext().getTypeAlign(BT);
474 llvm::DIType DbgTy =
475 DBuilder.createBasicType(BTName, Size, Align, Encoding);
476 return DbgTy;
477}
478
479llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
480 // Bit size, align and offset of the type.
481 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
482 if (Ty->isComplexIntegerType())
483 Encoding = llvm::dwarf::DW_ATE_lo_user;
484
485 uint64_t Size = CGM.getContext().getTypeSize(Ty);
486 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
487 llvm::DIType DbgTy =
488 DBuilder.createBasicType("complex", Size, Align, Encoding);
489
490 return DbgTy;
491}
492
493/// CreateCVRType - Get the qualified type from the cache or create
494/// a new one if necessary.
495llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
496 QualifierCollector Qc;
497 const Type *T = Qc.strip(Ty);
498
499 // Ignore these qualifiers for now.
500 Qc.removeObjCGCAttr();
501 Qc.removeAddressSpace();
502 Qc.removeObjCLifetime();
503
504 // We will create one Derived type for one qualifier and recurse to handle any
505 // additional ones.
506 unsigned Tag;
507 if (Qc.hasConst()) {
508 Tag = llvm::dwarf::DW_TAG_const_type;
509 Qc.removeConst();
510 } else if (Qc.hasVolatile()) {
511 Tag = llvm::dwarf::DW_TAG_volatile_type;
512 Qc.removeVolatile();
513 } else if (Qc.hasRestrict()) {
514 Tag = llvm::dwarf::DW_TAG_restrict_type;
515 Qc.removeRestrict();
516 } else {
517 assert(Qc.empty() && "Unknown type qualifier for debug info");
518 return getOrCreateType(QualType(T, 0), Unit);
519 }
520
521 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
522
523 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
524 // CVR derived types.
525 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
526
527 return DbgTy;
528}
529
530llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
531 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000532
533 // The frontend treats 'id' as a typedef to an ObjCObjectType,
534 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
535 // debug info, we want to emit 'id' in both cases.
536 if (Ty->isObjCQualifiedIdType())
537 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
538
Guy Benyei11169dd2012-12-18 14:30:41 +0000539 llvm::DIType DbgTy =
540 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
541 Ty->getPointeeType(), Unit);
542 return DbgTy;
543}
544
545llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
546 llvm::DIFile Unit) {
547 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
548 Ty->getPointeeType(), Unit);
549}
550
551// Creates a forward declaration for a RecordDecl in the given context.
552llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
553 llvm::DIDescriptor Ctx) {
554 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
555 unsigned Line = getLineNumber(RD->getLocation());
556 StringRef RDName = getClassName(RD);
557
558 unsigned Tag = 0;
559 if (RD->isStruct() || RD->isInterface())
560 Tag = llvm::dwarf::DW_TAG_structure_type;
561 else if (RD->isUnion())
562 Tag = llvm::dwarf::DW_TAG_union_type;
563 else {
564 assert(RD->isClass());
565 Tag = llvm::dwarf::DW_TAG_class_type;
566 }
567
568 // Create the type.
569 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
570}
571
572// Walk up the context chain and create forward decls for record decls,
573// and normal descriptors for namespaces.
574llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
575 if (!Context)
576 return TheCU;
577
578 // See if we already have the parent.
579 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
580 I = RegionMap.find(Context);
581 if (I != RegionMap.end()) {
582 llvm::Value *V = I->second;
583 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
584 }
585
586 // Check namespace.
587 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
588 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
589
590 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
591 if (!RD->isDependentType()) {
592 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
Eric Christopherc0c5d462013-02-21 22:35:08 +0000593 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 return llvm::DIDescriptor(Ty);
595 }
596 }
597 return TheCU;
598}
599
600/// CreatePointeeType - Create Pointee type. If Pointee is a record
601/// then emit record's fwd if debug info size reduction is enabled.
602llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
603 llvm::DIFile Unit) {
604 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
605 return getOrCreateType(PointeeTy, Unit);
606
607 // Limit debug info for the pointee type.
608
609 // If we have an existing type, use that, it's still smaller than creating
610 // a new type.
611 llvm::DIType Ty = getTypeOrNull(PointeeTy);
612 if (Ty.Verify()) return Ty;
613
614 // Handle qualifiers.
615 if (PointeeTy.hasLocalQualifiers())
616 return CreateQualifiedType(PointeeTy, Unit);
617
618 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
619 RecordDecl *RD = RTy->getDecl();
620 llvm::DIDescriptor FDContext =
621 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
622 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
623 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
624 return RetTy;
625 }
626 return getOrCreateType(PointeeTy, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000627}
628
629llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
630 const Type *Ty,
631 QualType PointeeTy,
632 llvm::DIFile Unit) {
633 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
634 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
635 return DBuilder.createReferenceType(Tag,
636 CreatePointeeType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // Bit size, align and offset of the type.
639 // Size is always the size of a pointer. We can't use getTypeSize here
640 // because that does not return the correct value for references.
641 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
642 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
643 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
644
645 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
646 Size, Align);
647}
648
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000649llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
650 if (Cache.Verify())
651 return Cache;
652 Cache =
653 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
654 Name, TheCU, getOrCreateMainFile(),
655 0);
656 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
657 Cache = DBuilder.createPointerType(Cache, Size);
658 return Cache;
659}
660
Guy Benyei11169dd2012-12-18 14:30:41 +0000661llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
662 llvm::DIFile Unit) {
663 if (BlockLiteralGenericSet)
664 return BlockLiteralGeneric;
665
666 SmallVector<llvm::Value *, 8> EltTys;
667 llvm::DIType FieldTy;
668 QualType FType;
669 uint64_t FieldSize, FieldOffset;
670 unsigned FieldAlign;
671 llvm::DIArray Elements;
672 llvm::DIType EltTy, DescTy;
673
674 FieldOffset = 0;
675 FType = CGM.getContext().UnsignedLongTy;
676 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
677 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
678
679 Elements = DBuilder.getOrCreateArray(EltTys);
680 EltTys.clear();
681
682 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
683 unsigned LineNo = getLineNumber(CurLoc);
684
685 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
686 Unit, LineNo, FieldOffset, 0,
687 Flags, Elements);
688
689 // Bit size, align and offset of the type.
690 uint64_t Size = CGM.getContext().getTypeSize(Ty);
691
692 DescTy = DBuilder.createPointerType(EltTy, Size);
693
694 FieldOffset = 0;
695 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
696 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
697 FType = CGM.getContext().IntTy;
698 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
699 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
700 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
701 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
702
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 FieldTy = DescTy;
705 FieldSize = CGM.getContext().getTypeSize(Ty);
706 FieldAlign = CGM.getContext().getTypeAlign(Ty);
707 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
708 LineNo, FieldSize, FieldAlign,
709 FieldOffset, 0, FieldTy);
710 EltTys.push_back(FieldTy);
711
712 FieldOffset += FieldSize;
713 Elements = DBuilder.getOrCreateArray(EltTys);
714
715 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
716 Unit, LineNo, FieldOffset, 0,
717 Flags, Elements);
718
719 BlockLiteralGenericSet = true;
720 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
721 return BlockLiteralGeneric;
722}
723
724llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
725 // Typedefs are derived from some other type. If we have a typedef of a
726 // typedef, make sure to emit the whole chain.
727 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
728 if (!Src.Verify())
729 return llvm::DIType();
730 // We don't set size information, but do specify where the typedef was
731 // declared.
732 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
733 const TypedefNameDecl *TyDecl = Ty->getDecl();
734
735 llvm::DIDescriptor TypedefContext =
736 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
737
738 return
739 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
740}
741
742llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
743 llvm::DIFile Unit) {
744 SmallVector<llvm::Value *, 16> EltTys;
745
746 // Add the result type at least.
747 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
748
749 // Set up remainder of arguments if there is a prototype.
750 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
751 if (isa<FunctionNoProtoType>(Ty))
752 EltTys.push_back(DBuilder.createUnspecifiedParameter());
753 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
754 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
755 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
756 }
757
758 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
759 return DBuilder.createSubroutineType(Unit, EltTypeArray);
760}
761
762
Guy Benyei11169dd2012-12-18 14:30:41 +0000763llvm::DIType CGDebugInfo::createFieldType(StringRef name,
764 QualType type,
765 uint64_t sizeInBitsOverride,
766 SourceLocation loc,
767 AccessSpecifier AS,
768 uint64_t offsetInBits,
769 llvm::DIFile tunit,
770 llvm::DIDescriptor scope) {
771 llvm::DIType debugType = getOrCreateType(type, tunit);
772
773 // Get the location for the field.
774 llvm::DIFile file = getOrCreateFile(loc);
775 unsigned line = getLineNumber(loc);
776
777 uint64_t sizeInBits = 0;
778 unsigned alignInBits = 0;
779 if (!type->isIncompleteArrayType()) {
780 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
781
782 if (sizeInBitsOverride)
783 sizeInBits = sizeInBitsOverride;
784 }
785
786 unsigned flags = 0;
787 if (AS == clang::AS_private)
788 flags |= llvm::DIDescriptor::FlagPrivate;
789 else if (AS == clang::AS_protected)
790 flags |= llvm::DIDescriptor::FlagProtected;
791
792 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
793 alignInBits, offsetInBits, flags, debugType);
794}
795
Eric Christopher91a31902013-01-16 01:22:32 +0000796/// CollectRecordLambdaFields - Helper for CollectRecordFields.
797void CGDebugInfo::
798CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
799 SmallVectorImpl<llvm::Value *> &elements,
800 llvm::DIType RecordTy) {
801 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
802 // has the name and the location of the variable so we should iterate over
803 // both concurrently.
804 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
805 RecordDecl::field_iterator Field = CXXDecl->field_begin();
806 unsigned fieldno = 0;
807 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
808 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
809 const LambdaExpr::Capture C = *I;
810 if (C.capturesVariable()) {
811 VarDecl *V = C.getCapturedVar();
812 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
813 StringRef VName = V->getName();
814 uint64_t SizeInBitsOverride = 0;
815 if (Field->isBitField()) {
816 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
817 assert(SizeInBitsOverride && "found named 0-width bitfield");
818 }
819 llvm::DIType fieldType
820 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
821 C.getLocation(), Field->getAccess(),
822 layout.getFieldOffset(fieldno), VUnit, RecordTy);
823 elements.push_back(fieldType);
824 } else {
825 // TODO: Need to handle 'this' in some way by probably renaming the
826 // this of the lambda class and having a field member of 'this' or
827 // by using AT_object_pointer for the function and having that be
828 // used as 'this' for semantic references.
829 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
830 FieldDecl *f = *Field;
831 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
832 QualType type = f->getType();
833 llvm::DIType fieldType
834 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
835 layout.getFieldOffset(fieldno), VUnit, RecordTy);
836
837 elements.push_back(fieldType);
838 }
839 }
840}
841
842/// CollectRecordStaticField - Helper for CollectRecordFields.
843void CGDebugInfo::
844CollectRecordStaticField(const VarDecl *Var,
845 SmallVectorImpl<llvm::Value *> &elements,
846 llvm::DIType RecordTy) {
847 // Create the descriptor for the static variable, with or without
848 // constant initializers.
849 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
850 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
851
852 // Do not describe enums as static members.
853 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
854 return;
855
856 unsigned LineNumber = getLineNumber(Var->getLocation());
857 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000858 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000859 if (Var->getInit()) {
860 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000861 if (Value) {
862 if (Value->isInt())
863 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
864 if (Value->isFloat())
865 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
866 }
Eric Christopher91a31902013-01-16 01:22:32 +0000867 }
868
869 unsigned Flags = 0;
870 AccessSpecifier Access = Var->getAccess();
871 if (Access == clang::AS_private)
872 Flags |= llvm::DIDescriptor::FlagPrivate;
873 else if (Access == clang::AS_protected)
874 Flags |= llvm::DIDescriptor::FlagProtected;
875
876 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikied42917f2013-01-20 01:19:17 +0000877 LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000878 elements.push_back(GV);
879 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
880}
881
882/// CollectRecordNormalField - Helper for CollectRecordFields.
883void CGDebugInfo::
884CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
885 llvm::DIFile tunit,
886 SmallVectorImpl<llvm::Value *> &elements,
887 llvm::DIType RecordTy) {
888 StringRef name = field->getName();
889 QualType type = field->getType();
890
891 // Ignore unnamed fields unless they're anonymous structs/unions.
892 if (name.empty() && !type->isRecordType())
893 return;
894
895 uint64_t SizeInBitsOverride = 0;
896 if (field->isBitField()) {
897 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
898 assert(SizeInBitsOverride && "found named 0-width bitfield");
899 }
900
901 llvm::DIType fieldType
902 = createFieldType(name, type, SizeInBitsOverride,
903 field->getLocation(), field->getAccess(),
904 OffsetInBits, tunit, RecordTy);
905
906 elements.push_back(fieldType);
907}
908
Guy Benyei11169dd2012-12-18 14:30:41 +0000909/// CollectRecordFields - A helper function to collect debug info for
910/// record fields. This is used while creating debug info entry for a Record.
911void CGDebugInfo::
912CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
913 SmallVectorImpl<llvm::Value *> &elements,
914 llvm::DIType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000915 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
916
Eric Christopher91a31902013-01-16 01:22:32 +0000917 if (CXXDecl && CXXDecl->isLambda())
918 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
919 else {
920 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000921
Eric Christopher91a31902013-01-16 01:22:32 +0000922 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000923 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000924
925 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 bool IsMsStruct = record->isMsStruct(CGM.getContext());
927 const FieldDecl *LastFD = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000928
Eric Christopher91a31902013-01-16 01:22:32 +0000929 // Static and non-static members should appear in the same order as
930 // the corresponding declarations in the source program.
931 for (RecordDecl::decl_iterator I = record->decls_begin(),
932 E = record->decls_end(); I != E; ++I)
933 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
934 CollectRecordStaticField(V, elements, RecordTy);
935 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
936 if (IsMsStruct) {
937 // Zero-length bitfields following non-bitfield members are
938 // completely ignored; we don't even count them.
939 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
940 continue;
941 LastFD = field;
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 }
Eric Christopher91a31902013-01-16 01:22:32 +0000943 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
944 tunit, elements, RecordTy);
945
946 // Bump field number for next field.
947 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 }
950}
951
952/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
953/// function type is not updated to include implicit "this" pointer. Use this
954/// routine to get a method type which includes "this" pointer.
955llvm::DIType
956CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
957 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000958 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000959 if (Method->isStatic())
David Blaikie7eb06852013-01-07 23:06:35 +0000960 return getOrCreateType(QualType(Func, 0), Unit);
961 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
962 Func, Unit);
963}
David Blaikie2aaf0652013-01-07 22:24:59 +0000964
David Blaikie7eb06852013-01-07 23:06:35 +0000965llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
966 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000968 llvm::DIArray Args = llvm::DICompositeType(
969 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 assert (Args.getNumElements() && "Invalid number of arguments!");
971
972 SmallVector<llvm::Value *, 16> Elts;
973
974 // First element is always return type. For 'void' functions it is NULL.
975 Elts.push_back(Args.getElement(0));
976
David Blaikie2aaf0652013-01-07 22:24:59 +0000977 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000978 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000979 if (isa<ClassTemplateSpecializationDecl>(RD)) {
980 // Create pointer type directly in this case.
981 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
982 QualType PointeeTy = ThisPtrTy->getPointeeType();
983 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
984 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
985 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
986 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
987 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
988 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
989 // TODO: This and the artificial type below are misleading, the
990 // types aren't artificial the argument is, but the current
991 // metadata doesn't represent that.
992 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
993 Elts.push_back(ThisPtrType);
994 } else {
995 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
996 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
997 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
998 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +0000999 }
1000
1001 // Copy rest of the arguments.
1002 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1003 Elts.push_back(Args.getElement(i));
1004
1005 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1006
1007 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1008}
1009
1010/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1011/// inside a function.
1012static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1013 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1014 return isFunctionLocalClass(NRD);
1015 if (isa<FunctionDecl>(RD->getDeclContext()))
1016 return true;
1017 return false;
1018}
1019
1020/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1021/// a single member function GlobalDecl.
1022llvm::DISubprogram
1023CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1024 llvm::DIFile Unit,
1025 llvm::DIType RecordTy) {
1026 bool IsCtorOrDtor =
1027 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1028
1029 StringRef MethodName = getFunctionName(Method);
1030 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1031
1032 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1033 // make sense to give a single ctor/dtor a linkage name.
1034 StringRef MethodLinkageName;
1035 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1036 MethodLinkageName = CGM.getMangledName(Method);
1037
1038 // Get the location for the method.
1039 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1040 unsigned MethodLine = getLineNumber(Method->getLocation());
1041
1042 // Collect virtual method info.
1043 llvm::DIType ContainingType;
1044 unsigned Virtuality = 0;
1045 unsigned VIndex = 0;
1046
1047 if (Method->isVirtual()) {
1048 if (Method->isPure())
1049 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1050 else
1051 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1052
1053 // It doesn't make sense to give a virtual destructor a vtable index,
1054 // since a single destructor has two entries in the vtable.
1055 if (!isa<CXXDestructorDecl>(Method))
1056 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1057 ContainingType = RecordTy;
1058 }
1059
1060 unsigned Flags = 0;
1061 if (Method->isImplicit())
1062 Flags |= llvm::DIDescriptor::FlagArtificial;
1063 AccessSpecifier Access = Method->getAccess();
1064 if (Access == clang::AS_private)
1065 Flags |= llvm::DIDescriptor::FlagPrivate;
1066 else if (Access == clang::AS_protected)
1067 Flags |= llvm::DIDescriptor::FlagProtected;
1068 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1069 if (CXXC->isExplicit())
1070 Flags |= llvm::DIDescriptor::FlagExplicit;
1071 } else if (const CXXConversionDecl *CXXC =
1072 dyn_cast<CXXConversionDecl>(Method)) {
1073 if (CXXC->isExplicit())
1074 Flags |= llvm::DIDescriptor::FlagExplicit;
1075 }
1076 if (Method->hasPrototype())
1077 Flags |= llvm::DIDescriptor::FlagPrototyped;
1078
1079 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1080 llvm::DISubprogram SP =
1081 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1082 MethodDefUnit, MethodLine,
1083 MethodTy, /*isLocalToUnit=*/false,
1084 /* isDefinition=*/ false,
1085 Virtuality, VIndex, ContainingType,
1086 Flags, CGM.getLangOpts().Optimize, NULL,
1087 TParamsArray);
1088
1089 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1090
1091 return SP;
1092}
1093
1094/// CollectCXXMemberFunctions - A helper function to collect debug info for
1095/// C++ member functions. This is used while creating debug info entry for
1096/// a Record.
1097void CGDebugInfo::
1098CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1099 SmallVectorImpl<llvm::Value *> &EltTys,
1100 llvm::DIType RecordTy) {
1101
1102 // Since we want more than just the individual member decls if we
1103 // have templated functions iterate over every declaration to gather
1104 // the functions.
1105 for(DeclContext::decl_iterator I = RD->decls_begin(),
1106 E = RD->decls_end(); I != E; ++I) {
1107 Decl *D = *I;
1108 if (D->isImplicit() && !D->isUsed())
1109 continue;
1110
1111 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1112 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1113 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1114 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1115 SE = FTD->spec_end(); SI != SE; ++SI)
1116 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1117 RecordTy));
1118 }
1119}
1120
1121/// CollectCXXFriends - A helper function to collect debug info for
1122/// C++ base classes. This is used while creating debug info entry for
1123/// a Record.
1124void CGDebugInfo::
1125CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1126 SmallVectorImpl<llvm::Value *> &EltTys,
1127 llvm::DIType RecordTy) {
1128 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1129 BE = RD->friend_end(); BI != BE; ++BI) {
1130 if ((*BI)->isUnsupportedFriend())
1131 continue;
1132 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1133 EltTys.push_back(DBuilder.createFriend(RecordTy,
1134 getOrCreateType(TInfo->getType(),
1135 Unit)));
1136 }
1137}
1138
1139/// CollectCXXBases - A helper function to collect debug info for
1140/// C++ base classes. This is used while creating debug info entry for
1141/// a Record.
1142void CGDebugInfo::
1143CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1144 SmallVectorImpl<llvm::Value *> &EltTys,
1145 llvm::DIType RecordTy) {
1146
1147 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1148 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1149 BE = RD->bases_end(); BI != BE; ++BI) {
1150 unsigned BFlags = 0;
1151 uint64_t BaseOffset;
1152
1153 const CXXRecordDecl *Base =
1154 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1155
1156 if (BI->isVirtual()) {
1157 // virtual base offset offset is -ve. The code generator emits dwarf
1158 // expression where it expects +ve number.
1159 BaseOffset =
1160 0 - CGM.getVTableContext()
1161 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1162 BFlags = llvm::DIDescriptor::FlagVirtual;
1163 } else
1164 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1165 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1166 // BI->isVirtual() and bits when not.
1167
1168 AccessSpecifier Access = BI->getAccessSpecifier();
1169 if (Access == clang::AS_private)
1170 BFlags |= llvm::DIDescriptor::FlagPrivate;
1171 else if (Access == clang::AS_protected)
1172 BFlags |= llvm::DIDescriptor::FlagProtected;
1173
1174 llvm::DIType DTy =
1175 DBuilder.createInheritance(RecordTy,
1176 getOrCreateType(BI->getType(), Unit),
1177 BaseOffset, BFlags);
1178 EltTys.push_back(DTy);
1179 }
1180}
1181
1182/// CollectTemplateParams - A helper function to collect template parameters.
1183llvm::DIArray CGDebugInfo::
1184CollectTemplateParams(const TemplateParameterList *TPList,
1185 const TemplateArgumentList &TAList,
1186 llvm::DIFile Unit) {
1187 SmallVector<llvm::Value *, 16> TemplateParams;
1188 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1189 const TemplateArgument &TA = TAList[i];
1190 const NamedDecl *ND = TPList->getParam(i);
1191 if (TA.getKind() == TemplateArgument::Type) {
1192 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1193 llvm::DITemplateTypeParameter TTP =
1194 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1195 TemplateParams.push_back(TTP);
1196 } else if (TA.getKind() == TemplateArgument::Integral) {
1197 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1198 llvm::DITemplateValueParameter TVP =
1199 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1200 TA.getAsIntegral().getZExtValue());
1201 TemplateParams.push_back(TVP);
1202 }
1203 }
1204 return DBuilder.getOrCreateArray(TemplateParams);
1205}
1206
1207/// CollectFunctionTemplateParams - A helper function to collect debug
1208/// info for function template parameters.
1209llvm::DIArray CGDebugInfo::
1210CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1211 if (FD->getTemplatedKind() ==
1212 FunctionDecl::TK_FunctionTemplateSpecialization) {
1213 const TemplateParameterList *TList =
1214 FD->getTemplateSpecializationInfo()->getTemplate()
1215 ->getTemplateParameters();
1216 return
1217 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1218 }
1219 return llvm::DIArray();
1220}
1221
1222/// CollectCXXTemplateParams - A helper function to collect debug info for
1223/// template parameters.
1224llvm::DIArray CGDebugInfo::
1225CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1226 llvm::DIFile Unit) {
1227 llvm::PointerUnion<ClassTemplateDecl *,
1228 ClassTemplatePartialSpecializationDecl *>
1229 PU = TSpecial->getSpecializedTemplateOrPartial();
1230
1231 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1232 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1233 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1234 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1235 return CollectTemplateParams(TPList, TAList, Unit);
1236}
1237
1238/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1239llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1240 if (VTablePtrType.isValid())
1241 return VTablePtrType;
1242
1243 ASTContext &Context = CGM.getContext();
1244
1245 /* Function type */
1246 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1247 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1248 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1249 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1250 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1251 "__vtbl_ptr_type");
1252 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1253 return VTablePtrType;
1254}
1255
1256/// getVTableName - Get vtable name for the given Class.
1257StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1258 // Construct gdb compatible name name.
1259 std::string Name = "_vptr$" + RD->getNameAsString();
1260
1261 // Copy this name on the side and use its reference.
1262 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1263 memcpy(StrPtr, Name.data(), Name.length());
1264 return StringRef(StrPtr, Name.length());
1265}
1266
1267
1268/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1269/// debug info entry in EltTys vector.
1270void CGDebugInfo::
1271CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1272 SmallVectorImpl<llvm::Value *> &EltTys) {
1273 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1274
1275 // If there is a primary base then it will hold vtable info.
1276 if (RL.getPrimaryBase())
1277 return;
1278
1279 // If this class is not dynamic then there is not any vtable info to collect.
1280 if (!RD->isDynamicClass())
1281 return;
1282
1283 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1284 llvm::DIType VPTR
1285 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1286 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1287 getOrCreateVTablePtrType(Unit));
1288 EltTys.push_back(VPTR);
1289}
1290
1291/// getOrCreateRecordType - Emit record type's standalone debug info.
1292llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1293 SourceLocation Loc) {
1294 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1295 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1296 return T;
1297}
1298
1299/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1300/// debug info.
1301llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001302 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1304 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1305 DBuilder.retainType(T);
1306 return T;
1307}
1308
1309/// CreateType - get structure or union type.
1310llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1311 RecordDecl *RD = Ty->getDecl();
1312
1313 // Get overall information about the record type for the debug info.
1314 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1315
1316 // Records and classes and unions can all be recursive. To handle them, we
1317 // first generate a debug descriptor for the struct as a forward declaration.
1318 // Then (if it is a definition) we go through and get debug info for all of
1319 // its members. Finally, we create a descriptor for the complete type (which
1320 // may refer to the forward decl if the struct is recursive) and replace all
1321 // uses of the forward declaration with the final definition.
1322
1323 llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1324
1325 if (FwdDecl.isForwardDecl())
1326 return FwdDecl;
1327
1328 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1329
1330 // Push the struct on region stack.
1331 LexicalBlockStack.push_back(FwdDeclNode);
1332 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1333
1334 // Add this to the completed types cache since we're completing it.
1335 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1336
1337 // Convert all the elements.
1338 SmallVector<llvm::Value *, 16> EltTys;
1339
1340 // Note: The split of CXXDecl information here is intentional, the
1341 // gdb tests will depend on a certain ordering at printout. The debug
1342 // information offsets are still correct if we merge them all together
1343 // though.
1344 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1345 if (CXXDecl) {
1346 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1347 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1348 }
1349
Eric Christopher91a31902013-01-16 01:22:32 +00001350 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1352 llvm::DIArray TParamsArray;
1353 if (CXXDecl) {
1354 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1355 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1356 if (const ClassTemplateSpecializationDecl *TSpecial
1357 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1358 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1359 }
1360
1361 LexicalBlockStack.pop_back();
1362 RegionMap.erase(Ty->getDecl());
1363
1364 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1365 // FIXME: Magic numbers ahoy! These should be changed when we
1366 // get some enums in llvm/Analysis/DebugInfo.h to refer to
1367 // them.
1368 if (RD->isUnion())
1369 FwdDeclNode->replaceOperandWith(10, Elements);
1370 else if (CXXDecl) {
1371 FwdDeclNode->replaceOperandWith(10, Elements);
1372 FwdDeclNode->replaceOperandWith(13, TParamsArray);
1373 } else
1374 FwdDeclNode->replaceOperandWith(10, Elements);
1375
1376 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1377 return llvm::DIType(FwdDeclNode);
1378}
1379
1380/// CreateType - get objective-c object type.
1381llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1382 llvm::DIFile Unit) {
1383 // Ignore protocols.
1384 return getOrCreateType(Ty->getBaseType(), Unit);
1385}
1386
1387/// CreateType - get objective-c interface type.
1388llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1389 llvm::DIFile Unit) {
1390 ObjCInterfaceDecl *ID = Ty->getDecl();
1391 if (!ID)
1392 return llvm::DIType();
1393
1394 // Get overall information about the record type for the debug info.
1395 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1396 unsigned Line = getLineNumber(ID->getLocation());
1397 unsigned RuntimeLang = TheCU.getLanguage();
1398
1399 // If this is just a forward declaration return a special forward-declaration
1400 // debug type since we won't be able to lay out the entire type.
1401 ObjCInterfaceDecl *Def = ID->getDefinition();
1402 if (!Def) {
1403 llvm::DIType FwdDecl =
1404 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001405 ID->getName(), TheCU, DefUnit, Line,
1406 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 return FwdDecl;
1408 }
1409
1410 ID = Def;
1411
1412 // Bit size, align and offset of the type.
1413 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1414 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1415
1416 unsigned Flags = 0;
1417 if (ID->getImplementation())
1418 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1419
1420 llvm::DIType RealDecl =
1421 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1422 Line, Size, Align, Flags,
1423 llvm::DIArray(), RuntimeLang);
1424
1425 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1426 // will find it and we're emitting the complete type.
1427 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1428 // Push the struct on region stack.
1429 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1430
1431 LexicalBlockStack.push_back(FwdDeclNode);
1432 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1433
1434 // Convert all the elements.
1435 SmallVector<llvm::Value *, 16> EltTys;
1436
1437 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1438 if (SClass) {
1439 llvm::DIType SClassTy =
1440 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1441 if (!SClassTy.isValid())
1442 return llvm::DIType();
1443
1444 llvm::DIType InhTag =
1445 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1446 EltTys.push_back(InhTag);
1447 }
1448
1449 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1450 E = ID->prop_end(); I != E; ++I) {
1451 const ObjCPropertyDecl *PD = *I;
1452 SourceLocation Loc = PD->getLocation();
1453 llvm::DIFile PUnit = getOrCreateFile(Loc);
1454 unsigned PLine = getLineNumber(Loc);
1455 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1456 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1457 llvm::MDNode *PropertyNode =
1458 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001459 PUnit, PLine,
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 (Getter && Getter->isImplicit()) ? "" :
1461 getSelectorName(PD->getGetterName()),
1462 (Setter && Setter->isImplicit()) ? "" :
1463 getSelectorName(PD->getSetterName()),
1464 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001465 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 EltTys.push_back(PropertyNode);
1467 }
1468
1469 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1470 unsigned FieldNo = 0;
1471 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1472 Field = Field->getNextIvar(), ++FieldNo) {
1473 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1474 if (!FieldTy.isValid())
1475 return llvm::DIType();
1476
1477 StringRef FieldName = Field->getName();
1478
1479 // Ignore unnamed fields.
1480 if (FieldName.empty())
1481 continue;
1482
1483 // Get the location for the field.
1484 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1485 unsigned FieldLine = getLineNumber(Field->getLocation());
1486 QualType FType = Field->getType();
1487 uint64_t FieldSize = 0;
1488 unsigned FieldAlign = 0;
1489
1490 if (!FType->isIncompleteArrayType()) {
1491
1492 // Bit size, align and offset of the type.
1493 FieldSize = Field->isBitField()
1494 ? Field->getBitWidthValue(CGM.getContext())
1495 : CGM.getContext().getTypeSize(FType);
1496 FieldAlign = CGM.getContext().getTypeAlign(FType);
1497 }
1498
1499 uint64_t FieldOffset;
1500 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1501 // We don't know the runtime offset of an ivar if we're using the
1502 // non-fragile ABI. For bitfields, use the bit offset into the first
1503 // byte of storage of the bitfield. For other fields, use zero.
1504 if (Field->isBitField()) {
1505 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1506 CGM, ID, Field);
1507 FieldOffset %= CGM.getContext().getCharWidth();
1508 } else {
1509 FieldOffset = 0;
1510 }
1511 } else {
1512 FieldOffset = RL.getFieldOffset(FieldNo);
1513 }
1514
1515 unsigned Flags = 0;
1516 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1517 Flags = llvm::DIDescriptor::FlagProtected;
1518 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1519 Flags = llvm::DIDescriptor::FlagPrivate;
1520
1521 llvm::MDNode *PropertyNode = NULL;
1522 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1523 if (ObjCPropertyImplDecl *PImpD =
1524 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1525 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001526 SourceLocation Loc = PD->getLocation();
1527 llvm::DIFile PUnit = getOrCreateFile(Loc);
1528 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1530 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1531 PropertyNode =
1532 DBuilder.createObjCProperty(PD->getName(),
1533 PUnit, PLine,
1534 (Getter && Getter->isImplicit()) ? "" :
1535 getSelectorName(PD->getGetterName()),
1536 (Setter && Setter->isImplicit()) ? "" :
1537 getSelectorName(PD->getSetterName()),
1538 PD->getPropertyAttributes(),
1539 getOrCreateType(PD->getType(), PUnit));
1540 }
1541 }
1542 }
1543 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1544 FieldLine, FieldSize, FieldAlign,
1545 FieldOffset, Flags, FieldTy,
1546 PropertyNode);
1547 EltTys.push_back(FieldTy);
1548 }
1549
1550 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1551 FwdDeclNode->replaceOperandWith(10, Elements);
1552
1553 LexicalBlockStack.pop_back();
1554 return llvm::DIType(FwdDeclNode);
1555}
1556
1557llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1558 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1559 int64_t Count = Ty->getNumElements();
1560 if (Count == 0)
1561 // If number of elements are not known then this is an unbounded array.
1562 // Use Count == -1 to express such arrays.
1563 Count = -1;
1564
1565 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1566 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1567
1568 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1569 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1570
1571 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1572}
1573
1574llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1575 llvm::DIFile Unit) {
1576 uint64_t Size;
1577 uint64_t Align;
1578
1579 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1580 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1581 Size = 0;
1582 Align =
1583 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1584 } else if (Ty->isIncompleteArrayType()) {
1585 Size = 0;
1586 if (Ty->getElementType()->isIncompleteType())
1587 Align = 0;
1588 else
1589 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1590 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1591 Size = 0;
1592 Align = 0;
1593 } else {
1594 // Size and align of the whole array, not the element type.
1595 Size = CGM.getContext().getTypeSize(Ty);
1596 Align = CGM.getContext().getTypeAlign(Ty);
1597 }
1598
1599 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1600 // interior arrays, do we care? Why aren't nested arrays represented the
1601 // obvious/recursive way?
1602 SmallVector<llvm::Value *, 8> Subscripts;
1603 QualType EltTy(Ty, 0);
1604 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1605 // If the number of elements is known, then count is that number. Otherwise,
1606 // it's -1. This allows us to represent a subrange with an array of 0
1607 // elements, like this:
1608 //
1609 // struct foo {
1610 // int x[0];
1611 // };
1612 int64_t Count = -1; // Count == -1 is an unbounded array.
1613 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1614 Count = CAT->getSize().getZExtValue();
1615
1616 // FIXME: Verify this is right for VLAs.
1617 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1618 EltTy = Ty->getElementType();
1619 }
1620
1621 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1622
1623 llvm::DIType DbgTy =
1624 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1625 SubscriptArray);
1626 return DbgTy;
1627}
1628
1629llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1630 llvm::DIFile Unit) {
1631 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1632 Ty, Ty->getPointeeType(), Unit);
1633}
1634
1635llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1636 llvm::DIFile Unit) {
1637 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1638 Ty, Ty->getPointeeType(), Unit);
1639}
1640
1641llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1642 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001643 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1644 if (!Ty->getPointeeType()->isFunctionType())
1645 return DBuilder.createMemberPointerType(
1646 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1647 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1648 CGM.getContext().getPointerType(
1649 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1650 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1651 ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001652}
1653
1654llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1655 llvm::DIFile U) {
1656 // Ignore the atomic wrapping
1657 // FIXME: What is the correct representation?
1658 return getOrCreateType(Ty->getValueType(), U);
1659}
1660
1661/// CreateEnumType - get enumeration type.
1662llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1663 uint64_t Size = 0;
1664 uint64_t Align = 0;
1665 if (!ED->getTypeForDecl()->isIncompleteType()) {
1666 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1667 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1668 }
1669
1670 // If this is just a forward declaration, construct an appropriately
1671 // marked node and just return it.
1672 if (!ED->getDefinition()) {
1673 llvm::DIDescriptor EDContext;
1674 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1675 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1676 unsigned Line = getLineNumber(ED->getLocation());
1677 StringRef EDName = ED->getName();
1678 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1679 EDName, EDContext, DefUnit, Line, 0,
1680 Size, Align);
1681 }
1682
1683 // Create DIEnumerator elements for each enumerator.
1684 SmallVector<llvm::Value *, 16> Enumerators;
1685 ED = ED->getDefinition();
1686 for (EnumDecl::enumerator_iterator
1687 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1688 Enum != EnumEnd; ++Enum) {
1689 Enumerators.push_back(
1690 DBuilder.createEnumerator(Enum->getName(),
1691 Enum->getInitVal().getZExtValue()));
1692 }
1693
1694 // Return a CompositeType for the enum itself.
1695 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1696
1697 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1698 unsigned Line = getLineNumber(ED->getLocation());
1699 llvm::DIDescriptor EnumContext =
1700 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1701 llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1702 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1703 llvm::DIType DbgTy =
1704 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1705 Size, Align, EltArray,
1706 ClassTy);
1707 return DbgTy;
1708}
1709
David Blaikie05491062013-01-21 04:37:12 +00001710static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1711 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 do {
David Blaikie05491062013-01-21 04:37:12 +00001713 Quals += T.getLocalQualifiers();
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 QualType LastT = T;
1715 switch (T->getTypeClass()) {
1716 default:
David Blaikie05491062013-01-21 04:37:12 +00001717 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 case Type::TemplateSpecialization:
1719 T = cast<TemplateSpecializationType>(T)->desugar();
1720 break;
1721 case Type::TypeOfExpr:
1722 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1723 break;
1724 case Type::TypeOf:
1725 T = cast<TypeOfType>(T)->getUnderlyingType();
1726 break;
1727 case Type::Decltype:
1728 T = cast<DecltypeType>(T)->getUnderlyingType();
1729 break;
1730 case Type::UnaryTransform:
1731 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1732 break;
1733 case Type::Attributed:
1734 T = cast<AttributedType>(T)->getEquivalentType();
1735 break;
1736 case Type::Elaborated:
1737 T = cast<ElaboratedType>(T)->getNamedType();
1738 break;
1739 case Type::Paren:
1740 T = cast<ParenType>(T)->getInnerType();
1741 break;
David Blaikie05491062013-01-21 04:37:12 +00001742 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 break;
1745 case Type::Auto:
1746 T = cast<AutoType>(T)->getDeducedType();
1747 break;
1748 }
1749
1750 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001751 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 } while (true);
1753}
1754
1755/// getType - Get the type from the cache or return null type if it doesn't exist.
1756llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1757
1758 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001759 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001760
1761 // Check for existing entry.
1762 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1763 TypeCache.find(Ty.getAsOpaquePtr());
1764 if (it != TypeCache.end()) {
1765 // Verify that the debug info still exists.
1766 if (llvm::Value *V = it->second)
1767 return llvm::DIType(cast<llvm::MDNode>(V));
1768 }
1769
1770 return llvm::DIType();
1771}
1772
1773/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1774/// doesn't exist.
1775llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1776
1777 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001778 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001779
1780 // Check for existing entry.
1781 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1782 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1783 if (it != CompletedTypeCache.end()) {
1784 // Verify that the debug info still exists.
1785 if (llvm::Value *V = it->second)
1786 return llvm::DIType(cast<llvm::MDNode>(V));
1787 }
1788
1789 return llvm::DIType();
1790}
1791
1792
1793/// getOrCreateType - Get the type from the cache or create a new
1794/// one if necessary.
1795llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1796 if (Ty.isNull())
1797 return llvm::DIType();
1798
1799 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001800 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001801
1802 llvm::DIType T = getCompletedTypeOrNull(Ty);
1803
1804 if (T.Verify())
1805 return T;
1806
1807 // Otherwise create the type.
1808 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1809
1810 llvm::DIType TC = getTypeOrNull(Ty);
1811 if (TC.Verify() && TC.isForwardDecl())
1812 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1813 static_cast<llvm::Value*>(TC)));
1814
1815 // And update the type cache.
1816 TypeCache[Ty.getAsOpaquePtr()] = Res;
1817
1818 if (!Res.isForwardDecl())
1819 CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1820
1821 return Res;
1822}
1823
1824/// CreateTypeNode - Create a new debug type node.
1825llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1826 // Handle qualifiers, which recursively handles what they refer to.
1827 if (Ty.hasLocalQualifiers())
1828 return CreateQualifiedType(Ty, Unit);
1829
1830 const char *Diag = 0;
1831
1832 // Work out details of type.
1833 switch (Ty->getTypeClass()) {
1834#define TYPE(Class, Base)
1835#define ABSTRACT_TYPE(Class, Base)
1836#define NON_CANONICAL_TYPE(Class, Base)
1837#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1838#include "clang/AST/TypeNodes.def"
1839 llvm_unreachable("Dependent types cannot show up in debug information");
1840
1841 case Type::ExtVector:
1842 case Type::Vector:
1843 return CreateType(cast<VectorType>(Ty), Unit);
1844 case Type::ObjCObjectPointer:
1845 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1846 case Type::ObjCObject:
1847 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1848 case Type::ObjCInterface:
1849 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1850 case Type::Builtin:
1851 return CreateType(cast<BuiltinType>(Ty));
1852 case Type::Complex:
1853 return CreateType(cast<ComplexType>(Ty));
1854 case Type::Pointer:
1855 return CreateType(cast<PointerType>(Ty), Unit);
1856 case Type::BlockPointer:
1857 return CreateType(cast<BlockPointerType>(Ty), Unit);
1858 case Type::Typedef:
1859 return CreateType(cast<TypedefType>(Ty), Unit);
1860 case Type::Record:
1861 return CreateType(cast<RecordType>(Ty));
1862 case Type::Enum:
1863 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1864 case Type::FunctionProto:
1865 case Type::FunctionNoProto:
1866 return CreateType(cast<FunctionType>(Ty), Unit);
1867 case Type::ConstantArray:
1868 case Type::VariableArray:
1869 case Type::IncompleteArray:
1870 return CreateType(cast<ArrayType>(Ty), Unit);
1871
1872 case Type::LValueReference:
1873 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1874 case Type::RValueReference:
1875 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1876
1877 case Type::MemberPointer:
1878 return CreateType(cast<MemberPointerType>(Ty), Unit);
1879
1880 case Type::Atomic:
1881 return CreateType(cast<AtomicType>(Ty), Unit);
1882
1883 case Type::Attributed:
1884 case Type::TemplateSpecialization:
1885 case Type::Elaborated:
1886 case Type::Paren:
1887 case Type::SubstTemplateTypeParm:
1888 case Type::TypeOfExpr:
1889 case Type::TypeOf:
1890 case Type::Decltype:
1891 case Type::UnaryTransform:
1892 case Type::Auto:
1893 llvm_unreachable("type should have been unwrapped!");
1894 }
1895
1896 assert(Diag && "Fall through without a diagnostic?");
1897 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1898 "debug information for %0 is not yet supported");
1899 CGM.getDiags().Report(DiagID)
1900 << Diag;
1901 return llvm::DIType();
1902}
1903
1904/// getOrCreateLimitedType - Get the type from the cache or create a new
1905/// limited type if necessary.
1906llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001907 llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 if (Ty.isNull())
1909 return llvm::DIType();
1910
1911 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001912 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001913
1914 llvm::DIType T = getTypeOrNull(Ty);
1915
1916 // We may have cached a forward decl when we could have created
1917 // a non-forward decl. Go ahead and create a non-forward decl
1918 // now.
1919 if (T.Verify() && !T.isForwardDecl()) return T;
1920
1921 // Otherwise create the type.
1922 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1923
1924 if (T.Verify() && T.isForwardDecl())
1925 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1926 static_cast<llvm::Value*>(T)));
1927
1928 // And update the type cache.
1929 TypeCache[Ty.getAsOpaquePtr()] = Res;
1930 return Res;
1931}
1932
1933// TODO: Currently used for context chains when limiting debug info.
1934llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1935 RecordDecl *RD = Ty->getDecl();
1936
1937 // Get overall information about the record type for the debug info.
1938 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1939 unsigned Line = getLineNumber(RD->getLocation());
1940 StringRef RDName = getClassName(RD);
1941
1942 llvm::DIDescriptor RDContext;
1943 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
1944 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1945 else
1946 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1947
1948 // If this is just a forward declaration, construct an appropriately
1949 // marked node and just return it.
1950 if (!RD->getDefinition())
1951 return createRecordFwdDecl(RD, RDContext);
1952
1953 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1954 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1955 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1956 llvm::TrackingVH<llvm::MDNode> RealDecl;
1957
1958 if (RD->isUnion())
1959 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001960 Size, Align, 0, llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 else if (RD->isClass()) {
1962 // FIXME: This could be a struct type giving a default visibility different
1963 // than C++ class type, but needs llvm metadata changes first.
1964 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001965 Size, Align, 0, 0, llvm::DIType(),
1966 llvm::DIArray(), llvm::DIType(),
1967 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00001968 } else
1969 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001970 Size, Align, 0, llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00001971
1972 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1973 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1974
1975 if (CXXDecl) {
1976 // A class's primary base or the class itself contains the vtable.
1977 llvm::MDNode *ContainingType = NULL;
1978 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1979 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1980 // Seek non virtual primary base root.
1981 while (1) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001982 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1983 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1984 if (PBT && !BRL.isPrimaryBaseVirtual())
1985 PBase = PBT;
1986 else
1987 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001988 }
1989 ContainingType =
Eric Christopherc0c5d462013-02-21 22:35:08 +00001990 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001991 }
1992 else if (CXXDecl->isDynamicClass())
1993 ContainingType = RealDecl;
1994
1995 RealDecl->replaceOperandWith(12, ContainingType);
1996 }
1997 return llvm::DIType(RealDecl);
1998}
1999
2000/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2001/// declare composite types that haven't been processed yet.
2002llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2003
2004 // Work out details of type.
2005 switch (Ty->getTypeClass()) {
2006#define TYPE(Class, Base)
2007#define ABSTRACT_TYPE(Class, Base)
2008#define NON_CANONICAL_TYPE(Class, Base)
2009#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2010 #include "clang/AST/TypeNodes.def"
2011 llvm_unreachable("Dependent types cannot show up in debug information");
2012
2013 case Type::Record:
2014 return CreateLimitedType(cast<RecordType>(Ty));
2015 default:
2016 return CreateTypeNode(Ty, Unit);
2017 }
2018}
2019
2020/// CreateMemberType - Create new member and increase Offset by FType's size.
2021llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2022 StringRef Name,
2023 uint64_t *Offset) {
2024 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2025 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2026 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2027 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2028 FieldSize, FieldAlign,
2029 *Offset, 0, FieldTy);
2030 *Offset += FieldSize;
2031 return Ty;
2032}
2033
2034/// getFunctionDeclaration - Return debug info descriptor to describe method
2035/// declaration for the given method definition.
2036llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2037 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2038 if (!FD) return llvm::DISubprogram();
2039
2040 // Setup context.
2041 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2042
2043 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2044 MI = SPCache.find(FD->getCanonicalDecl());
2045 if (MI != SPCache.end()) {
2046 llvm::Value *V = MI->second;
2047 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2048 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2049 return SP;
2050 }
2051
2052 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2053 E = FD->redecls_end(); I != E; ++I) {
2054 const FunctionDecl *NextFD = *I;
2055 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2056 MI = SPCache.find(NextFD->getCanonicalDecl());
2057 if (MI != SPCache.end()) {
2058 llvm::Value *V = MI->second;
2059 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2060 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2061 return SP;
2062 }
2063 }
2064 return llvm::DISubprogram();
2065}
2066
2067// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2068// implicit parameter "this".
2069llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2070 QualType FnType,
2071 llvm::DIFile F) {
2072
2073 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2074 return getOrCreateMethodType(Method, F);
2075 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2076 // Add "self" and "_cmd"
2077 SmallVector<llvm::Value *, 16> Elts;
2078
2079 // First element is always return type. For 'void' functions it is NULL.
2080 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2081 // "self" pointer is always first argument.
2082 llvm::DIType SelfTy = getOrCreateType(OMethod->getSelfDecl()->getType(), F);
2083 Elts.push_back(DBuilder.createObjectPointerType(SelfTy));
2084 // "_cmd" pointer is always second argument.
2085 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2086 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2087 // Get rest of the arguments.
2088 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2089 PE = OMethod->param_end(); PI != PE; ++PI)
2090 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2091
2092 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2093 return DBuilder.createSubroutineType(F, EltTypeArray);
2094 }
2095 return getOrCreateType(FnType, F);
2096}
2097
2098/// EmitFunctionStart - Constructs the debug code for entering a function.
2099void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2100 llvm::Function *Fn,
2101 CGBuilderTy &Builder) {
2102
2103 StringRef Name;
2104 StringRef LinkageName;
2105
2106 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2107
2108 const Decl *D = GD.getDecl();
2109 // Function may lack declaration in source code if it is created by Clang
2110 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2111 bool HasDecl = (D != 0);
2112 // Use the location of the declaration.
2113 SourceLocation Loc;
2114 if (HasDecl)
2115 Loc = D->getLocation();
2116
2117 unsigned Flags = 0;
2118 llvm::DIFile Unit = getOrCreateFile(Loc);
2119 llvm::DIDescriptor FDContext(Unit);
2120 llvm::DIArray TParamsArray;
2121 if (!HasDecl) {
2122 // Use llvm function name.
2123 Name = Fn->getName();
2124 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2125 // If there is a DISubprogram for this function available then use it.
2126 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2127 FI = SPCache.find(FD->getCanonicalDecl());
2128 if (FI != SPCache.end()) {
2129 llvm::Value *V = FI->second;
2130 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2131 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2132 llvm::MDNode *SPN = SP;
2133 LexicalBlockStack.push_back(SPN);
2134 RegionMap[D] = llvm::WeakVH(SP);
2135 return;
2136 }
2137 }
2138 Name = getFunctionName(FD);
2139 // Use mangled name as linkage name for c/c++ functions.
2140 if (FD->hasPrototype()) {
2141 LinkageName = CGM.getMangledName(GD);
2142 Flags |= llvm::DIDescriptor::FlagPrototyped;
2143 }
2144 if (LinkageName == Name ||
2145 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly)
2146 LinkageName = StringRef();
2147
2148 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2149 if (const NamespaceDecl *NSDecl =
2150 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2151 FDContext = getOrCreateNameSpace(NSDecl);
2152 else if (const RecordDecl *RDecl =
2153 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2154 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2155
2156 // Collect template parameters.
2157 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2158 }
2159 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2160 Name = getObjCMethodName(OMD);
2161 Flags |= llvm::DIDescriptor::FlagPrototyped;
2162 } else {
2163 // Use llvm function name.
2164 Name = Fn->getName();
2165 Flags |= llvm::DIDescriptor::FlagPrototyped;
2166 }
2167 if (!Name.empty() && Name[0] == '\01')
2168 Name = Name.substr(1);
2169
2170 unsigned LineNo = getLineNumber(Loc);
2171 if (!HasDecl || D->isImplicit())
2172 Flags |= llvm::DIDescriptor::FlagArtificial;
2173
2174 llvm::DIType DIFnType;
2175 llvm::DISubprogram SPDecl;
2176 if (HasDecl &&
2177 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2178 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2179 SPDecl = getFunctionDeclaration(D);
2180 } else {
2181 // Create fake but valid subroutine type. Otherwise
2182 // llvm::DISubprogram::Verify() would return false, and
2183 // subprogram DIE will miss DW_AT_decl_file and
2184 // DW_AT_decl_line fields.
2185 SmallVector<llvm::Value*, 16> Elts;
2186 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2187 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2188 }
2189 llvm::DISubprogram SP;
2190 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2191 LineNo, DIFnType,
2192 Fn->hasInternalLinkage(), true/*definition*/,
2193 getLineNumber(CurLoc), Flags,
2194 CGM.getLangOpts().Optimize,
2195 Fn, TParamsArray, SPDecl);
2196
2197 // Push function on region stack.
2198 llvm::MDNode *SPN = SP;
2199 LexicalBlockStack.push_back(SPN);
2200 if (HasDecl)
2201 RegionMap[D] = llvm::WeakVH(SP);
2202}
2203
2204/// EmitLocation - Emit metadata to indicate a change in line/column
2205/// information in the source file.
2206void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2207
2208 // Update our current location
2209 setLocation(Loc);
2210
2211 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2212
2213 // Don't bother if things are the same as last time.
2214 SourceManager &SM = CGM.getContext().getSourceManager();
2215 if (CurLoc == PrevLoc ||
2216 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2217 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002218 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2219 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2220 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 return;
2222
2223 // Update last state.
2224 PrevLoc = CurLoc;
2225
2226 llvm::MDNode *Scope = LexicalBlockStack.back();
2227 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2228 getColumnNumber(CurLoc),
2229 Scope));
2230}
2231
2232/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2233/// the stack.
2234void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2235 llvm::DIDescriptor D =
2236 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2237 llvm::DIDescriptor() :
2238 llvm::DIDescriptor(LexicalBlockStack.back()),
2239 getOrCreateFile(CurLoc),
2240 getLineNumber(CurLoc),
2241 getColumnNumber(CurLoc));
2242 llvm::MDNode *DN = D;
2243 LexicalBlockStack.push_back(DN);
2244}
2245
2246/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2247/// region - beginning of a DW_TAG_lexical_block.
2248void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2249 // Set our current location.
2250 setLocation(Loc);
2251
2252 // Create a new lexical block and push it on the stack.
2253 CreateLexicalBlock(Loc);
2254
2255 // Emit a line table change for the current location inside the new scope.
2256 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2257 getColumnNumber(Loc),
2258 LexicalBlockStack.back()));
2259}
2260
2261/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2262/// region - end of a DW_TAG_lexical_block.
2263void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2264 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2265
2266 // Provide an entry in the line table for the end of the block.
2267 EmitLocation(Builder, Loc);
2268
2269 LexicalBlockStack.pop_back();
2270}
2271
2272/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2273void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2274 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2275 unsigned RCount = FnBeginRegionCount.back();
2276 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2277
2278 // Pop all regions for this function.
2279 while (LexicalBlockStack.size() != RCount)
2280 EmitLexicalBlockEnd(Builder, CurLoc);
2281 FnBeginRegionCount.pop_back();
2282}
2283
2284// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2285// See BuildByRefType.
2286llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2287 uint64_t *XOffset) {
2288
2289 SmallVector<llvm::Value *, 5> EltTys;
2290 QualType FType;
2291 uint64_t FieldSize, FieldOffset;
2292 unsigned FieldAlign;
2293
2294 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2295 QualType Type = VD->getType();
2296
2297 FieldOffset = 0;
2298 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2299 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2300 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2301 FType = CGM.getContext().IntTy;
2302 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2303 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2304
2305 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2306 if (HasCopyAndDispose) {
2307 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2308 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2309 &FieldOffset));
2310 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2311 &FieldOffset));
2312 }
2313 bool HasByrefExtendedLayout;
2314 Qualifiers::ObjCLifetime Lifetime;
2315 if (CGM.getContext().getByrefLifetime(Type,
2316 Lifetime, HasByrefExtendedLayout)
2317 && HasByrefExtendedLayout)
2318 EltTys.push_back(CreateMemberType(Unit, FType,
2319 "__byref_variable_layout",
2320 &FieldOffset));
2321
2322 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2323 if (Align > CGM.getContext().toCharUnitsFromBits(
2324 CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2325 CharUnits FieldOffsetInBytes
2326 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2327 CharUnits AlignedOffsetInBytes
2328 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2329 CharUnits NumPaddingBytes
2330 = AlignedOffsetInBytes - FieldOffsetInBytes;
2331
2332 if (NumPaddingBytes.isPositive()) {
2333 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2334 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2335 pad, ArrayType::Normal, 0);
2336 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2337 }
2338 }
2339
2340 FType = Type;
2341 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2342 FieldSize = CGM.getContext().getTypeSize(FType);
2343 FieldAlign = CGM.getContext().toBits(Align);
2344
2345 *XOffset = FieldOffset;
2346 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2347 0, FieldSize, FieldAlign,
2348 FieldOffset, 0, FieldTy);
2349 EltTys.push_back(FieldTy);
2350 FieldOffset += FieldSize;
2351
2352 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2353
2354 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2355
2356 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2357 Elements);
2358}
2359
2360/// EmitDeclare - Emit local variable declaration debug info.
2361void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2362 llvm::Value *Storage,
2363 unsigned ArgNo, CGBuilderTy &Builder) {
2364 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2365 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2366
2367 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2368 llvm::DIType Ty;
2369 uint64_t XOffset = 0;
2370 if (VD->hasAttr<BlocksAttr>())
2371 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2372 else
2373 Ty = getOrCreateType(VD->getType(), Unit);
2374
2375 // If there is no debug info for this type then do not emit debug info
2376 // for this variable.
2377 if (!Ty)
2378 return;
2379
2380 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2381 // If Storage is an aggregate returned as 'sret' then let debugger know
2382 // about this.
2383 if (Arg->hasStructRetAttr())
2384 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2385 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2386 // If an aggregate variable has non trivial destructor or non trivial copy
2387 // constructor than it is pass indirectly. Let debug info know about this
2388 // by using reference of the aggregate type as a argument type.
2389 if (Record->hasNonTrivialCopyConstructor() ||
2390 !Record->hasTrivialDestructor())
2391 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2392 }
2393 }
2394
2395 // Get location information.
2396 unsigned Line = getLineNumber(VD->getLocation());
2397 unsigned Column = getColumnNumber(VD->getLocation());
2398 unsigned Flags = 0;
2399 if (VD->isImplicit())
2400 Flags |= llvm::DIDescriptor::FlagArtificial;
2401 // If this is the first argument and it is implicit then
2402 // give it an object pointer flag.
2403 // FIXME: There has to be a better way to do this, but for static
2404 // functions there won't be an implicit param at arg1 and
2405 // otherwise it is 'self' or 'this'.
2406 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2407 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2408
2409 llvm::MDNode *Scope = LexicalBlockStack.back();
2410
2411 StringRef Name = VD->getName();
2412 if (!Name.empty()) {
2413 if (VD->hasAttr<BlocksAttr>()) {
2414 CharUnits offset = CharUnits::fromQuantity(32);
2415 SmallVector<llvm::Value *, 9> addr;
2416 llvm::Type *Int64Ty = CGM.Int64Ty;
2417 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2418 // offset of __forwarding field
2419 offset = CGM.getContext().toCharUnitsFromBits(
2420 CGM.getContext().getTargetInfo().getPointerWidth(0));
2421 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2422 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2423 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2424 // offset of x field
2425 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2426 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2427
2428 // Create the descriptor for the variable.
2429 llvm::DIVariable D =
2430 DBuilder.createComplexVariable(Tag,
2431 llvm::DIDescriptor(Scope),
2432 VD->getName(), Unit, Line, Ty,
2433 addr, ArgNo);
2434
2435 // Insert an llvm.dbg.declare into the current block.
2436 llvm::Instruction *Call =
2437 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2438 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2439 return;
2440 } else if (isa<VariableArrayType>(VD->getType())) {
2441 // These are "complex" variables in that they need an op_deref.
2442 // Create the descriptor for the variable.
2443 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2444 llvm::DIBuilder::OpDeref);
2445 llvm::DIVariable D =
2446 DBuilder.createComplexVariable(Tag,
2447 llvm::DIDescriptor(Scope),
2448 Name, Unit, Line, Ty,
2449 Addr, ArgNo);
2450
2451 // Insert an llvm.dbg.declare into the current block.
2452 llvm::Instruction *Call =
2453 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2454 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2455 return;
2456 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002457 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2458 // If VD is an anonymous union then Storage represents value for
2459 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002461 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 for (RecordDecl::field_iterator I = RD->field_begin(),
2463 E = RD->field_end();
2464 I != E; ++I) {
2465 FieldDecl *Field = *I;
2466 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2467 StringRef FieldName = Field->getName();
2468
2469 // Ignore unnamed fields. Do not ignore unnamed records.
2470 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2471 continue;
2472
2473 // Use VarDecl's Tag, Scope and Line number.
2474 llvm::DIVariable D =
2475 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2476 FieldName, Unit, Line, FieldTy,
2477 CGM.getLangOpts().Optimize, Flags,
2478 ArgNo);
2479
2480 // Insert an llvm.dbg.declare into the current block.
2481 llvm::Instruction *Call =
2482 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2483 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2484 }
David Blaikie219c7d92013-01-05 20:03:07 +00002485 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 }
2487 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002488
2489 // Create the descriptor for the variable.
2490 llvm::DIVariable D =
2491 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2492 Name, Unit, Line, Ty,
2493 CGM.getLangOpts().Optimize, Flags, ArgNo);
2494
2495 // Insert an llvm.dbg.declare into the current block.
2496 llvm::Instruction *Call =
2497 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2498 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002499}
2500
2501void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2502 llvm::Value *Storage,
2503 CGBuilderTy &Builder) {
2504 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2505 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2506}
2507
2508void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2509 llvm::Value *Storage,
2510 CGBuilderTy &Builder,
2511 const CGBlockInfo &blockInfo) {
2512 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2513 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2514
2515 if (Builder.GetInsertBlock() == 0)
2516 return;
2517
2518 bool isByRef = VD->hasAttr<BlocksAttr>();
2519
2520 uint64_t XOffset = 0;
2521 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2522 llvm::DIType Ty;
2523 if (isByRef)
2524 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2525 else
2526 Ty = getOrCreateType(VD->getType(), Unit);
2527
2528 // Self is passed along as an implicit non-arg variable in a
2529 // block. Mark it as the object pointer.
2530 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2531 Ty = DBuilder.createObjectPointerType(Ty);
2532
2533 // Get location information.
2534 unsigned Line = getLineNumber(VD->getLocation());
2535 unsigned Column = getColumnNumber(VD->getLocation());
2536
2537 const llvm::DataLayout &target = CGM.getDataLayout();
2538
2539 CharUnits offset = CharUnits::fromQuantity(
2540 target.getStructLayout(blockInfo.StructureType)
2541 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2542
2543 SmallVector<llvm::Value *, 9> addr;
2544 llvm::Type *Int64Ty = CGM.Int64Ty;
2545 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2546 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2547 if (isByRef) {
2548 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2549 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2550 // offset of __forwarding field
2551 offset = CGM.getContext()
2552 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2553 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2554 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2555 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2556 // offset of x field
2557 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2558 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2559 }
2560
2561 // Create the descriptor for the variable.
2562 llvm::DIVariable D =
2563 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2564 llvm::DIDescriptor(LexicalBlockStack.back()),
2565 VD->getName(), Unit, Line, Ty, addr);
2566 // Insert an llvm.dbg.declare into the current block.
2567 llvm::Instruction *Call =
2568 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2569 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2570 LexicalBlockStack.back()));
2571}
2572
2573/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2574/// variable declaration.
2575void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2576 unsigned ArgNo,
2577 CGBuilderTy &Builder) {
2578 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2579 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2580}
2581
2582namespace {
2583 struct BlockLayoutChunk {
2584 uint64_t OffsetInBits;
2585 const BlockDecl::Capture *Capture;
2586 };
2587 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2588 return l.OffsetInBits < r.OffsetInBits;
2589 }
2590}
2591
2592void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2593 llvm::Value *addr,
2594 CGBuilderTy &Builder) {
2595 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2596 ASTContext &C = CGM.getContext();
2597 const BlockDecl *blockDecl = block.getBlockDecl();
2598
2599 // Collect some general information about the block's location.
2600 SourceLocation loc = blockDecl->getCaretLocation();
2601 llvm::DIFile tunit = getOrCreateFile(loc);
2602 unsigned line = getLineNumber(loc);
2603 unsigned column = getColumnNumber(loc);
2604
2605 // Build the debug-info type for the block literal.
2606 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2607
2608 const llvm::StructLayout *blockLayout =
2609 CGM.getDataLayout().getStructLayout(block.StructureType);
2610
2611 SmallVector<llvm::Value*, 16> fields;
2612 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2613 blockLayout->getElementOffsetInBits(0),
2614 tunit, tunit));
2615 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2616 blockLayout->getElementOffsetInBits(1),
2617 tunit, tunit));
2618 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2619 blockLayout->getElementOffsetInBits(2),
2620 tunit, tunit));
2621 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2622 blockLayout->getElementOffsetInBits(3),
2623 tunit, tunit));
2624 fields.push_back(createFieldType("__descriptor",
2625 C.getPointerType(block.NeedsCopyDispose ?
2626 C.getBlockDescriptorExtendedType() :
2627 C.getBlockDescriptorType()),
2628 0, loc, AS_public,
2629 blockLayout->getElementOffsetInBits(4),
2630 tunit, tunit));
2631
2632 // We want to sort the captures by offset, not because DWARF
2633 // requires this, but because we're paranoid about debuggers.
2634 SmallVector<BlockLayoutChunk, 8> chunks;
2635
2636 // 'this' capture.
2637 if (blockDecl->capturesCXXThis()) {
2638 BlockLayoutChunk chunk;
2639 chunk.OffsetInBits =
2640 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2641 chunk.Capture = 0;
2642 chunks.push_back(chunk);
2643 }
2644
2645 // Variable captures.
2646 for (BlockDecl::capture_const_iterator
2647 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2648 i != e; ++i) {
2649 const BlockDecl::Capture &capture = *i;
2650 const VarDecl *variable = capture.getVariable();
2651 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2652
2653 // Ignore constant captures.
2654 if (captureInfo.isConstant())
2655 continue;
2656
2657 BlockLayoutChunk chunk;
2658 chunk.OffsetInBits =
2659 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2660 chunk.Capture = &capture;
2661 chunks.push_back(chunk);
2662 }
2663
2664 // Sort by offset.
2665 llvm::array_pod_sort(chunks.begin(), chunks.end());
2666
2667 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2668 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2669 uint64_t offsetInBits = i->OffsetInBits;
2670 const BlockDecl::Capture *capture = i->Capture;
2671
2672 // If we have a null capture, this must be the C++ 'this' capture.
2673 if (!capture) {
2674 const CXXMethodDecl *method =
2675 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2676 QualType type = method->getThisType(C);
2677
2678 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2679 offsetInBits, tunit, tunit));
2680 continue;
2681 }
2682
2683 const VarDecl *variable = capture->getVariable();
2684 StringRef name = variable->getName();
2685
2686 llvm::DIType fieldType;
2687 if (capture->isByRef()) {
2688 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2689
2690 // FIXME: this creates a second copy of this type!
2691 uint64_t xoffset;
2692 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2693 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2694 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2695 ptrInfo.first, ptrInfo.second,
2696 offsetInBits, 0, fieldType);
2697 } else {
2698 fieldType = createFieldType(name, variable->getType(), 0,
2699 loc, AS_public, offsetInBits, tunit, tunit);
2700 }
2701 fields.push_back(fieldType);
2702 }
2703
2704 SmallString<36> typeName;
2705 llvm::raw_svector_ostream(typeName)
2706 << "__block_literal_" << CGM.getUniqueBlockCount();
2707
2708 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2709
2710 llvm::DIType type =
2711 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2712 CGM.getContext().toBits(block.BlockSize),
2713 CGM.getContext().toBits(block.BlockAlign),
2714 0, fieldsArray);
2715 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2716
2717 // Get overall information about the block.
2718 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2719 llvm::MDNode *scope = LexicalBlockStack.back();
2720 StringRef name = ".block_descriptor";
2721
2722 // Create the descriptor for the parameter.
2723 llvm::DIVariable debugVar =
2724 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2725 llvm::DIDescriptor(scope),
2726 name, tunit, line, type,
2727 CGM.getLangOpts().Optimize, flags,
2728 cast<llvm::Argument>(addr)->getArgNo() + 1);
2729
2730 // Insert an llvm.dbg.value into the current block.
2731 llvm::Instruction *declare =
2732 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2733 Builder.GetInsertBlock());
2734 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2735}
2736
Eric Christopher91a31902013-01-16 01:22:32 +00002737/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2738/// a static data member of a class, find its corresponding in-class
2739/// declaration.
2740llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2741 if (cast<VarDecl>(D)->isStaticDataMember()) {
2742 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2743 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2744 if (MI != StaticDataMemberCache.end())
2745 // Verify the info still exists.
2746 if (llvm::Value *V = MI->second)
2747 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2748 }
2749 return llvm::DIDerivedType();
2750}
2751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752/// EmitGlobalVariable - Emit information about a global variable.
2753void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2754 const VarDecl *D) {
2755 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2756 // Create global variable debug descriptor.
2757 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2758 unsigned LineNo = getLineNumber(D->getLocation());
2759
2760 setLocation(D->getLocation());
2761
2762 QualType T = D->getType();
2763 if (T->isIncompleteArrayType()) {
2764
2765 // CodeGen turns int[] into int[1] so we'll do the same here.
2766 llvm::APInt ConstVal(32, 1);
2767 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2768
2769 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2770 ArrayType::Normal, 0);
2771 }
2772 StringRef DeclName = D->getName();
2773 StringRef LinkageName;
2774 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2775 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2776 LinkageName = Var->getName();
2777 if (LinkageName == DeclName)
2778 LinkageName = StringRef();
2779 llvm::DIDescriptor DContext =
2780 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2781 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2782 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher91a31902013-01-16 01:22:32 +00002783 Var->hasInternalLinkage(), Var,
2784 getStaticDataMemberDeclaration(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002785}
2786
2787/// EmitGlobalVariable - Emit information about an objective-c interface.
2788void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2789 ObjCInterfaceDecl *ID) {
2790 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2791 // Create global variable debug descriptor.
2792 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2793 unsigned LineNo = getLineNumber(ID->getLocation());
2794
2795 StringRef Name = ID->getName();
2796
2797 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2798 if (T->isIncompleteArrayType()) {
2799
2800 // CodeGen turns int[] into int[1] so we'll do the same here.
2801 llvm::APInt ConstVal(32, 1);
2802 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2803
2804 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2805 ArrayType::Normal, 0);
2806 }
2807
2808 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2809 getOrCreateType(T, Unit),
2810 Var->hasInternalLinkage(), Var);
2811}
2812
2813/// EmitGlobalVariable - Emit global variable's debug info.
2814void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2815 llvm::Constant *Init) {
2816 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2817 // Create the descriptor for the variable.
2818 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2819 StringRef Name = VD->getName();
2820 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2821 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2822 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2823 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2824 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2825 }
2826 // Do not use DIGlobalVariable for enums.
2827 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2828 return;
2829 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2830 getLineNumber(VD->getLocation()),
Eric Christopher91a31902013-01-16 01:22:32 +00002831 Ty, true, Init,
2832 getStaticDataMemberDeclaration(VD));
Guy Benyei11169dd2012-12-18 14:30:41 +00002833}
2834
2835/// getOrCreateNamesSpace - Return namespace descriptor for the given
2836/// namespace decl.
2837llvm::DINameSpace
2838CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2839 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2840 NameSpaceCache.find(NSDecl);
2841 if (I != NameSpaceCache.end())
2842 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2843
2844 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2845 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2846 llvm::DIDescriptor Context =
2847 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2848 llvm::DINameSpace NS =
2849 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2850 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2851 return NS;
2852}
2853
2854void CGDebugInfo::finalize() {
2855 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2856 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2857 llvm::DIType Ty, RepTy;
2858 // Verify that the debug info still exists.
2859 if (llvm::Value *V = VI->second)
2860 Ty = llvm::DIType(cast<llvm::MDNode>(V));
2861
2862 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2863 TypeCache.find(VI->first);
2864 if (it != TypeCache.end()) {
2865 // Verify that the debug info still exists.
2866 if (llvm::Value *V = it->second)
2867 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2868 }
2869
2870 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2871 Ty.replaceAllUsesWith(RepTy);
2872 }
2873 }
2874 DBuilder.finalize();
2875}