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