1 //===--- 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 "CGCXXABI.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 using namespace clang;
42 using namespace clang::CodeGen;
43
CGDebugInfo(CodeGenModule & CGM)44 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
45 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
47 CreateCompileUnit();
48 }
49
~CGDebugInfo()50 CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53 }
54
ApplyDebugLocation(CodeGenFunction & CGF,SourceLocation TemporaryLocation)55 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
56 SourceLocation TemporaryLocation)
57 : CGF(CGF) {
58 init(TemporaryLocation);
59 }
60
ApplyDebugLocation(CodeGenFunction & CGF,bool DefaultToEmpty,SourceLocation TemporaryLocation)61 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
62 bool DefaultToEmpty,
63 SourceLocation TemporaryLocation)
64 : CGF(CGF) {
65 init(TemporaryLocation, DefaultToEmpty);
66 }
67
init(SourceLocation TemporaryLocation,bool DefaultToEmpty)68 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
69 bool DefaultToEmpty) {
70 if (auto *DI = CGF.getDebugInfo()) {
71 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
72 if (TemporaryLocation.isInvalid()) {
73 if (DefaultToEmpty)
74 CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc());
75 else {
76 // Construct a location that has a valid scope, but no line info.
77 assert(!DI->LexicalBlockStack.empty());
78 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
79 CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
80 }
81 } else
82 DI->EmitLocation(CGF.Builder, TemporaryLocation);
83 }
84 }
85
ApplyDebugLocation(CodeGenFunction & CGF,const Expr * E)86 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
87 : CGF(CGF) {
88 init(E->getExprLoc());
89 }
90
ApplyDebugLocation(CodeGenFunction & CGF,llvm::DebugLoc Loc)91 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
92 : CGF(CGF) {
93 if (CGF.getDebugInfo()) {
94 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
95 if (Loc)
96 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
97 }
98 }
99
~ApplyDebugLocation()100 ApplyDebugLocation::~ApplyDebugLocation() {
101 // Query CGF so the location isn't overwritten when location updates are
102 // temporarily disabled (for C++ default function arguments)
103 if (CGF.getDebugInfo())
104 CGF.Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
105 }
106
107 /// ArtificialLocation - An RAII object that temporarily switches to
108 /// an artificial debug location that has a valid scope, but no line
setLocation(SourceLocation Loc)109 void CGDebugInfo::setLocation(SourceLocation Loc) {
110 // If the new location isn't valid return.
111 if (Loc.isInvalid())
112 return;
113
114 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
115
116 // If we've changed files in the middle of a lexical scope go ahead
117 // and create a new lexical scope with file node if it's different
118 // from the one in the scope.
119 if (LexicalBlockStack.empty())
120 return;
121
122 SourceManager &SM = CGM.getContext().getSourceManager();
123 auto *Scope = cast<llvm::MDScope>(LexicalBlockStack.back());
124 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
125
126 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
127 return;
128
129 if (auto *LBF = dyn_cast<llvm::MDLexicalBlockFile>(Scope)) {
130 llvm::DIDescriptor D = DBuilder.createLexicalBlockFile(
131 LBF->getScope(), getOrCreateFile(CurLoc));
132 llvm::MDNode *N = D;
133 LexicalBlockStack.pop_back();
134 LexicalBlockStack.emplace_back(N);
135 } else if (isa<llvm::MDLexicalBlock>(Scope) ||
136 isa<llvm::MDSubprogram>(Scope)) {
137 llvm::DIDescriptor D =
138 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
139 llvm::MDNode *N = D;
140 LexicalBlockStack.pop_back();
141 LexicalBlockStack.emplace_back(N);
142 }
143 }
144
145 /// getContextDescriptor - Get context info for the decl.
getContextDescriptor(const Decl * Context)146 llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
147 if (!Context)
148 return TheCU;
149
150 auto I = RegionMap.find(Context);
151 if (I != RegionMap.end()) {
152 llvm::Metadata *V = I->second;
153 return dyn_cast_or_null<llvm::MDScope>(V);
154 }
155
156 // Check namespace.
157 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
158 return getOrCreateNameSpace(NSDecl);
159
160 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
161 if (!RDecl->isDependentType())
162 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
163 getOrCreateMainFile());
164 return TheCU;
165 }
166
167 /// getFunctionName - Get function name for the given FunctionDecl. If the
168 /// name is constructed on demand (e.g. C++ destructor) then the name
169 /// is stored on the side.
getFunctionName(const FunctionDecl * FD)170 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
171 assert(FD && "Invalid FunctionDecl!");
172 IdentifierInfo *FII = FD->getIdentifier();
173 FunctionTemplateSpecializationInfo *Info =
174 FD->getTemplateSpecializationInfo();
175 if (!Info && FII)
176 return FII->getName();
177
178 // Otherwise construct human readable name for debug info.
179 SmallString<128> NS;
180 llvm::raw_svector_ostream OS(NS);
181 FD->printName(OS);
182
183 // Add any template specialization args.
184 if (Info) {
185 const TemplateArgumentList *TArgs = Info->TemplateArguments;
186 const TemplateArgument *Args = TArgs->data();
187 unsigned NumArgs = TArgs->size();
188 PrintingPolicy Policy(CGM.getLangOpts());
189 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
190 Policy);
191 }
192
193 // Copy this name on the side and use its reference.
194 return internString(OS.str());
195 }
196
getObjCMethodName(const ObjCMethodDecl * OMD)197 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
198 SmallString<256> MethodName;
199 llvm::raw_svector_ostream OS(MethodName);
200 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
201 const DeclContext *DC = OMD->getDeclContext();
202 if (const ObjCImplementationDecl *OID =
203 dyn_cast<const ObjCImplementationDecl>(DC)) {
204 OS << OID->getName();
205 } else if (const ObjCInterfaceDecl *OID =
206 dyn_cast<const ObjCInterfaceDecl>(DC)) {
207 OS << OID->getName();
208 } else if (const ObjCCategoryImplDecl *OCD =
209 dyn_cast<const ObjCCategoryImplDecl>(DC)) {
210 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
211 << OCD->getIdentifier()->getNameStart() << ')';
212 } else if (isa<ObjCProtocolDecl>(DC)) {
213 // We can extract the type of the class from the self pointer.
214 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
215 QualType ClassTy =
216 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
217 ClassTy.print(OS, PrintingPolicy(LangOptions()));
218 }
219 }
220 OS << ' ' << OMD->getSelector().getAsString() << ']';
221
222 return internString(OS.str());
223 }
224
225 /// getSelectorName - Return selector name. This is used for debugging
226 /// info.
getSelectorName(Selector S)227 StringRef CGDebugInfo::getSelectorName(Selector S) {
228 return internString(S.getAsString());
229 }
230
231 /// getClassName - Get class name including template argument list.
getClassName(const RecordDecl * RD)232 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
233 // quick optimization to avoid having to intern strings that are already
234 // stored reliably elsewhere
235 if (!isa<ClassTemplateSpecializationDecl>(RD))
236 return RD->getName();
237
238 SmallString<128> Name;
239 {
240 llvm::raw_svector_ostream OS(Name);
241 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
242 /*Qualified*/ false);
243 }
244
245 // Copy this name on the side and use its reference.
246 return internString(Name);
247 }
248
249 /// getOrCreateFile - Get the file debug info descriptor for the input location.
getOrCreateFile(SourceLocation Loc)250 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
251 if (!Loc.isValid())
252 // If Location is not valid then use main input file.
253 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
254
255 SourceManager &SM = CGM.getContext().getSourceManager();
256 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
257
258 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
259 // If the location is not valid then use main input file.
260 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
261
262 // Cache the results.
263 const char *fname = PLoc.getFilename();
264 auto it = DIFileCache.find(fname);
265
266 if (it != DIFileCache.end()) {
267 // Verify that the information still exists.
268 if (llvm::Metadata *V = it->second)
269 return cast<llvm::MDFile>(V);
270 }
271
272 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
273
274 DIFileCache[fname].reset(F);
275 return F;
276 }
277
278 /// getOrCreateMainFile - Get the file info for main compile unit.
getOrCreateMainFile()279 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
280 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
281 }
282
283 /// getLineNumber - Get line number for the location. If location is invalid
284 /// then use current location.
getLineNumber(SourceLocation Loc)285 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
286 if (Loc.isInvalid() && CurLoc.isInvalid())
287 return 0;
288 SourceManager &SM = CGM.getContext().getSourceManager();
289 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
290 return PLoc.isValid() ? PLoc.getLine() : 0;
291 }
292
293 /// getColumnNumber - Get column number for the location.
getColumnNumber(SourceLocation Loc,bool Force)294 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
295 // We may not want column information at all.
296 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
297 return 0;
298
299 // If the location is invalid then use the current column.
300 if (Loc.isInvalid() && CurLoc.isInvalid())
301 return 0;
302 SourceManager &SM = CGM.getContext().getSourceManager();
303 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
304 return PLoc.isValid() ? PLoc.getColumn() : 0;
305 }
306
getCurrentDirname()307 StringRef CGDebugInfo::getCurrentDirname() {
308 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
309 return CGM.getCodeGenOpts().DebugCompilationDir;
310
311 if (!CWDName.empty())
312 return CWDName;
313 SmallString<256> CWD;
314 llvm::sys::fs::current_path(CWD);
315 return CWDName = internString(CWD);
316 }
317
318 /// CreateCompileUnit - Create new compile unit.
CreateCompileUnit()319 void CGDebugInfo::CreateCompileUnit() {
320
321 // Should we be asking the SourceManager for the main file name, instead of
322 // accepting it as an argument? This just causes the main file name to
323 // mismatch with source locations and create extra lexical scopes or
324 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
325 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
326 // because that's what the SourceManager says)
327
328 // Get absolute path name.
329 SourceManager &SM = CGM.getContext().getSourceManager();
330 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
331 if (MainFileName.empty())
332 MainFileName = "<stdin>";
333
334 // The main file name provided via the "-main-file-name" option contains just
335 // the file name itself with no path information. This file name may have had
336 // a relative path, so we look into the actual file entry for the main
337 // file to determine the real absolute path for the file.
338 std::string MainFileDir;
339 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
340 MainFileDir = MainFile->getDir()->getName();
341 if (MainFileDir != ".") {
342 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
343 llvm::sys::path::append(MainFileDirSS, MainFileName);
344 MainFileName = MainFileDirSS.str();
345 }
346 }
347
348 // Save filename string.
349 StringRef Filename = internString(MainFileName);
350
351 // Save split dwarf file string.
352 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
353 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
354
355 llvm::dwarf::SourceLanguage LangTag;
356 const LangOptions &LO = CGM.getLangOpts();
357 if (LO.CPlusPlus) {
358 if (LO.ObjC1)
359 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
360 else
361 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
362 } else if (LO.ObjC1) {
363 LangTag = llvm::dwarf::DW_LANG_ObjC;
364 } else if (LO.C99) {
365 LangTag = llvm::dwarf::DW_LANG_C99;
366 } else {
367 LangTag = llvm::dwarf::DW_LANG_C89;
368 }
369
370 std::string Producer = getClangFullVersion();
371
372 // Figure out which version of the ObjC runtime we have.
373 unsigned RuntimeVers = 0;
374 if (LO.ObjC1)
375 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
376
377 // Create new compile unit.
378 // FIXME - Eliminate TheCU.
379 TheCU = DBuilder.createCompileUnit(
380 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
381 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
382 DebugKind <= CodeGenOptions::DebugLineTablesOnly
383 ? llvm::DIBuilder::LineTablesOnly
384 : llvm::DIBuilder::FullDebug,
385 DebugKind != CodeGenOptions::LocTrackingOnly);
386 }
387
388 /// CreateType - Get the Basic type from the cache or create a new
389 /// one if necessary.
CreateType(const BuiltinType * BT)390 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
391 llvm::dwarf::TypeKind Encoding;
392 StringRef BTName;
393 switch (BT->getKind()) {
394 #define BUILTIN_TYPE(Id, SingletonId)
395 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
396 #include "clang/AST/BuiltinTypes.def"
397 case BuiltinType::Dependent:
398 llvm_unreachable("Unexpected builtin type");
399 case BuiltinType::NullPtr:
400 return DBuilder.createNullPtrType();
401 case BuiltinType::Void:
402 return llvm::DIType();
403 case BuiltinType::ObjCClass:
404 if (!ClassTy)
405 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
406 "objc_class", TheCU,
407 getOrCreateMainFile(), 0);
408 return ClassTy;
409 case BuiltinType::ObjCId: {
410 // typedef struct objc_class *Class;
411 // typedef struct objc_object {
412 // Class isa;
413 // } *id;
414
415 if (ObjTy)
416 return ObjTy;
417
418 if (!ClassTy)
419 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
420 "objc_class", TheCU,
421 getOrCreateMainFile(), 0);
422
423 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
424
425 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
426
427 ObjTy =
428 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
429 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
430
431 DBuilder.replaceArrays(
432 ObjTy,
433 DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
434 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
435 return ObjTy;
436 }
437 case BuiltinType::ObjCSel: {
438 if (!SelTy)
439 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
440 "objc_selector", TheCU,
441 getOrCreateMainFile(), 0);
442 return SelTy;
443 }
444
445 case BuiltinType::OCLImage1d:
446 return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
447 case BuiltinType::OCLImage1dArray:
448 return getOrCreateStructPtrType("opencl_image1d_array_t",
449 OCLImage1dArrayDITy);
450 case BuiltinType::OCLImage1dBuffer:
451 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
452 OCLImage1dBufferDITy);
453 case BuiltinType::OCLImage2d:
454 return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
455 case BuiltinType::OCLImage2dArray:
456 return getOrCreateStructPtrType("opencl_image2d_array_t",
457 OCLImage2dArrayDITy);
458 case BuiltinType::OCLImage3d:
459 return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
460 case BuiltinType::OCLSampler:
461 return DBuilder.createBasicType(
462 "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
463 CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
464 case BuiltinType::OCLEvent:
465 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
466
467 case BuiltinType::UChar:
468 case BuiltinType::Char_U:
469 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
470 break;
471 case BuiltinType::Char_S:
472 case BuiltinType::SChar:
473 Encoding = llvm::dwarf::DW_ATE_signed_char;
474 break;
475 case BuiltinType::Char16:
476 case BuiltinType::Char32:
477 Encoding = llvm::dwarf::DW_ATE_UTF;
478 break;
479 case BuiltinType::UShort:
480 case BuiltinType::UInt:
481 case BuiltinType::UInt128:
482 case BuiltinType::ULong:
483 case BuiltinType::WChar_U:
484 case BuiltinType::ULongLong:
485 Encoding = llvm::dwarf::DW_ATE_unsigned;
486 break;
487 case BuiltinType::Short:
488 case BuiltinType::Int:
489 case BuiltinType::Int128:
490 case BuiltinType::Long:
491 case BuiltinType::WChar_S:
492 case BuiltinType::LongLong:
493 Encoding = llvm::dwarf::DW_ATE_signed;
494 break;
495 case BuiltinType::Bool:
496 Encoding = llvm::dwarf::DW_ATE_boolean;
497 break;
498 case BuiltinType::Half:
499 case BuiltinType::Float:
500 case BuiltinType::LongDouble:
501 case BuiltinType::Double:
502 Encoding = llvm::dwarf::DW_ATE_float;
503 break;
504 }
505
506 switch (BT->getKind()) {
507 case BuiltinType::Long:
508 BTName = "long int";
509 break;
510 case BuiltinType::LongLong:
511 BTName = "long long int";
512 break;
513 case BuiltinType::ULong:
514 BTName = "long unsigned int";
515 break;
516 case BuiltinType::ULongLong:
517 BTName = "long long unsigned int";
518 break;
519 default:
520 BTName = BT->getName(CGM.getLangOpts());
521 break;
522 }
523 // Bit size, align and offset of the type.
524 uint64_t Size = CGM.getContext().getTypeSize(BT);
525 uint64_t Align = CGM.getContext().getTypeAlign(BT);
526 llvm::DIType DbgTy = DBuilder.createBasicType(BTName, Size, Align, Encoding);
527 return DbgTy;
528 }
529
CreateType(const ComplexType * Ty)530 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
531 // Bit size, align and offset of the type.
532 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
533 if (Ty->isComplexIntegerType())
534 Encoding = llvm::dwarf::DW_ATE_lo_user;
535
536 uint64_t Size = CGM.getContext().getTypeSize(Ty);
537 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
538 llvm::DIType DbgTy =
539 DBuilder.createBasicType("complex", Size, Align, Encoding);
540
541 return DbgTy;
542 }
543
544 /// CreateCVRType - Get the qualified type from the cache or create
545 /// a new one if necessary.
CreateQualifiedType(QualType Ty,llvm::DIFile Unit)546 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
547 QualifierCollector Qc;
548 const Type *T = Qc.strip(Ty);
549
550 // Ignore these qualifiers for now.
551 Qc.removeObjCGCAttr();
552 Qc.removeAddressSpace();
553 Qc.removeObjCLifetime();
554
555 // We will create one Derived type for one qualifier and recurse to handle any
556 // additional ones.
557 llvm::dwarf::Tag Tag;
558 if (Qc.hasConst()) {
559 Tag = llvm::dwarf::DW_TAG_const_type;
560 Qc.removeConst();
561 } else if (Qc.hasVolatile()) {
562 Tag = llvm::dwarf::DW_TAG_volatile_type;
563 Qc.removeVolatile();
564 } else if (Qc.hasRestrict()) {
565 Tag = llvm::dwarf::DW_TAG_restrict_type;
566 Qc.removeRestrict();
567 } else {
568 assert(Qc.empty() && "Unknown type qualifier for debug info");
569 return getOrCreateType(QualType(T, 0), Unit);
570 }
571
572 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
573
574 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
575 // CVR derived types.
576 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
577
578 return DbgTy;
579 }
580
CreateType(const ObjCObjectPointerType * Ty,llvm::DIFile Unit)581 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
582 llvm::DIFile Unit) {
583
584 // The frontend treats 'id' as a typedef to an ObjCObjectType,
585 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
586 // debug info, we want to emit 'id' in both cases.
587 if (Ty->isObjCQualifiedIdType())
588 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
589
590 llvm::DIType DbgTy = CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type,
591 Ty, Ty->getPointeeType(), Unit);
592 return DbgTy;
593 }
594
CreateType(const PointerType * Ty,llvm::DIFile Unit)595 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, llvm::DIFile Unit) {
596 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
597 Ty->getPointeeType(), Unit);
598 }
599
600 /// In C++ mode, types have linkage, so we can rely on the ODR and
601 /// on their mangled names, if they're external.
getUniqueTagTypeName(const TagType * Ty,CodeGenModule & CGM,llvm::DICompileUnit TheCU)602 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
603 CodeGenModule &CGM,
604 llvm::DICompileUnit TheCU) {
605 SmallString<256> FullName;
606 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
607 // For now, only apply ODR with C++.
608 const TagDecl *TD = Ty->getDecl();
609 if (TheCU->getSourceLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
610 !TD->isExternallyVisible())
611 return FullName;
612 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
613 if (CGM.getTarget().getCXXABI().isMicrosoft())
614 return FullName;
615
616 // TODO: This is using the RTTI name. Is there a better way to get
617 // a unique string for a type?
618 llvm::raw_svector_ostream Out(FullName);
619 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
620 Out.flush();
621 return FullName;
622 }
623
getTagForRecord(const RecordDecl * RD)624 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
625 llvm::dwarf::Tag Tag;
626 if (RD->isStruct() || RD->isInterface())
627 Tag = llvm::dwarf::DW_TAG_structure_type;
628 else if (RD->isUnion())
629 Tag = llvm::dwarf::DW_TAG_union_type;
630 else {
631 // FIXME: This could be a struct type giving a default visibility different
632 // than C++ class type, but needs llvm metadata changes first.
633 assert(RD->isClass());
634 Tag = llvm::dwarf::DW_TAG_class_type;
635 }
636 return Tag;
637 }
638
639 // Creates a forward declaration for a RecordDecl in the given context.
640 llvm::MDCompositeType *
getOrCreateRecordFwdDecl(const RecordType * Ty,llvm::MDScope * Ctx)641 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
642 llvm::MDScope *Ctx) {
643 const RecordDecl *RD = Ty->getDecl();
644 if (llvm::MDType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
645 return cast<llvm::MDCompositeType>(T);
646 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
647 unsigned Line = getLineNumber(RD->getLocation());
648 StringRef RDName = getClassName(RD);
649
650 uint64_t Size = 0;
651 uint64_t Align = 0;
652
653 const RecordDecl *D = RD->getDefinition();
654 if (D && D->isCompleteDefinition()) {
655 Size = CGM.getContext().getTypeSize(Ty);
656 Align = CGM.getContext().getTypeAlign(Ty);
657 }
658
659 // Create the type.
660 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
661 llvm::MDCompositeType *RetTy = DBuilder.createReplaceableCompositeType(
662 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
663 llvm::DebugNode::FlagFwdDecl, FullName);
664 ReplaceMap.emplace_back(
665 std::piecewise_construct, std::make_tuple(Ty),
666 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
667 return RetTy;
668 }
669
CreatePointerLikeType(llvm::dwarf::Tag Tag,const Type * Ty,QualType PointeeTy,llvm::DIFile Unit)670 llvm::DIType CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
671 const Type *Ty,
672 QualType PointeeTy,
673 llvm::DIFile Unit) {
674 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
675 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
676 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
677
678 // Bit size, align and offset of the type.
679 // Size is always the size of a pointer. We can't use getTypeSize here
680 // because that does not return the correct value for references.
681 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
682 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
683 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
684
685 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
686 Align);
687 }
688
getOrCreateStructPtrType(StringRef Name,llvm::DIType & Cache)689 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
690 llvm::DIType &Cache) {
691 if (Cache)
692 return Cache;
693 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
694 TheCU, getOrCreateMainFile(), 0);
695 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
696 Cache = DBuilder.createPointerType(Cache, Size);
697 return Cache;
698 }
699
CreateType(const BlockPointerType * Ty,llvm::DIFile Unit)700 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
701 llvm::DIFile Unit) {
702 if (BlockLiteralGeneric)
703 return BlockLiteralGeneric;
704
705 SmallVector<llvm::Metadata *, 8> EltTys;
706 llvm::DIType FieldTy;
707 QualType FType;
708 uint64_t FieldSize, FieldOffset;
709 unsigned FieldAlign;
710 llvm::DIArray Elements;
711 llvm::DIType EltTy, DescTy;
712
713 FieldOffset = 0;
714 FType = CGM.getContext().UnsignedLongTy;
715 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
716 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
717
718 Elements = DBuilder.getOrCreateArray(EltTys);
719 EltTys.clear();
720
721 unsigned Flags = llvm::DebugNode::FlagAppleBlock;
722 unsigned LineNo = getLineNumber(CurLoc);
723
724 EltTy = DBuilder.createStructType(Unit, "__block_descriptor", Unit, LineNo,
725 FieldOffset, 0, Flags, llvm::DIType(),
726 Elements);
727
728 // Bit size, align and offset of the type.
729 uint64_t Size = CGM.getContext().getTypeSize(Ty);
730
731 DescTy = DBuilder.createPointerType(EltTy, Size);
732
733 FieldOffset = 0;
734 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
735 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
736 FType = CGM.getContext().IntTy;
737 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
738 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
739 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
740 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
741
742 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
743 FieldTy = DescTy;
744 FieldSize = CGM.getContext().getTypeSize(Ty);
745 FieldAlign = CGM.getContext().getTypeAlign(Ty);
746 FieldTy =
747 DBuilder.createMemberType(Unit, "__descriptor", Unit, LineNo, FieldSize,
748 FieldAlign, FieldOffset, 0, FieldTy);
749 EltTys.push_back(FieldTy);
750
751 FieldOffset += FieldSize;
752 Elements = DBuilder.getOrCreateArray(EltTys);
753
754 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic", Unit,
755 LineNo, FieldOffset, 0, Flags,
756 llvm::DIType(), Elements);
757
758 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
759 return BlockLiteralGeneric;
760 }
761
CreateType(const TemplateSpecializationType * Ty,llvm::DIFile Unit)762 llvm::DIType CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
763 llvm::DIFile Unit) {
764 assert(Ty->isTypeAlias());
765 llvm::DIType Src = getOrCreateType(Ty->getAliasedType(), Unit);
766
767 SmallString<128> NS;
768 llvm::raw_svector_ostream OS(NS);
769 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
770 /*qualified*/ false);
771
772 TemplateSpecializationType::PrintTemplateArgumentList(
773 OS, Ty->getArgs(), Ty->getNumArgs(),
774 CGM.getContext().getPrintingPolicy());
775
776 TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
777 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
778
779 SourceLocation Loc = AliasDecl->getLocation();
780 return DBuilder.createTypedef(
781 Src, internString(OS.str()), getOrCreateFile(Loc), getLineNumber(Loc),
782 getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext())));
783 }
784
CreateType(const TypedefType * Ty,llvm::DIFile Unit)785 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
786 // We don't set size information, but do specify where the typedef was
787 // declared.
788 SourceLocation Loc = Ty->getDecl()->getLocation();
789
790 // Typedefs are derived from some other type.
791 return DBuilder.createTypedef(
792 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
793 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
794 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())));
795 }
796
CreateType(const FunctionType * Ty,llvm::DIFile Unit)797 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
798 llvm::DIFile Unit) {
799 SmallVector<llvm::Metadata *, 16> EltTys;
800
801 // Add the result type at least.
802 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
803
804 // Set up remainder of arguments if there is a prototype.
805 // otherwise emit it as a variadic function.
806 if (isa<FunctionNoProtoType>(Ty))
807 EltTys.push_back(DBuilder.createUnspecifiedParameter());
808 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
809 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
810 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
811 if (FPT->isVariadic())
812 EltTys.push_back(DBuilder.createUnspecifiedParameter());
813 }
814
815 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
816 return DBuilder.createSubroutineType(Unit, EltTypeArray);
817 }
818
819 /// Convert an AccessSpecifier into the corresponding DIDescriptor flag.
820 /// As an optimization, return 0 if the access specifier equals the
821 /// default for the containing type.
getAccessFlag(AccessSpecifier Access,const RecordDecl * RD)822 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
823 AccessSpecifier Default = clang::AS_none;
824 if (RD && RD->isClass())
825 Default = clang::AS_private;
826 else if (RD && (RD->isStruct() || RD->isUnion()))
827 Default = clang::AS_public;
828
829 if (Access == Default)
830 return 0;
831
832 switch (Access) {
833 case clang::AS_private:
834 return llvm::DebugNode::FlagPrivate;
835 case clang::AS_protected:
836 return llvm::DebugNode::FlagProtected;
837 case clang::AS_public:
838 return llvm::DebugNode::FlagPublic;
839 case clang::AS_none:
840 return 0;
841 }
842 llvm_unreachable("unexpected access enumerator");
843 }
844
createFieldType(StringRef name,QualType type,uint64_t sizeInBitsOverride,SourceLocation loc,AccessSpecifier AS,uint64_t offsetInBits,llvm::DIFile tunit,llvm::DIScope scope,const RecordDecl * RD)845 llvm::DIType CGDebugInfo::createFieldType(
846 StringRef name, QualType type, uint64_t sizeInBitsOverride,
847 SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
848 llvm::DIFile tunit, llvm::DIScope scope, const RecordDecl *RD) {
849 llvm::DIType debugType = getOrCreateType(type, tunit);
850
851 // Get the location for the field.
852 llvm::DIFile file = getOrCreateFile(loc);
853 unsigned line = getLineNumber(loc);
854
855 uint64_t SizeInBits = 0;
856 unsigned AlignInBits = 0;
857 if (!type->isIncompleteArrayType()) {
858 TypeInfo TI = CGM.getContext().getTypeInfo(type);
859 SizeInBits = TI.Width;
860 AlignInBits = TI.Align;
861
862 if (sizeInBitsOverride)
863 SizeInBits = sizeInBitsOverride;
864 }
865
866 unsigned flags = getAccessFlag(AS, RD);
867 return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
868 AlignInBits, offsetInBits, flags, debugType);
869 }
870
871 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
CollectRecordLambdaFields(const CXXRecordDecl * CXXDecl,SmallVectorImpl<llvm::Metadata * > & elements,llvm::DIType RecordTy)872 void CGDebugInfo::CollectRecordLambdaFields(
873 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
874 llvm::DIType RecordTy) {
875 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
876 // has the name and the location of the variable so we should iterate over
877 // both concurrently.
878 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
879 RecordDecl::field_iterator Field = CXXDecl->field_begin();
880 unsigned fieldno = 0;
881 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
882 E = CXXDecl->captures_end();
883 I != E; ++I, ++Field, ++fieldno) {
884 const LambdaCapture &C = *I;
885 if (C.capturesVariable()) {
886 VarDecl *V = C.getCapturedVar();
887 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
888 StringRef VName = V->getName();
889 uint64_t SizeInBitsOverride = 0;
890 if (Field->isBitField()) {
891 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
892 assert(SizeInBitsOverride && "found named 0-width bitfield");
893 }
894 llvm::DIType fieldType = createFieldType(
895 VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
896 Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
897 CXXDecl);
898 elements.push_back(fieldType);
899 } else if (C.capturesThis()) {
900 // TODO: Need to handle 'this' in some way by probably renaming the
901 // this of the lambda class and having a field member of 'this' or
902 // by using AT_object_pointer for the function and having that be
903 // used as 'this' for semantic references.
904 FieldDecl *f = *Field;
905 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
906 QualType type = f->getType();
907 llvm::DIType fieldType = createFieldType(
908 "this", type, 0, f->getLocation(), f->getAccess(),
909 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
910
911 elements.push_back(fieldType);
912 }
913 }
914 }
915
916 /// Helper for CollectRecordFields.
CreateRecordStaticField(const VarDecl * Var,llvm::DIType RecordTy,const RecordDecl * RD)917 llvm::DIDerivedType CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
918 llvm::DIType RecordTy,
919 const RecordDecl *RD) {
920 // Create the descriptor for the static variable, with or without
921 // constant initializers.
922 Var = Var->getCanonicalDecl();
923 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
924 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
925
926 unsigned LineNumber = getLineNumber(Var->getLocation());
927 StringRef VName = Var->getName();
928 llvm::Constant *C = nullptr;
929 if (Var->getInit()) {
930 const APValue *Value = Var->evaluateValue();
931 if (Value) {
932 if (Value->isInt())
933 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
934 if (Value->isFloat())
935 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
936 }
937 }
938
939 unsigned Flags = getAccessFlag(Var->getAccess(), RD);
940 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
941 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
942 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
943 return GV;
944 }
945
946 /// CollectRecordNormalField - Helper for CollectRecordFields.
CollectRecordNormalField(const FieldDecl * field,uint64_t OffsetInBits,llvm::DIFile tunit,SmallVectorImpl<llvm::Metadata * > & elements,llvm::DIType RecordTy,const RecordDecl * RD)947 void CGDebugInfo::CollectRecordNormalField(
948 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile tunit,
949 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType RecordTy,
950 const RecordDecl *RD) {
951 StringRef name = field->getName();
952 QualType type = field->getType();
953
954 // Ignore unnamed fields unless they're anonymous structs/unions.
955 if (name.empty() && !type->isRecordType())
956 return;
957
958 uint64_t SizeInBitsOverride = 0;
959 if (field->isBitField()) {
960 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
961 assert(SizeInBitsOverride && "found named 0-width bitfield");
962 }
963
964 llvm::DIType fieldType =
965 createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
966 field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
967
968 elements.push_back(fieldType);
969 }
970
971 /// CollectRecordFields - A helper function to collect debug info for
972 /// record fields. This is used while creating debug info entry for a Record.
CollectRecordFields(const RecordDecl * record,llvm::DIFile tunit,SmallVectorImpl<llvm::Metadata * > & elements,llvm::DICompositeType RecordTy)973 void CGDebugInfo::CollectRecordFields(
974 const RecordDecl *record, llvm::DIFile tunit,
975 SmallVectorImpl<llvm::Metadata *> &elements,
976 llvm::DICompositeType RecordTy) {
977 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
978
979 if (CXXDecl && CXXDecl->isLambda())
980 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
981 else {
982 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
983
984 // Field number for non-static fields.
985 unsigned fieldNo = 0;
986
987 // Static and non-static members should appear in the same order as
988 // the corresponding declarations in the source program.
989 for (const auto *I : record->decls())
990 if (const auto *V = dyn_cast<VarDecl>(I)) {
991 // Reuse the existing static member declaration if one exists
992 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
993 if (MI != StaticDataMemberCache.end()) {
994 assert(MI->second &&
995 "Static data member declaration should still exist");
996 elements.push_back(cast<llvm::MDDerivedTypeBase>(MI->second));
997 } else {
998 auto Field = CreateRecordStaticField(V, RecordTy, record);
999 elements.push_back(Field);
1000 }
1001 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1002 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1003 elements, RecordTy, record);
1004
1005 // Bump field number for next field.
1006 ++fieldNo;
1007 }
1008 }
1009 }
1010
1011 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
1012 /// function type is not updated to include implicit "this" pointer. Use this
1013 /// routine to get a method type which includes "this" pointer.
1014 llvm::MDSubroutineType *
getOrCreateMethodType(const CXXMethodDecl * Method,llvm::DIFile Unit)1015 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1016 llvm::DIFile Unit) {
1017 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1018 if (Method->isStatic())
1019 return cast_or_null<llvm::MDSubroutineType>(
1020 getOrCreateType(QualType(Func, 0), Unit));
1021 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1022 Func, Unit);
1023 }
1024
getOrCreateInstanceMethodType(QualType ThisPtr,const FunctionProtoType * Func,llvm::DIFile Unit)1025 llvm::MDSubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1026 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
1027 // Add "this" pointer.
1028 llvm::DITypeArray Args(
1029 cast<llvm::MDSubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1030 ->getTypeArray());
1031 assert(Args.size() && "Invalid number of arguments!");
1032
1033 SmallVector<llvm::Metadata *, 16> Elts;
1034
1035 // First element is always return type. For 'void' functions it is NULL.
1036 Elts.push_back(Args[0]);
1037
1038 // "this" pointer is always first argument.
1039 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1040 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1041 // Create pointer type directly in this case.
1042 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1043 QualType PointeeTy = ThisPtrTy->getPointeeType();
1044 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1045 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1046 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1047 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
1048 llvm::DIType ThisPtrType =
1049 DBuilder.createPointerType(PointeeType, Size, Align);
1050 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1051 // TODO: This and the artificial type below are misleading, the
1052 // types aren't artificial the argument is, but the current
1053 // metadata doesn't represent that.
1054 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1055 Elts.push_back(ThisPtrType);
1056 } else {
1057 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1058 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1059 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1060 Elts.push_back(ThisPtrType);
1061 }
1062
1063 // Copy rest of the arguments.
1064 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1065 Elts.push_back(Args[i]);
1066
1067 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1068
1069 unsigned Flags = 0;
1070 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1071 Flags |= llvm::DebugNode::FlagLValueReference;
1072 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1073 Flags |= llvm::DebugNode::FlagRValueReference;
1074
1075 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
1076 }
1077
1078 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1079 /// inside a function.
isFunctionLocalClass(const CXXRecordDecl * RD)1080 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1081 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1082 return isFunctionLocalClass(NRD);
1083 if (isa<FunctionDecl>(RD->getDeclContext()))
1084 return true;
1085 return false;
1086 }
1087
1088 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1089 /// a single member function GlobalDecl.
1090 llvm::DISubprogram
CreateCXXMemberFunction(const CXXMethodDecl * Method,llvm::DIFile Unit,llvm::DIType RecordTy)1091 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1092 llvm::DIFile Unit, llvm::DIType RecordTy) {
1093 bool IsCtorOrDtor =
1094 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1095
1096 StringRef MethodName = getFunctionName(Method);
1097 llvm::MDSubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1098
1099 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1100 // make sense to give a single ctor/dtor a linkage name.
1101 StringRef MethodLinkageName;
1102 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1103 MethodLinkageName = CGM.getMangledName(Method);
1104
1105 // Get the location for the method.
1106 llvm::DIFile MethodDefUnit;
1107 unsigned MethodLine = 0;
1108 if (!Method->isImplicit()) {
1109 MethodDefUnit = getOrCreateFile(Method->getLocation());
1110 MethodLine = getLineNumber(Method->getLocation());
1111 }
1112
1113 // Collect virtual method info.
1114 llvm::DIType ContainingType;
1115 unsigned Virtuality = 0;
1116 unsigned VIndex = 0;
1117
1118 if (Method->isVirtual()) {
1119 if (Method->isPure())
1120 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1121 else
1122 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1123
1124 // It doesn't make sense to give a virtual destructor a vtable index,
1125 // since a single destructor has two entries in the vtable.
1126 // FIXME: Add proper support for debug info for virtual calls in
1127 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1128 // lookup if we have multiple or virtual inheritance.
1129 if (!isa<CXXDestructorDecl>(Method) &&
1130 !CGM.getTarget().getCXXABI().isMicrosoft())
1131 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1132 ContainingType = RecordTy;
1133 }
1134
1135 unsigned Flags = 0;
1136 if (Method->isImplicit())
1137 Flags |= llvm::DebugNode::FlagArtificial;
1138 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1139 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1140 if (CXXC->isExplicit())
1141 Flags |= llvm::DebugNode::FlagExplicit;
1142 } else if (const CXXConversionDecl *CXXC =
1143 dyn_cast<CXXConversionDecl>(Method)) {
1144 if (CXXC->isExplicit())
1145 Flags |= llvm::DebugNode::FlagExplicit;
1146 }
1147 if (Method->hasPrototype())
1148 Flags |= llvm::DebugNode::FlagPrototyped;
1149 if (Method->getRefQualifier() == RQ_LValue)
1150 Flags |= llvm::DebugNode::FlagLValueReference;
1151 if (Method->getRefQualifier() == RQ_RValue)
1152 Flags |= llvm::DebugNode::FlagRValueReference;
1153
1154 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1155 llvm::DISubprogram SP = DBuilder.createMethod(
1156 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1157 MethodTy, /*isLocalToUnit=*/false,
1158 /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
1159 CGM.getLangOpts().Optimize, nullptr, TParamsArray.get());
1160
1161 SPCache[Method->getCanonicalDecl()].reset(SP);
1162
1163 return SP;
1164 }
1165
1166 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1167 /// C++ member functions. This is used while creating debug info entry for
1168 /// a Record.
CollectCXXMemberFunctions(const CXXRecordDecl * RD,llvm::DIFile Unit,SmallVectorImpl<llvm::Metadata * > & EltTys,llvm::DIType RecordTy)1169 void CGDebugInfo::CollectCXXMemberFunctions(
1170 const CXXRecordDecl *RD, llvm::DIFile Unit,
1171 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType RecordTy) {
1172
1173 // Since we want more than just the individual member decls if we
1174 // have templated functions iterate over every declaration to gather
1175 // the functions.
1176 for (const auto *I : RD->decls()) {
1177 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1178 // If the member is implicit, don't add it to the member list. This avoids
1179 // the member being added to type units by LLVM, while still allowing it
1180 // to be emitted into the type declaration/reference inside the compile
1181 // unit.
1182 // FIXME: Handle Using(Shadow?)Decls here to create
1183 // DW_TAG_imported_declarations inside the class for base decls brought into
1184 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1185 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1186 // referenced)
1187 if (!Method || Method->isImplicit())
1188 continue;
1189
1190 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1191 continue;
1192
1193 // Reuse the existing member function declaration if it exists.
1194 // It may be associated with the declaration of the type & should be
1195 // reused as we're building the definition.
1196 //
1197 // This situation can arise in the vtable-based debug info reduction where
1198 // implicit members are emitted in a non-vtable TU.
1199 auto MI = SPCache.find(Method->getCanonicalDecl());
1200 EltTys.push_back(MI == SPCache.end()
1201 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1202 : static_cast<llvm::Metadata *>(MI->second));
1203 }
1204 }
1205
1206 /// CollectCXXBases - A helper function to collect debug info for
1207 /// C++ base classes. This is used while creating debug info entry for
1208 /// a Record.
CollectCXXBases(const CXXRecordDecl * RD,llvm::DIFile Unit,SmallVectorImpl<llvm::Metadata * > & EltTys,llvm::DIType RecordTy)1209 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1210 SmallVectorImpl<llvm::Metadata *> &EltTys,
1211 llvm::DIType RecordTy) {
1212
1213 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1214 for (const auto &BI : RD->bases()) {
1215 unsigned BFlags = 0;
1216 uint64_t BaseOffset;
1217
1218 const CXXRecordDecl *Base =
1219 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1220
1221 if (BI.isVirtual()) {
1222 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1223 // virtual base offset offset is -ve. The code generator emits dwarf
1224 // expression where it expects +ve number.
1225 BaseOffset = 0 - CGM.getItaniumVTableContext()
1226 .getVirtualBaseOffsetOffset(RD, Base)
1227 .getQuantity();
1228 } else {
1229 // In the MS ABI, store the vbtable offset, which is analogous to the
1230 // vbase offset offset in Itanium.
1231 BaseOffset =
1232 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1233 }
1234 BFlags = llvm::DebugNode::FlagVirtual;
1235 } else
1236 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1237 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1238 // BI->isVirtual() and bits when not.
1239
1240 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1241 llvm::DIType DTy = DBuilder.createInheritance(
1242 RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
1243 EltTys.push_back(DTy);
1244 }
1245 }
1246
1247 /// CollectTemplateParams - A helper function to collect template parameters.
1248 llvm::DIArray
CollectTemplateParams(const TemplateParameterList * TPList,ArrayRef<TemplateArgument> TAList,llvm::DIFile Unit)1249 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1250 ArrayRef<TemplateArgument> TAList,
1251 llvm::DIFile Unit) {
1252 SmallVector<llvm::Metadata *, 16> TemplateParams;
1253 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1254 const TemplateArgument &TA = TAList[i];
1255 StringRef Name;
1256 if (TPList)
1257 Name = TPList->getParam(i)->getName();
1258 switch (TA.getKind()) {
1259 case TemplateArgument::Type: {
1260 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1261 llvm::DITemplateTypeParameter TTP =
1262 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
1263 TemplateParams.push_back(TTP);
1264 } break;
1265 case TemplateArgument::Integral: {
1266 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1267 llvm::DITemplateValueParameter TVP =
1268 DBuilder.createTemplateValueParameter(
1269 TheCU, Name, TTy,
1270 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1271 TemplateParams.push_back(TVP);
1272 } break;
1273 case TemplateArgument::Declaration: {
1274 const ValueDecl *D = TA.getAsDecl();
1275 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1276 llvm::DIType TTy = getOrCreateType(T, Unit);
1277 llvm::Constant *V = nullptr;
1278 const CXXMethodDecl *MD;
1279 // Variable pointer template parameters have a value that is the address
1280 // of the variable.
1281 if (const auto *VD = dyn_cast<VarDecl>(D))
1282 V = CGM.GetAddrOfGlobalVar(VD);
1283 // Member function pointers have special support for building them, though
1284 // this is currently unsupported in LLVM CodeGen.
1285 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1286 V = CGM.getCXXABI().EmitMemberPointer(MD);
1287 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1288 V = CGM.GetAddrOfFunction(FD);
1289 // Member data pointers have special handling too to compute the fixed
1290 // offset within the object.
1291 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1292 // These five lines (& possibly the above member function pointer
1293 // handling) might be able to be refactored to use similar code in
1294 // CodeGenModule::getMemberPointerConstant
1295 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1296 CharUnits chars =
1297 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1298 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1299 }
1300 llvm::DITemplateValueParameter TVP =
1301 DBuilder.createTemplateValueParameter(
1302 TheCU, Name, TTy,
1303 cast_or_null<llvm::Constant>(V->stripPointerCasts()));
1304 TemplateParams.push_back(TVP);
1305 } break;
1306 case TemplateArgument::NullPtr: {
1307 QualType T = TA.getNullPtrType();
1308 llvm::DIType TTy = getOrCreateType(T, Unit);
1309 llvm::Constant *V = nullptr;
1310 // Special case member data pointer null values since they're actually -1
1311 // instead of zero.
1312 if (const MemberPointerType *MPT =
1313 dyn_cast<MemberPointerType>(T.getTypePtr()))
1314 // But treat member function pointers as simple zero integers because
1315 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1316 // CodeGen grows handling for values of non-null member function
1317 // pointers then perhaps we could remove this special case and rely on
1318 // EmitNullMemberPointer for member function pointers.
1319 if (MPT->isMemberDataPointer())
1320 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1321 if (!V)
1322 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1323 llvm::DITemplateValueParameter TVP =
1324 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1325 cast<llvm::Constant>(V));
1326 TemplateParams.push_back(TVP);
1327 } break;
1328 case TemplateArgument::Template: {
1329 llvm::DITemplateValueParameter
1330 TVP = DBuilder.createTemplateTemplateParameter(
1331 TheCU, Name, llvm::DIType(),
1332 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString());
1333 TemplateParams.push_back(TVP);
1334 } break;
1335 case TemplateArgument::Pack: {
1336 llvm::DITemplateValueParameter TVP = DBuilder.createTemplateParameterPack(
1337 TheCU, Name, llvm::DIType(),
1338 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit));
1339 TemplateParams.push_back(TVP);
1340 } break;
1341 case TemplateArgument::Expression: {
1342 const Expr *E = TA.getAsExpr();
1343 QualType T = E->getType();
1344 if (E->isGLValue())
1345 T = CGM.getContext().getLValueReferenceType(T);
1346 llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1347 assert(V && "Expression in template argument isn't constant");
1348 llvm::DIType TTy = getOrCreateType(T, Unit);
1349 llvm::DITemplateValueParameter TVP =
1350 DBuilder.createTemplateValueParameter(
1351 TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts()));
1352 TemplateParams.push_back(TVP);
1353 } break;
1354 // And the following should never occur:
1355 case TemplateArgument::TemplateExpansion:
1356 case TemplateArgument::Null:
1357 llvm_unreachable(
1358 "These argument types shouldn't exist in concrete types");
1359 }
1360 }
1361 return DBuilder.getOrCreateArray(TemplateParams);
1362 }
1363
1364 /// CollectFunctionTemplateParams - A helper function to collect debug
1365 /// info for function template parameters.
CollectFunctionTemplateParams(const FunctionDecl * FD,llvm::DIFile Unit)1366 llvm::DIArray CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1367 llvm::DIFile Unit) {
1368 if (FD->getTemplatedKind() ==
1369 FunctionDecl::TK_FunctionTemplateSpecialization) {
1370 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1371 ->getTemplate()
1372 ->getTemplateParameters();
1373 return CollectTemplateParams(
1374 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1375 }
1376 return llvm::DIArray();
1377 }
1378
1379 /// CollectCXXTemplateParams - A helper function to collect debug info for
1380 /// template parameters.
CollectCXXTemplateParams(const ClassTemplateSpecializationDecl * TSpecial,llvm::DIFile Unit)1381 llvm::DIArray CGDebugInfo::CollectCXXTemplateParams(
1382 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile Unit) {
1383 // Always get the full list of parameters, not just the ones from
1384 // the specialization.
1385 TemplateParameterList *TPList =
1386 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1387 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1388 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1389 }
1390
1391 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
getOrCreateVTablePtrType(llvm::DIFile Unit)1392 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1393 if (VTablePtrType)
1394 return VTablePtrType;
1395
1396 ASTContext &Context = CGM.getContext();
1397
1398 /* Function type */
1399 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1400 llvm::DITypeArray SElements = DBuilder.getOrCreateTypeArray(STy);
1401 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1402 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1403 llvm::DIType vtbl_ptr_type =
1404 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1405 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1406 return VTablePtrType;
1407 }
1408
1409 /// getVTableName - Get vtable name for the given Class.
getVTableName(const CXXRecordDecl * RD)1410 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1411 // Copy the gdb compatible name on the side and use its reference.
1412 return internString("_vptr$", RD->getNameAsString());
1413 }
1414
1415 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1416 /// debug info entry in EltTys vector.
CollectVTableInfo(const CXXRecordDecl * RD,llvm::DIFile Unit,SmallVectorImpl<llvm::Metadata * > & EltTys)1417 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1418 SmallVectorImpl<llvm::Metadata *> &EltTys) {
1419 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1420
1421 // If there is a primary base then it will hold vtable info.
1422 if (RL.getPrimaryBase())
1423 return;
1424
1425 // If this class is not dynamic then there is not any vtable info to collect.
1426 if (!RD->isDynamicClass())
1427 return;
1428
1429 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1430 llvm::DIType VPTR = DBuilder.createMemberType(
1431 Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1432 llvm::DebugNode::FlagArtificial, getOrCreateVTablePtrType(Unit));
1433 EltTys.push_back(VPTR);
1434 }
1435
1436 /// getOrCreateRecordType - Emit record type's standalone debug info.
getOrCreateRecordType(QualType RTy,SourceLocation Loc)1437 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1438 SourceLocation Loc) {
1439 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1440 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1441 return T;
1442 }
1443
1444 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1445 /// debug info.
getOrCreateInterfaceType(QualType D,SourceLocation Loc)1446 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1447 SourceLocation Loc) {
1448 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1449 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1450 RetainedTypes.push_back(D.getAsOpaquePtr());
1451 return T;
1452 }
1453
completeType(const EnumDecl * ED)1454 void CGDebugInfo::completeType(const EnumDecl *ED) {
1455 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1456 return;
1457 QualType Ty = CGM.getContext().getEnumType(ED);
1458 void *TyPtr = Ty.getAsOpaquePtr();
1459 auto I = TypeCache.find(TyPtr);
1460 if (I == TypeCache.end() || !cast<llvm::MDType>(I->second)->isForwardDecl())
1461 return;
1462 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1463 assert(!Res->isForwardDecl());
1464 TypeCache[TyPtr].reset(Res);
1465 }
1466
completeType(const RecordDecl * RD)1467 void CGDebugInfo::completeType(const RecordDecl *RD) {
1468 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1469 !CGM.getLangOpts().CPlusPlus)
1470 completeRequiredType(RD);
1471 }
1472
completeRequiredType(const RecordDecl * RD)1473 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1474 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1475 return;
1476
1477 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1478 if (CXXDecl->isDynamicClass())
1479 return;
1480
1481 QualType Ty = CGM.getContext().getRecordType(RD);
1482 llvm::DIType T = getTypeOrNull(Ty);
1483 if (T && T->isForwardDecl())
1484 completeClassData(RD);
1485 }
1486
completeClassData(const RecordDecl * RD)1487 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1488 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1489 return;
1490 QualType Ty = CGM.getContext().getRecordType(RD);
1491 void *TyPtr = Ty.getAsOpaquePtr();
1492 auto I = TypeCache.find(TyPtr);
1493 if (I != TypeCache.end() && !cast<llvm::MDType>(I->second)->isForwardDecl())
1494 return;
1495 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1496 assert(!Res->isForwardDecl());
1497 TypeCache[TyPtr].reset(Res);
1498 }
1499
hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,CXXRecordDecl::method_iterator End)1500 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1501 CXXRecordDecl::method_iterator End) {
1502 for (; I != End; ++I)
1503 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1504 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1505 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1506 return true;
1507 return false;
1508 }
1509
shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,const RecordDecl * RD,const LangOptions & LangOpts)1510 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1511 const RecordDecl *RD,
1512 const LangOptions &LangOpts) {
1513 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1514 return false;
1515
1516 if (!LangOpts.CPlusPlus)
1517 return false;
1518
1519 if (!RD->isCompleteDefinitionRequired())
1520 return true;
1521
1522 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1523
1524 if (!CXXDecl)
1525 return false;
1526
1527 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1528 return true;
1529
1530 TemplateSpecializationKind Spec = TSK_Undeclared;
1531 if (const ClassTemplateSpecializationDecl *SD =
1532 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1533 Spec = SD->getSpecializationKind();
1534
1535 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1536 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1537 CXXDecl->method_end()))
1538 return true;
1539
1540 return false;
1541 }
1542
1543 /// CreateType - get structure or union type.
CreateType(const RecordType * Ty)1544 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1545 RecordDecl *RD = Ty->getDecl();
1546 llvm::DIType T = cast_or_null<llvm::MDType>(getTypeOrNull(QualType(Ty, 0)));
1547 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
1548 if (!T)
1549 T = getOrCreateRecordFwdDecl(
1550 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
1551 return T;
1552 }
1553
1554 return CreateTypeDefinition(Ty);
1555 }
1556
CreateTypeDefinition(const RecordType * Ty)1557 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1558 RecordDecl *RD = Ty->getDecl();
1559
1560 // Get overall information about the record type for the debug info.
1561 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1562
1563 // Records and classes and unions can all be recursive. To handle them, we
1564 // first generate a debug descriptor for the struct as a forward declaration.
1565 // Then (if it is a definition) we go through and get debug info for all of
1566 // its members. Finally, we create a descriptor for the complete type (which
1567 // may refer to the forward decl if the struct is recursive) and replace all
1568 // uses of the forward declaration with the final definition.
1569
1570 auto *FwdDecl =
1571 cast<llvm::MDCompositeType>(getOrCreateLimitedType(Ty, DefUnit));
1572
1573 const RecordDecl *D = RD->getDefinition();
1574 if (!D || !D->isCompleteDefinition())
1575 return FwdDecl;
1576
1577 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1578 CollectContainingType(CXXDecl, FwdDecl);
1579
1580 // Push the struct on region stack.
1581 LexicalBlockStack.emplace_back(&*FwdDecl);
1582 RegionMap[Ty->getDecl()].reset(FwdDecl);
1583
1584 // Convert all the elements.
1585 SmallVector<llvm::Metadata *, 16> EltTys;
1586 // what about nested types?
1587
1588 // Note: The split of CXXDecl information here is intentional, the
1589 // gdb tests will depend on a certain ordering at printout. The debug
1590 // information offsets are still correct if we merge them all together
1591 // though.
1592 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1593 if (CXXDecl) {
1594 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1595 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1596 }
1597
1598 // Collect data fields (including static variables and any initializers).
1599 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1600 if (CXXDecl)
1601 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1602
1603 LexicalBlockStack.pop_back();
1604 RegionMap.erase(Ty->getDecl());
1605
1606 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1607 DBuilder.replaceArrays(FwdDecl, Elements);
1608
1609 if (FwdDecl->isTemporary())
1610 FwdDecl =
1611 llvm::MDNode::replaceWithPermanent(llvm::TempMDCompositeType(FwdDecl));
1612
1613 RegionMap[Ty->getDecl()].reset(FwdDecl);
1614 return FwdDecl;
1615 }
1616
1617 /// CreateType - get objective-c object type.
CreateType(const ObjCObjectType * Ty,llvm::DIFile Unit)1618 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1619 llvm::DIFile Unit) {
1620 // Ignore protocols.
1621 return getOrCreateType(Ty->getBaseType(), Unit);
1622 }
1623
1624 /// \return true if Getter has the default name for the property PD.
hasDefaultGetterName(const ObjCPropertyDecl * PD,const ObjCMethodDecl * Getter)1625 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1626 const ObjCMethodDecl *Getter) {
1627 assert(PD);
1628 if (!Getter)
1629 return true;
1630
1631 assert(Getter->getDeclName().isObjCZeroArgSelector());
1632 return PD->getName() ==
1633 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1634 }
1635
1636 /// \return true if Setter has the default name for the property PD.
hasDefaultSetterName(const ObjCPropertyDecl * PD,const ObjCMethodDecl * Setter)1637 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1638 const ObjCMethodDecl *Setter) {
1639 assert(PD);
1640 if (!Setter)
1641 return true;
1642
1643 assert(Setter->getDeclName().isObjCOneArgSelector());
1644 return SelectorTable::constructSetterName(PD->getName()) ==
1645 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1646 }
1647
1648 /// CreateType - get objective-c interface type.
CreateType(const ObjCInterfaceType * Ty,llvm::DIFile Unit)1649 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1650 llvm::DIFile Unit) {
1651 ObjCInterfaceDecl *ID = Ty->getDecl();
1652 if (!ID)
1653 return llvm::DIType();
1654
1655 // Get overall information about the record type for the debug info.
1656 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1657 unsigned Line = getLineNumber(ID->getLocation());
1658 auto RuntimeLang =
1659 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1660
1661 // If this is just a forward declaration return a special forward-declaration
1662 // debug type since we won't be able to lay out the entire type.
1663 ObjCInterfaceDecl *Def = ID->getDefinition();
1664 if (!Def || !Def->getImplementation()) {
1665 llvm::DIType FwdDecl = DBuilder.createReplaceableCompositeType(
1666 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1667 RuntimeLang);
1668 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1669 return FwdDecl;
1670 }
1671
1672 return CreateTypeDefinition(Ty, Unit);
1673 }
1674
CreateTypeDefinition(const ObjCInterfaceType * Ty,llvm::DIFile Unit)1675 llvm::DIType CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
1676 llvm::DIFile Unit) {
1677 ObjCInterfaceDecl *ID = Ty->getDecl();
1678 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1679 unsigned Line = getLineNumber(ID->getLocation());
1680 unsigned RuntimeLang = TheCU->getSourceLanguage();
1681
1682 // Bit size, align and offset of the type.
1683 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1684 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1685
1686 unsigned Flags = 0;
1687 if (ID->getImplementation())
1688 Flags |= llvm::DebugNode::FlagObjcClassComplete;
1689
1690 llvm::MDCompositeType *RealDecl = DBuilder.createStructType(
1691 Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, llvm::DIType(),
1692 llvm::DIArray(), RuntimeLang);
1693
1694 QualType QTy(Ty, 0);
1695 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
1696
1697 // Push the struct on region stack.
1698 LexicalBlockStack.emplace_back(RealDecl);
1699 RegionMap[Ty->getDecl()].reset(RealDecl);
1700
1701 // Convert all the elements.
1702 SmallVector<llvm::Metadata *, 16> EltTys;
1703
1704 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1705 if (SClass) {
1706 llvm::DIType SClassTy =
1707 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1708 if (!SClassTy)
1709 return llvm::DIType();
1710
1711 llvm::DIType InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1712 EltTys.push_back(InhTag);
1713 }
1714
1715 // Create entries for all of the properties.
1716 for (const auto *PD : ID->properties()) {
1717 SourceLocation Loc = PD->getLocation();
1718 llvm::DIFile PUnit = getOrCreateFile(Loc);
1719 unsigned PLine = getLineNumber(Loc);
1720 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1721 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1722 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
1723 PD->getName(), PUnit, PLine,
1724 hasDefaultGetterName(PD, Getter) ? ""
1725 : getSelectorName(PD->getGetterName()),
1726 hasDefaultSetterName(PD, Setter) ? ""
1727 : getSelectorName(PD->getSetterName()),
1728 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
1729 EltTys.push_back(PropertyNode);
1730 }
1731
1732 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1733 unsigned FieldNo = 0;
1734 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1735 Field = Field->getNextIvar(), ++FieldNo) {
1736 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1737 if (!FieldTy)
1738 return llvm::DIType();
1739
1740 StringRef FieldName = Field->getName();
1741
1742 // Ignore unnamed fields.
1743 if (FieldName.empty())
1744 continue;
1745
1746 // Get the location for the field.
1747 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1748 unsigned FieldLine = getLineNumber(Field->getLocation());
1749 QualType FType = Field->getType();
1750 uint64_t FieldSize = 0;
1751 unsigned FieldAlign = 0;
1752
1753 if (!FType->isIncompleteArrayType()) {
1754
1755 // Bit size, align and offset of the type.
1756 FieldSize = Field->isBitField()
1757 ? Field->getBitWidthValue(CGM.getContext())
1758 : CGM.getContext().getTypeSize(FType);
1759 FieldAlign = CGM.getContext().getTypeAlign(FType);
1760 }
1761
1762 uint64_t FieldOffset;
1763 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1764 // We don't know the runtime offset of an ivar if we're using the
1765 // non-fragile ABI. For bitfields, use the bit offset into the first
1766 // byte of storage of the bitfield. For other fields, use zero.
1767 if (Field->isBitField()) {
1768 FieldOffset =
1769 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
1770 FieldOffset %= CGM.getContext().getCharWidth();
1771 } else {
1772 FieldOffset = 0;
1773 }
1774 } else {
1775 FieldOffset = RL.getFieldOffset(FieldNo);
1776 }
1777
1778 unsigned Flags = 0;
1779 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1780 Flags = llvm::DebugNode::FlagProtected;
1781 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1782 Flags = llvm::DebugNode::FlagPrivate;
1783 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
1784 Flags = llvm::DebugNode::FlagPublic;
1785
1786 llvm::MDNode *PropertyNode = nullptr;
1787 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1788 if (ObjCPropertyImplDecl *PImpD =
1789 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1790 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1791 SourceLocation Loc = PD->getLocation();
1792 llvm::DIFile PUnit = getOrCreateFile(Loc);
1793 unsigned PLine = getLineNumber(Loc);
1794 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1795 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1796 PropertyNode = DBuilder.createObjCProperty(
1797 PD->getName(), PUnit, PLine,
1798 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
1799 PD->getGetterName()),
1800 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
1801 PD->getSetterName()),
1802 PD->getPropertyAttributes(),
1803 getOrCreateType(PD->getType(), PUnit));
1804 }
1805 }
1806 }
1807 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
1808 FieldSize, FieldAlign, FieldOffset, Flags,
1809 FieldTy, PropertyNode);
1810 EltTys.push_back(FieldTy);
1811 }
1812
1813 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1814 DBuilder.replaceArrays(RealDecl, Elements);
1815
1816 LexicalBlockStack.pop_back();
1817 return RealDecl;
1818 }
1819
CreateType(const VectorType * Ty,llvm::DIFile Unit)1820 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1821 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1822 int64_t Count = Ty->getNumElements();
1823 if (Count == 0)
1824 // If number of elements are not known then this is an unbounded array.
1825 // Use Count == -1 to express such arrays.
1826 Count = -1;
1827
1828 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1829 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1830
1831 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1832 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1833
1834 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1835 }
1836
CreateType(const ArrayType * Ty,llvm::DIFile Unit)1837 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile Unit) {
1838 uint64_t Size;
1839 uint64_t Align;
1840
1841 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1842 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1843 Size = 0;
1844 Align =
1845 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1846 } else if (Ty->isIncompleteArrayType()) {
1847 Size = 0;
1848 if (Ty->getElementType()->isIncompleteType())
1849 Align = 0;
1850 else
1851 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1852 } else if (Ty->isIncompleteType()) {
1853 Size = 0;
1854 Align = 0;
1855 } else {
1856 // Size and align of the whole array, not the element type.
1857 Size = CGM.getContext().getTypeSize(Ty);
1858 Align = CGM.getContext().getTypeAlign(Ty);
1859 }
1860
1861 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1862 // interior arrays, do we care? Why aren't nested arrays represented the
1863 // obvious/recursive way?
1864 SmallVector<llvm::Metadata *, 8> Subscripts;
1865 QualType EltTy(Ty, 0);
1866 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1867 // If the number of elements is known, then count is that number. Otherwise,
1868 // it's -1. This allows us to represent a subrange with an array of 0
1869 // elements, like this:
1870 //
1871 // struct foo {
1872 // int x[0];
1873 // };
1874 int64_t Count = -1; // Count == -1 is an unbounded array.
1875 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1876 Count = CAT->getSize().getZExtValue();
1877
1878 // FIXME: Verify this is right for VLAs.
1879 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1880 EltTy = Ty->getElementType();
1881 }
1882
1883 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1884
1885 llvm::DIType DbgTy = DBuilder.createArrayType(
1886 Size, Align, getOrCreateType(EltTy, Unit), SubscriptArray);
1887 return DbgTy;
1888 }
1889
CreateType(const LValueReferenceType * Ty,llvm::DIFile Unit)1890 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1891 llvm::DIFile Unit) {
1892 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
1893 Ty->getPointeeType(), Unit);
1894 }
1895
CreateType(const RValueReferenceType * Ty,llvm::DIFile Unit)1896 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1897 llvm::DIFile Unit) {
1898 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
1899 Ty->getPointeeType(), Unit);
1900 }
1901
CreateType(const MemberPointerType * Ty,llvm::DIFile U)1902 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1903 llvm::DIFile U) {
1904 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1905 if (!Ty->getPointeeType()->isFunctionType())
1906 return DBuilder.createMemberPointerType(
1907 getOrCreateType(Ty->getPointeeType(), U), ClassType,
1908 CGM.getContext().getTypeSize(Ty));
1909
1910 const FunctionProtoType *FPT =
1911 Ty->getPointeeType()->getAs<FunctionProtoType>();
1912 return DBuilder.createMemberPointerType(
1913 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
1914 Ty->getClass(), FPT->getTypeQuals())),
1915 FPT, U),
1916 ClassType, CGM.getContext().getTypeSize(Ty));
1917 }
1918
CreateType(const AtomicType * Ty,llvm::DIFile U)1919 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile U) {
1920 // Ignore the atomic wrapping
1921 // FIXME: What is the correct representation?
1922 return getOrCreateType(Ty->getValueType(), U);
1923 }
1924
1925 /// CreateEnumType - get enumeration type.
CreateEnumType(const EnumType * Ty)1926 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1927 const EnumDecl *ED = Ty->getDecl();
1928 uint64_t Size = 0;
1929 uint64_t Align = 0;
1930 if (!ED->getTypeForDecl()->isIncompleteType()) {
1931 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1932 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1933 }
1934
1935 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1936
1937 // If this is just a forward declaration, construct an appropriately
1938 // marked node and just return it.
1939 if (!ED->getDefinition()) {
1940 llvm::MDScope *EDContext =
1941 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1942 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1943 unsigned Line = getLineNumber(ED->getLocation());
1944 StringRef EDName = ED->getName();
1945 llvm::DIType RetTy = DBuilder.createReplaceableCompositeType(
1946 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1947 0, Size, Align, llvm::DebugNode::FlagFwdDecl, FullName);
1948 ReplaceMap.emplace_back(
1949 std::piecewise_construct, std::make_tuple(Ty),
1950 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1951 return RetTy;
1952 }
1953
1954 return CreateTypeDefinition(Ty);
1955 }
1956
CreateTypeDefinition(const EnumType * Ty)1957 llvm::DIType CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1958 const EnumDecl *ED = Ty->getDecl();
1959 uint64_t Size = 0;
1960 uint64_t Align = 0;
1961 if (!ED->getTypeForDecl()->isIncompleteType()) {
1962 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1963 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1964 }
1965
1966 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1967
1968 // Create DIEnumerator elements for each enumerator.
1969 SmallVector<llvm::Metadata *, 16> Enumerators;
1970 ED = ED->getDefinition();
1971 for (const auto *Enum : ED->enumerators()) {
1972 Enumerators.push_back(DBuilder.createEnumerator(
1973 Enum->getName(), Enum->getInitVal().getSExtValue()));
1974 }
1975
1976 // Return a CompositeType for the enum itself.
1977 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1978
1979 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1980 unsigned Line = getLineNumber(ED->getLocation());
1981 llvm::MDScope *EnumContext =
1982 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1983 llvm::DIType ClassTy = ED->isFixed()
1984 ? getOrCreateType(ED->getIntegerType(), DefUnit)
1985 : llvm::DIType();
1986 llvm::DIType DbgTy =
1987 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1988 Size, Align, EltArray, ClassTy, FullName);
1989 return DbgTy;
1990 }
1991
UnwrapTypeForDebugInfo(QualType T,const ASTContext & C)1992 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1993 Qualifiers Quals;
1994 do {
1995 Qualifiers InnerQuals = T.getLocalQualifiers();
1996 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1997 // that is already there.
1998 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1999 Quals += InnerQuals;
2000 QualType LastT = T;
2001 switch (T->getTypeClass()) {
2002 default:
2003 return C.getQualifiedType(T.getTypePtr(), Quals);
2004 case Type::TemplateSpecialization: {
2005 const auto *Spec = cast<TemplateSpecializationType>(T);
2006 if (Spec->isTypeAlias())
2007 return C.getQualifiedType(T.getTypePtr(), Quals);
2008 T = Spec->desugar();
2009 break;
2010 }
2011 case Type::TypeOfExpr:
2012 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2013 break;
2014 case Type::TypeOf:
2015 T = cast<TypeOfType>(T)->getUnderlyingType();
2016 break;
2017 case Type::Decltype:
2018 T = cast<DecltypeType>(T)->getUnderlyingType();
2019 break;
2020 case Type::UnaryTransform:
2021 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2022 break;
2023 case Type::Attributed:
2024 T = cast<AttributedType>(T)->getEquivalentType();
2025 break;
2026 case Type::Elaborated:
2027 T = cast<ElaboratedType>(T)->getNamedType();
2028 break;
2029 case Type::Paren:
2030 T = cast<ParenType>(T)->getInnerType();
2031 break;
2032 case Type::SubstTemplateTypeParm:
2033 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2034 break;
2035 case Type::Auto:
2036 QualType DT = cast<AutoType>(T)->getDeducedType();
2037 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2038 T = DT;
2039 break;
2040 }
2041
2042 assert(T != LastT && "Type unwrapping failed to unwrap!");
2043 (void)LastT;
2044 } while (true);
2045 }
2046
2047 /// getType - Get the type from the cache or return null type if it doesn't
2048 /// exist.
getTypeOrNull(QualType Ty)2049 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2050
2051 // Unwrap the type as needed for debug information.
2052 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2053
2054 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2055 if (it != TypeCache.end()) {
2056 // Verify that the debug info still exists.
2057 if (llvm::Metadata *V = it->second)
2058 return cast<llvm::MDType>(V);
2059 }
2060
2061 return nullptr;
2062 }
2063
completeTemplateDefinition(const ClassTemplateSpecializationDecl & SD)2064 void CGDebugInfo::completeTemplateDefinition(
2065 const ClassTemplateSpecializationDecl &SD) {
2066 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2067 return;
2068
2069 completeClassData(&SD);
2070 // In case this type has no member function definitions being emitted, ensure
2071 // it is retained
2072 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2073 }
2074
2075 /// getOrCreateType - Get the type from the cache or create a new
2076 /// one if necessary.
getOrCreateType(QualType Ty,llvm::DIFile Unit)2077 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
2078 if (Ty.isNull())
2079 return llvm::DIType();
2080
2081 // Unwrap the type as needed for debug information.
2082 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2083
2084 if (llvm::DIType T = getTypeOrNull(Ty))
2085 return T;
2086
2087 // Otherwise create the type.
2088 llvm::DIType Res = CreateTypeNode(Ty, Unit);
2089 void *TyPtr = Ty.getAsOpaquePtr();
2090
2091 // And update the type cache.
2092 TypeCache[TyPtr].reset(Res);
2093
2094 return Res;
2095 }
2096
2097 /// Currently the checksum of an interface includes the number of
2098 /// ivars and property accessors.
Checksum(const ObjCInterfaceDecl * ID)2099 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2100 // The assumption is that the number of ivars can only increase
2101 // monotonically, so it is safe to just use their current number as
2102 // a checksum.
2103 unsigned Sum = 0;
2104 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2105 Ivar != nullptr; Ivar = Ivar->getNextIvar())
2106 ++Sum;
2107
2108 return Sum;
2109 }
2110
getObjCInterfaceDecl(QualType Ty)2111 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2112 switch (Ty->getTypeClass()) {
2113 case Type::ObjCObjectPointer:
2114 return getObjCInterfaceDecl(
2115 cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2116 case Type::ObjCInterface:
2117 return cast<ObjCInterfaceType>(Ty)->getDecl();
2118 default:
2119 return nullptr;
2120 }
2121 }
2122
2123 /// CreateTypeNode - Create a new debug type node.
CreateTypeNode(QualType Ty,llvm::DIFile Unit)2124 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
2125 // Handle qualifiers, which recursively handles what they refer to.
2126 if (Ty.hasLocalQualifiers())
2127 return CreateQualifiedType(Ty, Unit);
2128
2129 // Work out details of type.
2130 switch (Ty->getTypeClass()) {
2131 #define TYPE(Class, Base)
2132 #define ABSTRACT_TYPE(Class, Base)
2133 #define NON_CANONICAL_TYPE(Class, Base)
2134 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2135 #include "clang/AST/TypeNodes.def"
2136 llvm_unreachable("Dependent types cannot show up in debug information");
2137
2138 case Type::ExtVector:
2139 case Type::Vector:
2140 return CreateType(cast<VectorType>(Ty), Unit);
2141 case Type::ObjCObjectPointer:
2142 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2143 case Type::ObjCObject:
2144 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2145 case Type::ObjCInterface:
2146 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2147 case Type::Builtin:
2148 return CreateType(cast<BuiltinType>(Ty));
2149 case Type::Complex:
2150 return CreateType(cast<ComplexType>(Ty));
2151 case Type::Pointer:
2152 return CreateType(cast<PointerType>(Ty), Unit);
2153 case Type::Adjusted:
2154 case Type::Decayed:
2155 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2156 return CreateType(
2157 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2158 case Type::BlockPointer:
2159 return CreateType(cast<BlockPointerType>(Ty), Unit);
2160 case Type::Typedef:
2161 return CreateType(cast<TypedefType>(Ty), Unit);
2162 case Type::Record:
2163 return CreateType(cast<RecordType>(Ty));
2164 case Type::Enum:
2165 return CreateEnumType(cast<EnumType>(Ty));
2166 case Type::FunctionProto:
2167 case Type::FunctionNoProto:
2168 return CreateType(cast<FunctionType>(Ty), Unit);
2169 case Type::ConstantArray:
2170 case Type::VariableArray:
2171 case Type::IncompleteArray:
2172 return CreateType(cast<ArrayType>(Ty), Unit);
2173
2174 case Type::LValueReference:
2175 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2176 case Type::RValueReference:
2177 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2178
2179 case Type::MemberPointer:
2180 return CreateType(cast<MemberPointerType>(Ty), Unit);
2181
2182 case Type::Atomic:
2183 return CreateType(cast<AtomicType>(Ty), Unit);
2184
2185 case Type::TemplateSpecialization:
2186 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2187
2188 case Type::Auto:
2189 case Type::Attributed:
2190 case Type::Elaborated:
2191 case Type::Paren:
2192 case Type::SubstTemplateTypeParm:
2193 case Type::TypeOfExpr:
2194 case Type::TypeOf:
2195 case Type::Decltype:
2196 case Type::UnaryTransform:
2197 case Type::PackExpansion:
2198 break;
2199 }
2200
2201 llvm_unreachable("type should have been unwrapped!");
2202 }
2203
2204 /// getOrCreateLimitedType - Get the type from the cache or create a new
2205 /// limited type if necessary.
getOrCreateLimitedType(const RecordType * Ty,llvm::DIFile Unit)2206 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2207 llvm::DIFile Unit) {
2208 QualType QTy(Ty, 0);
2209
2210 auto *T = cast_or_null<llvm::MDCompositeTypeBase>(getTypeOrNull(QTy));
2211
2212 // We may have cached a forward decl when we could have created
2213 // a non-forward decl. Go ahead and create a non-forward decl
2214 // now.
2215 if (T && !T->isForwardDecl())
2216 return T;
2217
2218 // Otherwise create the type.
2219 llvm::MDCompositeType *Res = CreateLimitedType(Ty);
2220
2221 // Propagate members from the declaration to the definition
2222 // CreateType(const RecordType*) will overwrite this with the members in the
2223 // correct order if the full type is needed.
2224 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DIArray());
2225
2226 // And update the type cache.
2227 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2228 return Res;
2229 }
2230
2231 // TODO: Currently used for context chains when limiting debug info.
CreateLimitedType(const RecordType * Ty)2232 llvm::MDCompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2233 RecordDecl *RD = Ty->getDecl();
2234
2235 // Get overall information about the record type for the debug info.
2236 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2237 unsigned Line = getLineNumber(RD->getLocation());
2238 StringRef RDName = getClassName(RD);
2239
2240 llvm::MDScope *RDContext =
2241 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2242
2243 // If we ended up creating the type during the context chain construction,
2244 // just return that.
2245 auto *T = cast_or_null<llvm::MDCompositeType>(
2246 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2247 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2248 return T;
2249
2250 // If this is just a forward or incomplete declaration, construct an
2251 // appropriately marked node and just return it.
2252 const RecordDecl *D = RD->getDefinition();
2253 if (!D || !D->isCompleteDefinition())
2254 return getOrCreateRecordFwdDecl(Ty, RDContext);
2255
2256 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2257 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2258
2259 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2260
2261 llvm::MDCompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2262 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
2263 FullName);
2264
2265 RegionMap[Ty->getDecl()].reset(RealDecl);
2266 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2267
2268 if (const ClassTemplateSpecializationDecl *TSpecial =
2269 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2270 DBuilder.replaceArrays(RealDecl, llvm::DIArray(),
2271 CollectCXXTemplateParams(TSpecial, DefUnit));
2272 return RealDecl;
2273 }
2274
CollectContainingType(const CXXRecordDecl * RD,llvm::MDCompositeType * RealDecl)2275 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2276 llvm::MDCompositeType *RealDecl) {
2277 // A class's primary base or the class itself contains the vtable.
2278 llvm::MDCompositeType *ContainingType = nullptr;
2279 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2280 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2281 // Seek non-virtual primary base root.
2282 while (1) {
2283 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2284 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2285 if (PBT && !BRL.isPrimaryBaseVirtual())
2286 PBase = PBT;
2287 else
2288 break;
2289 }
2290 ContainingType = cast<llvm::MDCompositeType>(
2291 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2292 getOrCreateFile(RD->getLocation())));
2293 } else if (RD->isDynamicClass())
2294 ContainingType = RealDecl;
2295
2296 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2297 }
2298
2299 /// CreateMemberType - Create new member and increase Offset by FType's size.
CreateMemberType(llvm::DIFile Unit,QualType FType,StringRef Name,uint64_t * Offset)2300 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2301 StringRef Name, uint64_t *Offset) {
2302 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2303 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2304 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2305 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
2306 FieldAlign, *Offset, 0, FieldTy);
2307 *Offset += FieldSize;
2308 return Ty;
2309 }
2310
collectFunctionDeclProps(GlobalDecl GD,llvm::DIFile Unit,StringRef & Name,StringRef & LinkageName,llvm::MDScope * & FDContext,llvm::DIArray & TParamsArray,unsigned & Flags)2311 void CGDebugInfo::collectFunctionDeclProps(
2312 GlobalDecl GD, llvm::DIFile Unit, StringRef &Name, StringRef &LinkageName,
2313 llvm::MDScope *&FDContext, llvm::DIArray &TParamsArray, unsigned &Flags) {
2314 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2315 Name = getFunctionName(FD);
2316 // Use mangled name as linkage name for C/C++ functions.
2317 if (FD->hasPrototype()) {
2318 LinkageName = CGM.getMangledName(GD);
2319 Flags |= llvm::DebugNode::FlagPrototyped;
2320 }
2321 // No need to replicate the linkage name if it isn't different from the
2322 // subprogram name, no need to have it at all unless coverage is enabled or
2323 // debug is set to more than just line tables.
2324 if (LinkageName == Name ||
2325 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2326 !CGM.getCodeGenOpts().EmitGcovNotes &&
2327 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2328 LinkageName = StringRef();
2329
2330 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2331 if (const NamespaceDecl *NSDecl =
2332 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2333 FDContext = getOrCreateNameSpace(NSDecl);
2334 else if (const RecordDecl *RDecl =
2335 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2336 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2337 // Collect template parameters.
2338 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2339 }
2340 }
2341
collectVarDeclProps(const VarDecl * VD,llvm::DIFile & Unit,unsigned & LineNo,QualType & T,StringRef & Name,StringRef & LinkageName,llvm::MDScope * & VDContext)2342 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile &Unit,
2343 unsigned &LineNo, QualType &T,
2344 StringRef &Name, StringRef &LinkageName,
2345 llvm::MDScope *&VDContext) {
2346 Unit = getOrCreateFile(VD->getLocation());
2347 LineNo = getLineNumber(VD->getLocation());
2348
2349 setLocation(VD->getLocation());
2350
2351 T = VD->getType();
2352 if (T->isIncompleteArrayType()) {
2353 // CodeGen turns int[] into int[1] so we'll do the same here.
2354 llvm::APInt ConstVal(32, 1);
2355 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2356
2357 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2358 ArrayType::Normal, 0);
2359 }
2360
2361 Name = VD->getName();
2362 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2363 !isa<ObjCMethodDecl>(VD->getDeclContext()))
2364 LinkageName = CGM.getMangledName(VD);
2365 if (LinkageName == Name)
2366 LinkageName = StringRef();
2367
2368 // Since we emit declarations (DW_AT_members) for static members, place the
2369 // definition of those static members in the namespace they were declared in
2370 // in the source code (the lexical decl context).
2371 // FIXME: Generalize this for even non-member global variables where the
2372 // declaration and definition may have different lexical decl contexts, once
2373 // we have support for emitting declarations of (non-member) global variables.
2374 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2375 : VD->getDeclContext();
2376 // When a record type contains an in-line initialization of a static data
2377 // member, and the record type is marked as __declspec(dllexport), an implicit
2378 // definition of the member will be created in the record context. DWARF
2379 // doesn't seem to have a nice way to describe this in a form that consumers
2380 // are likely to understand, so fake the "normal" situation of a definition
2381 // outside the class by putting it in the global scope.
2382 if (DC->isRecord())
2383 DC = CGM.getContext().getTranslationUnitDecl();
2384 VDContext = getContextDescriptor(dyn_cast<Decl>(DC));
2385 }
2386
2387 llvm::DISubprogram
getFunctionForwardDeclaration(const FunctionDecl * FD)2388 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2389 llvm::DIArray TParamsArray;
2390 StringRef Name, LinkageName;
2391 unsigned Flags = 0;
2392 SourceLocation Loc = FD->getLocation();
2393 llvm::DIFile Unit = getOrCreateFile(Loc);
2394 llvm::MDScope *DContext = Unit;
2395 unsigned Line = getLineNumber(Loc);
2396
2397 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2398 TParamsArray, Flags);
2399 // Build function type.
2400 SmallVector<QualType, 16> ArgTypes;
2401 for (const ParmVarDecl *Parm: FD->parameters())
2402 ArgTypes.push_back(Parm->getType());
2403 QualType FnType =
2404 CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
2405 FunctionProtoType::ExtProtoInfo());
2406 llvm::MDSubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2407 DContext, Name, LinkageName, Unit, Line,
2408 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2409 false /*declaration*/, 0, Flags, CGM.getLangOpts().Optimize, nullptr,
2410 TParamsArray.get(), getFunctionDeclaration(FD));
2411 const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2412 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2413 std::make_tuple(CanonDecl),
2414 std::make_tuple(SP));
2415 return SP;
2416 }
2417
2418 llvm::DIGlobalVariable
getGlobalVariableForwardDeclaration(const VarDecl * VD)2419 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2420 QualType T;
2421 StringRef Name, LinkageName;
2422 SourceLocation Loc = VD->getLocation();
2423 llvm::DIFile Unit = getOrCreateFile(Loc);
2424 llvm::MDScope *DContext = Unit;
2425 unsigned Line = getLineNumber(Loc);
2426
2427 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2428 llvm::DIGlobalVariable GV =
2429 DBuilder.createTempGlobalVariableFwdDecl(DContext, Name, LinkageName, Unit,
2430 Line, getOrCreateType(T, Unit),
2431 !VD->isExternallyVisible(),
2432 nullptr, nullptr);
2433 FwdDeclReplaceMap.emplace_back(
2434 std::piecewise_construct,
2435 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2436 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2437 return GV;
2438 }
2439
getDeclarationOrDefinition(const Decl * D)2440 llvm::DebugNode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2441 // We only need a declaration (not a definition) of the type - so use whatever
2442 // we would otherwise do to get a type for a pointee. (forward declarations in
2443 // limited debug info, full definitions (if the type definition is available)
2444 // in unlimited debug info)
2445 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2446 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2447 getOrCreateFile(TD->getLocation()));
2448 auto I = DeclCache.find(D->getCanonicalDecl());
2449
2450 if (I != DeclCache.end())
2451 return dyn_cast_or_null<llvm::DebugNode>(I->second);
2452
2453 // No definition for now. Emit a forward definition that might be
2454 // merged with a potential upcoming definition.
2455 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2456 return getFunctionForwardDeclaration(FD);
2457 else if (const auto *VD = dyn_cast<VarDecl>(D))
2458 return getGlobalVariableForwardDeclaration(VD);
2459
2460 return nullptr;
2461 }
2462
2463 /// getFunctionDeclaration - Return debug info descriptor to describe method
2464 /// declaration for the given method definition.
getFunctionDeclaration(const Decl * D)2465 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2466 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2467 return llvm::DISubprogram();
2468
2469 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2470 if (!FD)
2471 return llvm::DISubprogram();
2472
2473 // Setup context.
2474 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2475
2476 auto MI = SPCache.find(FD->getCanonicalDecl());
2477 if (MI == SPCache.end()) {
2478 if (const CXXMethodDecl *MD =
2479 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2480 llvm::DICompositeType T = cast<llvm::MDCompositeType>(S);
2481 llvm::DISubprogram SP =
2482 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2483 return SP;
2484 }
2485 }
2486 if (MI != SPCache.end()) {
2487 auto *SP = dyn_cast_or_null<llvm::MDSubprogram>(MI->second);
2488 if (SP && !SP->isDefinition())
2489 return SP;
2490 }
2491
2492 for (auto NextFD : FD->redecls()) {
2493 auto MI = SPCache.find(NextFD->getCanonicalDecl());
2494 if (MI != SPCache.end()) {
2495 auto *SP = dyn_cast_or_null<llvm::MDSubprogram>(MI->second);
2496 if (SP && !SP->isDefinition())
2497 return SP;
2498 }
2499 }
2500 return llvm::DISubprogram();
2501 }
2502
2503 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2504 // implicit parameter "this".
getOrCreateFunctionType(const Decl * D,QualType FnType,llvm::DIFile F)2505 llvm::MDSubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2506 QualType FnType,
2507 llvm::DIFile F) {
2508 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2509 // Create fake but valid subroutine type. Otherwise
2510 // llvm::DISubprogram::Verify() would return false, and
2511 // subprogram DIE will miss DW_AT_decl_file and
2512 // DW_AT_decl_line fields.
2513 return DBuilder.createSubroutineType(F,
2514 DBuilder.getOrCreateTypeArray(None));
2515
2516 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2517 return getOrCreateMethodType(Method, F);
2518 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2519 // Add "self" and "_cmd"
2520 SmallVector<llvm::Metadata *, 16> Elts;
2521
2522 // First element is always return type. For 'void' functions it is NULL.
2523 QualType ResultTy = OMethod->getReturnType();
2524
2525 // Replace the instancetype keyword with the actual type.
2526 if (ResultTy == CGM.getContext().getObjCInstanceType())
2527 ResultTy = CGM.getContext().getPointerType(
2528 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2529
2530 Elts.push_back(getOrCreateType(ResultTy, F));
2531 // "self" pointer is always first argument.
2532 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2533 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2534 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2535 // "_cmd" pointer is always second argument.
2536 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2537 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2538 // Get rest of the arguments.
2539 for (const auto *PI : OMethod->params())
2540 Elts.push_back(getOrCreateType(PI->getType(), F));
2541 // Variadic methods need a special marker at the end of the type list.
2542 if (OMethod->isVariadic())
2543 Elts.push_back(DBuilder.createUnspecifiedParameter());
2544
2545 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2546 return DBuilder.createSubroutineType(F, EltTypeArray);
2547 }
2548
2549 // Handle variadic function types; they need an additional
2550 // unspecified parameter.
2551 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2552 if (FD->isVariadic()) {
2553 SmallVector<llvm::Metadata *, 16> EltTys;
2554 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2555 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2556 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2557 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2558 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2559 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
2560 return DBuilder.createSubroutineType(F, EltTypeArray);
2561 }
2562
2563 return cast<llvm::MDSubroutineType>(getOrCreateType(FnType, F));
2564 }
2565
2566 /// EmitFunctionStart - Constructs the debug code for entering a function.
EmitFunctionStart(GlobalDecl GD,SourceLocation Loc,SourceLocation ScopeLoc,QualType FnType,llvm::Function * Fn,CGBuilderTy & Builder)2567 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
2568 SourceLocation ScopeLoc, QualType FnType,
2569 llvm::Function *Fn, CGBuilderTy &Builder) {
2570
2571 StringRef Name;
2572 StringRef LinkageName;
2573
2574 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2575
2576 const Decl *D = GD.getDecl();
2577 bool HasDecl = (D != nullptr);
2578
2579 unsigned Flags = 0;
2580 llvm::DIFile Unit = getOrCreateFile(Loc);
2581 llvm::MDScope *FDContext = Unit;
2582 llvm::DIArray TParamsArray;
2583 if (!HasDecl) {
2584 // Use llvm function name.
2585 LinkageName = Fn->getName();
2586 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2587 // If there is a DISubprogram for this function available then use it.
2588 auto FI = SPCache.find(FD->getCanonicalDecl());
2589 if (FI != SPCache.end()) {
2590 auto *SP = dyn_cast_or_null<llvm::MDSubprogram>(FI->second);
2591 if (SP && SP->isDefinition()) {
2592 llvm::MDNode *SPN = SP;
2593 LexicalBlockStack.emplace_back(SPN);
2594 RegionMap[D].reset(SP);
2595 return;
2596 }
2597 }
2598 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2599 TParamsArray, Flags);
2600 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2601 Name = getObjCMethodName(OMD);
2602 Flags |= llvm::DebugNode::FlagPrototyped;
2603 } else {
2604 // Use llvm function name.
2605 Name = Fn->getName();
2606 Flags |= llvm::DebugNode::FlagPrototyped;
2607 }
2608 if (!Name.empty() && Name[0] == '\01')
2609 Name = Name.substr(1);
2610
2611 if (!HasDecl || D->isImplicit()) {
2612 Flags |= llvm::DebugNode::FlagArtificial;
2613 // Artificial functions without a location should not silently reuse CurLoc.
2614 if (Loc.isInvalid())
2615 CurLoc = SourceLocation();
2616 }
2617 unsigned LineNo = getLineNumber(Loc);
2618 unsigned ScopeLine = getLineNumber(ScopeLoc);
2619
2620 // FIXME: The function declaration we're constructing here is mostly reusing
2621 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2622 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2623 // all subprograms instead of the actual context since subprogram definitions
2624 // are emitted as CU level entities by the backend.
2625 llvm::DISubprogram SP = DBuilder.createFunction(
2626 FDContext, Name, LinkageName, Unit, LineNo,
2627 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2628 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn,
2629 TParamsArray.get(), getFunctionDeclaration(D));
2630 // We might get here with a VarDecl in the case we're generating
2631 // code for the initialization of globals. Do not record these decls
2632 // as they will overwrite the actual VarDecl Decl in the cache.
2633 if (HasDecl && isa<FunctionDecl>(D))
2634 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
2635
2636 // Push the function onto the lexical block stack.
2637 llvm::MDNode *SPN = SP;
2638 LexicalBlockStack.emplace_back(SPN);
2639
2640 if (HasDecl)
2641 RegionMap[D].reset(SP);
2642 }
2643
2644 /// EmitLocation - Emit metadata to indicate a change in line/column
2645 /// information in the source file. If the location is invalid, the
2646 /// previous location will be reused.
EmitLocation(CGBuilderTy & Builder,SourceLocation Loc)2647 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2648 // Update our current location
2649 setLocation(Loc);
2650
2651 if (CurLoc.isInvalid() || CurLoc.isMacroID())
2652 return;
2653
2654 llvm::MDNode *Scope = LexicalBlockStack.back();
2655 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2656 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
2657 }
2658
2659 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2660 /// the stack.
CreateLexicalBlock(SourceLocation Loc)2661 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2662 llvm::MDNode *Back = nullptr;
2663 if (!LexicalBlockStack.empty())
2664 Back = LexicalBlockStack.back().get();
2665 llvm::DIDescriptor D = DBuilder.createLexicalBlock(
2666 cast<llvm::MDScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
2667 getColumnNumber(CurLoc));
2668 llvm::MDNode *DN = D;
2669 LexicalBlockStack.emplace_back(DN);
2670 }
2671
2672 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2673 /// region - beginning of a DW_TAG_lexical_block.
EmitLexicalBlockStart(CGBuilderTy & Builder,SourceLocation Loc)2674 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2675 SourceLocation Loc) {
2676 // Set our current location.
2677 setLocation(Loc);
2678
2679 // Emit a line table change for the current location inside the new scope.
2680 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2681 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
2682
2683 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2684 return;
2685
2686 // Create a new lexical block and push it on the stack.
2687 CreateLexicalBlock(Loc);
2688 }
2689
2690 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2691 /// region - end of a DW_TAG_lexical_block.
EmitLexicalBlockEnd(CGBuilderTy & Builder,SourceLocation Loc)2692 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2693 SourceLocation Loc) {
2694 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2695
2696 // Provide an entry in the line table for the end of the block.
2697 EmitLocation(Builder, Loc);
2698
2699 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2700 return;
2701
2702 LexicalBlockStack.pop_back();
2703 }
2704
2705 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
EmitFunctionEnd(CGBuilderTy & Builder)2706 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2707 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2708 unsigned RCount = FnBeginRegionCount.back();
2709 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2710
2711 // Pop all regions for this function.
2712 while (LexicalBlockStack.size() != RCount) {
2713 // Provide an entry in the line table for the end of the block.
2714 EmitLocation(Builder, CurLoc);
2715 LexicalBlockStack.pop_back();
2716 }
2717 FnBeginRegionCount.pop_back();
2718 }
2719
2720 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2721 // See BuildByRefType.
EmitTypeForVarWithBlocksAttr(const VarDecl * VD,uint64_t * XOffset)2722 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2723 uint64_t *XOffset) {
2724
2725 SmallVector<llvm::Metadata *, 5> EltTys;
2726 QualType FType;
2727 uint64_t FieldSize, FieldOffset;
2728 unsigned FieldAlign;
2729
2730 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2731 QualType Type = VD->getType();
2732
2733 FieldOffset = 0;
2734 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2735 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2736 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2737 FType = CGM.getContext().IntTy;
2738 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2739 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2740
2741 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2742 if (HasCopyAndDispose) {
2743 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2744 EltTys.push_back(
2745 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
2746 EltTys.push_back(
2747 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
2748 }
2749 bool HasByrefExtendedLayout;
2750 Qualifiers::ObjCLifetime Lifetime;
2751 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
2752 HasByrefExtendedLayout) &&
2753 HasByrefExtendedLayout) {
2754 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2755 EltTys.push_back(
2756 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
2757 }
2758
2759 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2760 if (Align > CGM.getContext().toCharUnitsFromBits(
2761 CGM.getTarget().getPointerAlign(0))) {
2762 CharUnits FieldOffsetInBytes =
2763 CGM.getContext().toCharUnitsFromBits(FieldOffset);
2764 CharUnits AlignedOffsetInBytes =
2765 FieldOffsetInBytes.RoundUpToAlignment(Align);
2766 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
2767
2768 if (NumPaddingBytes.isPositive()) {
2769 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2770 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2771 pad, ArrayType::Normal, 0);
2772 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2773 }
2774 }
2775
2776 FType = Type;
2777 llvm::DIType FieldTy = getOrCreateType(FType, Unit);
2778 FieldSize = CGM.getContext().getTypeSize(FType);
2779 FieldAlign = CGM.getContext().toBits(Align);
2780
2781 *XOffset = FieldOffset;
2782 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
2783 FieldAlign, FieldOffset, 0, FieldTy);
2784 EltTys.push_back(FieldTy);
2785 FieldOffset += FieldSize;
2786
2787 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2788
2789 unsigned Flags = llvm::DebugNode::FlagBlockByrefStruct;
2790
2791 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2792 llvm::DIType(), Elements);
2793 }
2794
2795 /// EmitDeclare - Emit local variable declaration debug info.
EmitDeclare(const VarDecl * VD,llvm::dwarf::Tag Tag,llvm::Value * Storage,unsigned ArgNo,CGBuilderTy & Builder)2796 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::Tag Tag,
2797 llvm::Value *Storage, unsigned ArgNo,
2798 CGBuilderTy &Builder) {
2799 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2800 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2801
2802 bool Unwritten =
2803 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2804 cast<Decl>(VD->getDeclContext())->isImplicit());
2805 llvm::DIFile Unit;
2806 if (!Unwritten)
2807 Unit = getOrCreateFile(VD->getLocation());
2808 llvm::DIType Ty;
2809 uint64_t XOffset = 0;
2810 if (VD->hasAttr<BlocksAttr>())
2811 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2812 else
2813 Ty = getOrCreateType(VD->getType(), Unit);
2814
2815 // If there is no debug info for this type then do not emit debug info
2816 // for this variable.
2817 if (!Ty)
2818 return;
2819
2820 // Get location information.
2821 unsigned Line = 0;
2822 unsigned Column = 0;
2823 if (!Unwritten) {
2824 Line = getLineNumber(VD->getLocation());
2825 Column = getColumnNumber(VD->getLocation());
2826 }
2827 SmallVector<int64_t, 9> Expr;
2828 unsigned Flags = 0;
2829 if (VD->isImplicit())
2830 Flags |= llvm::DebugNode::FlagArtificial;
2831 // If this is the first argument and it is implicit then
2832 // give it an object pointer flag.
2833 // FIXME: There has to be a better way to do this, but for static
2834 // functions there won't be an implicit param at arg1 and
2835 // otherwise it is 'self' or 'this'.
2836 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2837 Flags |= llvm::DebugNode::FlagObjectPointer;
2838 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2839 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2840 !VD->getType()->isPointerType())
2841 Expr.push_back(llvm::dwarf::DW_OP_deref);
2842
2843 auto *Scope = cast<llvm::MDScope>(LexicalBlockStack.back());
2844
2845 StringRef Name = VD->getName();
2846 if (!Name.empty()) {
2847 if (VD->hasAttr<BlocksAttr>()) {
2848 CharUnits offset = CharUnits::fromQuantity(32);
2849 Expr.push_back(llvm::dwarf::DW_OP_plus);
2850 // offset of __forwarding field
2851 offset = CGM.getContext().toCharUnitsFromBits(
2852 CGM.getTarget().getPointerWidth(0));
2853 Expr.push_back(offset.getQuantity());
2854 Expr.push_back(llvm::dwarf::DW_OP_deref);
2855 Expr.push_back(llvm::dwarf::DW_OP_plus);
2856 // offset of x field
2857 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2858 Expr.push_back(offset.getQuantity());
2859
2860 // Create the descriptor for the variable.
2861 llvm::DIVariable D = DBuilder.createLocalVariable(
2862 Tag, Scope, VD->getName(), Unit, Line, Ty, ArgNo);
2863
2864 // Insert an llvm.dbg.declare into the current block.
2865 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2866 llvm::DebugLoc::get(Line, Column, Scope),
2867 Builder.GetInsertBlock());
2868 return;
2869 } else if (isa<VariableArrayType>(VD->getType()))
2870 Expr.push_back(llvm::dwarf::DW_OP_deref);
2871 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2872 // If VD is an anonymous union then Storage represents value for
2873 // all union fields.
2874 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2875 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2876 for (const auto *Field : RD->fields()) {
2877 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2878 StringRef FieldName = Field->getName();
2879
2880 // Ignore unnamed fields. Do not ignore unnamed records.
2881 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2882 continue;
2883
2884 // Use VarDecl's Tag, Scope and Line number.
2885 llvm::DIVariable D = DBuilder.createLocalVariable(
2886 Tag, Scope, FieldName, Unit, Line, FieldTy,
2887 CGM.getLangOpts().Optimize, Flags, ArgNo);
2888
2889 // Insert an llvm.dbg.declare into the current block.
2890 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2891 llvm::DebugLoc::get(Line, Column, Scope),
2892 Builder.GetInsertBlock());
2893 }
2894 return;
2895 }
2896 }
2897
2898 // Create the descriptor for the variable.
2899 llvm::DIVariable D =
2900 DBuilder.createLocalVariable(Tag, Scope, Name, Unit, Line, Ty,
2901 CGM.getLangOpts().Optimize, Flags, ArgNo);
2902
2903 // Insert an llvm.dbg.declare into the current block.
2904 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2905 llvm::DebugLoc::get(Line, Column, Scope),
2906 Builder.GetInsertBlock());
2907 }
2908
EmitDeclareOfAutoVariable(const VarDecl * VD,llvm::Value * Storage,CGBuilderTy & Builder)2909 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2910 llvm::Value *Storage,
2911 CGBuilderTy &Builder) {
2912 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2913 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2914 }
2915
2916 /// Look up the completed type for a self pointer in the TypeCache and
2917 /// create a copy of it with the ObjectPointer and Artificial flags
2918 /// set. If the type is not cached, a new one is created. This should
2919 /// never happen though, since creating a type for the implicit self
2920 /// argument implies that we already parsed the interface definition
2921 /// and the ivar declarations in the implementation.
CreateSelfType(const QualType & QualTy,llvm::DIType Ty)2922 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2923 llvm::DIType Ty) {
2924 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2925 if (CachedTy)
2926 Ty = CachedTy;
2927 return DBuilder.createObjectPointerType(Ty);
2928 }
2929
EmitDeclareOfBlockDeclRefVariable(const VarDecl * VD,llvm::Value * Storage,CGBuilderTy & Builder,const CGBlockInfo & blockInfo,llvm::Instruction * InsertPoint)2930 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2931 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2932 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
2933 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2934 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2935
2936 if (Builder.GetInsertBlock() == nullptr)
2937 return;
2938
2939 bool isByRef = VD->hasAttr<BlocksAttr>();
2940
2941 uint64_t XOffset = 0;
2942 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2943 llvm::DIType Ty;
2944 if (isByRef)
2945 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2946 else
2947 Ty = getOrCreateType(VD->getType(), Unit);
2948
2949 // Self is passed along as an implicit non-arg variable in a
2950 // block. Mark it as the object pointer.
2951 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2952 Ty = CreateSelfType(VD->getType(), Ty);
2953
2954 // Get location information.
2955 unsigned Line = getLineNumber(VD->getLocation());
2956 unsigned Column = getColumnNumber(VD->getLocation());
2957
2958 const llvm::DataLayout &target = CGM.getDataLayout();
2959
2960 CharUnits offset = CharUnits::fromQuantity(
2961 target.getStructLayout(blockInfo.StructureType)
2962 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2963
2964 SmallVector<int64_t, 9> addr;
2965 if (isa<llvm::AllocaInst>(Storage))
2966 addr.push_back(llvm::dwarf::DW_OP_deref);
2967 addr.push_back(llvm::dwarf::DW_OP_plus);
2968 addr.push_back(offset.getQuantity());
2969 if (isByRef) {
2970 addr.push_back(llvm::dwarf::DW_OP_deref);
2971 addr.push_back(llvm::dwarf::DW_OP_plus);
2972 // offset of __forwarding field
2973 offset =
2974 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
2975 addr.push_back(offset.getQuantity());
2976 addr.push_back(llvm::dwarf::DW_OP_deref);
2977 addr.push_back(llvm::dwarf::DW_OP_plus);
2978 // offset of x field
2979 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2980 addr.push_back(offset.getQuantity());
2981 }
2982
2983 // Create the descriptor for the variable.
2984 llvm::DIVariable D = DBuilder.createLocalVariable(
2985 llvm::dwarf::DW_TAG_auto_variable,
2986 cast<llvm::MDLocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
2987 Line, Ty);
2988
2989 // Insert an llvm.dbg.declare into the current block.
2990 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
2991 if (InsertPoint)
2992 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2993 InsertPoint);
2994 else
2995 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2996 Builder.GetInsertBlock());
2997 }
2998
2999 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
3000 /// variable declaration.
EmitDeclareOfArgVariable(const VarDecl * VD,llvm::Value * AI,unsigned ArgNo,CGBuilderTy & Builder)3001 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3002 unsigned ArgNo,
3003 CGBuilderTy &Builder) {
3004 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3005 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
3006 }
3007
3008 namespace {
3009 struct BlockLayoutChunk {
3010 uint64_t OffsetInBits;
3011 const BlockDecl::Capture *Capture;
3012 };
operator <(const BlockLayoutChunk & l,const BlockLayoutChunk & r)3013 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3014 return l.OffsetInBits < r.OffsetInBits;
3015 }
3016 }
3017
EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo & block,llvm::Value * Arg,unsigned ArgNo,llvm::Value * LocalAddr,CGBuilderTy & Builder)3018 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3019 llvm::Value *Arg,
3020 unsigned ArgNo,
3021 llvm::Value *LocalAddr,
3022 CGBuilderTy &Builder) {
3023 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3024 ASTContext &C = CGM.getContext();
3025 const BlockDecl *blockDecl = block.getBlockDecl();
3026
3027 // Collect some general information about the block's location.
3028 SourceLocation loc = blockDecl->getCaretLocation();
3029 llvm::DIFile tunit = getOrCreateFile(loc);
3030 unsigned line = getLineNumber(loc);
3031 unsigned column = getColumnNumber(loc);
3032
3033 // Build the debug-info type for the block literal.
3034 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3035
3036 const llvm::StructLayout *blockLayout =
3037 CGM.getDataLayout().getStructLayout(block.StructureType);
3038
3039 SmallVector<llvm::Metadata *, 16> fields;
3040 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3041 blockLayout->getElementOffsetInBits(0),
3042 tunit, tunit));
3043 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3044 blockLayout->getElementOffsetInBits(1),
3045 tunit, tunit));
3046 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3047 blockLayout->getElementOffsetInBits(2),
3048 tunit, tunit));
3049 auto *FnTy = block.getBlockExpr()->getFunctionType();
3050 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3051 fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
3052 blockLayout->getElementOffsetInBits(3),
3053 tunit, tunit));
3054 fields.push_back(createFieldType(
3055 "__descriptor", C.getPointerType(block.NeedsCopyDispose
3056 ? C.getBlockDescriptorExtendedType()
3057 : C.getBlockDescriptorType()),
3058 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3059
3060 // We want to sort the captures by offset, not because DWARF
3061 // requires this, but because we're paranoid about debuggers.
3062 SmallVector<BlockLayoutChunk, 8> chunks;
3063
3064 // 'this' capture.
3065 if (blockDecl->capturesCXXThis()) {
3066 BlockLayoutChunk chunk;
3067 chunk.OffsetInBits =
3068 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3069 chunk.Capture = nullptr;
3070 chunks.push_back(chunk);
3071 }
3072
3073 // Variable captures.
3074 for (const auto &capture : blockDecl->captures()) {
3075 const VarDecl *variable = capture.getVariable();
3076 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3077
3078 // Ignore constant captures.
3079 if (captureInfo.isConstant())
3080 continue;
3081
3082 BlockLayoutChunk chunk;
3083 chunk.OffsetInBits =
3084 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3085 chunk.Capture = &capture;
3086 chunks.push_back(chunk);
3087 }
3088
3089 // Sort by offset.
3090 llvm::array_pod_sort(chunks.begin(), chunks.end());
3091
3092 for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
3093 e = chunks.end();
3094 i != e; ++i) {
3095 uint64_t offsetInBits = i->OffsetInBits;
3096 const BlockDecl::Capture *capture = i->Capture;
3097
3098 // If we have a null capture, this must be the C++ 'this' capture.
3099 if (!capture) {
3100 const CXXMethodDecl *method =
3101 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3102 QualType type = method->getThisType(C);
3103
3104 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3105 offsetInBits, tunit, tunit));
3106 continue;
3107 }
3108
3109 const VarDecl *variable = capture->getVariable();
3110 StringRef name = variable->getName();
3111
3112 llvm::DIType fieldType;
3113 if (capture->isByRef()) {
3114 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3115
3116 // FIXME: this creates a second copy of this type!
3117 uint64_t xoffset;
3118 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3119 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3120 fieldType =
3121 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
3122 PtrInfo.Align, offsetInBits, 0, fieldType);
3123 } else {
3124 fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
3125 offsetInBits, tunit, tunit);
3126 }
3127 fields.push_back(fieldType);
3128 }
3129
3130 SmallString<36> typeName;
3131 llvm::raw_svector_ostream(typeName) << "__block_literal_"
3132 << CGM.getUniqueBlockCount();
3133
3134 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3135
3136 llvm::DIType type =
3137 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3138 CGM.getContext().toBits(block.BlockSize),
3139 CGM.getContext().toBits(block.BlockAlign), 0,
3140 llvm::DIType(), fieldsArray);
3141 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3142
3143 // Get overall information about the block.
3144 unsigned flags = llvm::DebugNode::FlagArtificial;
3145 auto *scope = cast<llvm::MDLocalScope>(LexicalBlockStack.back());
3146
3147 // Create the descriptor for the parameter.
3148 llvm::DIVariable debugVar = DBuilder.createLocalVariable(
3149 llvm::dwarf::DW_TAG_arg_variable, scope, Arg->getName(), tunit, line,
3150 type, CGM.getLangOpts().Optimize, flags, ArgNo);
3151
3152 if (LocalAddr) {
3153 // Insert an llvm.dbg.value into the current block.
3154 DBuilder.insertDbgValueIntrinsic(
3155 LocalAddr, 0, debugVar, DBuilder.createExpression(),
3156 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3157 }
3158
3159 // Insert an llvm.dbg.declare into the current block.
3160 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3161 llvm::DebugLoc::get(line, column, scope),
3162 Builder.GetInsertBlock());
3163 }
3164
3165 /// If D is an out-of-class definition of a static data member of a class, find
3166 /// its corresponding in-class declaration.
3167 llvm::DIDerivedType
getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl * D)3168 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3169 if (!D->isStaticDataMember())
3170 return llvm::DIDerivedType();
3171
3172 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3173 if (MI != StaticDataMemberCache.end()) {
3174 assert(MI->second && "Static data member declaration should still exist");
3175 return cast<llvm::MDDerivedTypeBase>(MI->second);
3176 }
3177
3178 // If the member wasn't found in the cache, lazily construct and add it to the
3179 // type (used when a limited form of the type is emitted).
3180 auto DC = D->getDeclContext();
3181 llvm::DICompositeType Ctxt =
3182 cast<llvm::MDCompositeType>(getContextDescriptor(cast<Decl>(DC)));
3183 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3184 }
3185
3186 /// Recursively collect all of the member fields of a global anonymous decl and
3187 /// create static variables for them. The first time this is called it needs
3188 /// to be on a union and then from there we can have additional unnamed fields.
CollectAnonRecordDecls(const RecordDecl * RD,llvm::DIFile Unit,unsigned LineNo,StringRef LinkageName,llvm::GlobalVariable * Var,llvm::MDScope * DContext)3189 llvm::DIGlobalVariable CGDebugInfo::CollectAnonRecordDecls(
3190 const RecordDecl *RD, llvm::DIFile Unit, unsigned LineNo,
3191 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::MDScope *DContext) {
3192 llvm::DIGlobalVariable GV;
3193
3194 for (const auto *Field : RD->fields()) {
3195 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
3196 StringRef FieldName = Field->getName();
3197
3198 // Ignore unnamed fields, but recurse into anonymous records.
3199 if (FieldName.empty()) {
3200 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3201 if (RT)
3202 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3203 Var, DContext);
3204 continue;
3205 }
3206 // Use VarDecl's Tag, Scope and Line number.
3207 GV = DBuilder.createGlobalVariable(
3208 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
3209 Var->hasInternalLinkage(), Var, llvm::DIDerivedType());
3210 }
3211 return GV;
3212 }
3213
3214 /// EmitGlobalVariable - Emit information about a global variable.
EmitGlobalVariable(llvm::GlobalVariable * Var,const VarDecl * D)3215 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3216 const VarDecl *D) {
3217 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3218 // Create global variable debug descriptor.
3219 llvm::DIFile Unit;
3220 llvm::MDScope *DContext = nullptr;
3221 unsigned LineNo;
3222 StringRef DeclName, LinkageName;
3223 QualType T;
3224 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3225
3226 // Attempt to store one global variable for the declaration - even if we
3227 // emit a lot of fields.
3228 llvm::DIGlobalVariable GV;
3229
3230 // If this is an anonymous union then we'll want to emit a global
3231 // variable for each member of the anonymous union so that it's possible
3232 // to find the name of any field in the union.
3233 if (T->isUnionType() && DeclName.empty()) {
3234 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3235 assert(RD->isAnonymousStructOrUnion() &&
3236 "unnamed non-anonymous struct or union?");
3237 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3238 } else {
3239 GV = DBuilder.createGlobalVariable(
3240 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3241 Var->hasInternalLinkage(), Var,
3242 getOrCreateStaticDataMemberDeclarationOrNull(D));
3243 }
3244 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
3245 }
3246
3247 /// EmitGlobalVariable - Emit global variable's debug info.
EmitGlobalVariable(const ValueDecl * VD,llvm::Constant * Init)3248 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3249 llvm::Constant *Init) {
3250 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3251 // Create the descriptor for the variable.
3252 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3253 StringRef Name = VD->getName();
3254 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3255 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3256 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3257 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3258 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3259 }
3260 // Do not use DIGlobalVariable for enums.
3261 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3262 return;
3263 // Do not emit separate definitions for function local const/statics.
3264 if (isa<FunctionDecl>(VD->getDeclContext()))
3265 return;
3266 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3267 auto *VarD = cast<VarDecl>(VD);
3268 if (VarD->isStaticDataMember()) {
3269 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3270 getContextDescriptor(RD);
3271 // Ensure that the type is retained even though it's otherwise unreferenced.
3272 RetainedTypes.push_back(
3273 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3274 return;
3275 }
3276
3277 llvm::MDScope *DContext =
3278 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
3279
3280 auto &GV = DeclCache[VD];
3281 if (GV)
3282 return;
3283 GV.reset(DBuilder.createGlobalVariable(
3284 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3285 true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
3286 }
3287
getCurrentContextDescriptor(const Decl * D)3288 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3289 if (!LexicalBlockStack.empty())
3290 return cast<llvm::MDScope>(LexicalBlockStack.back());
3291 return getContextDescriptor(D);
3292 }
3293
EmitUsingDirective(const UsingDirectiveDecl & UD)3294 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3295 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3296 return;
3297 DBuilder.createImportedModule(
3298 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3299 getOrCreateNameSpace(UD.getNominatedNamespace()),
3300 getLineNumber(UD.getLocation()));
3301 }
3302
EmitUsingDecl(const UsingDecl & UD)3303 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3304 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3305 return;
3306 assert(UD.shadow_size() &&
3307 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3308 // Emitting one decl is sufficient - debuggers can detect that this is an
3309 // overloaded name & provide lookup for all the overloads.
3310 const UsingShadowDecl &USD = **UD.shadow_begin();
3311 if (llvm::DebugNode *Target =
3312 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3313 DBuilder.createImportedDeclaration(
3314 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3315 getLineNumber(USD.getLocation()));
3316 }
3317
3318 llvm::DIImportedEntity
EmitNamespaceAlias(const NamespaceAliasDecl & NA)3319 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3320 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3321 return llvm::DIImportedEntity();
3322 auto &VH = NamespaceAliasCache[&NA];
3323 if (VH)
3324 return cast<llvm::MDImportedEntity>(VH);
3325 llvm::DIImportedEntity R;
3326 if (const NamespaceAliasDecl *Underlying =
3327 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3328 // This could cache & dedup here rather than relying on metadata deduping.
3329 R = DBuilder.createImportedDeclaration(
3330 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3331 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3332 NA.getName());
3333 else
3334 R = DBuilder.createImportedDeclaration(
3335 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3336 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3337 getLineNumber(NA.getLocation()), NA.getName());
3338 VH.reset(R);
3339 return R;
3340 }
3341
3342 /// getOrCreateNamesSpace - Return namespace descriptor for the given
3343 /// namespace decl.
3344 llvm::DINameSpace
getOrCreateNameSpace(const NamespaceDecl * NSDecl)3345 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3346 NSDecl = NSDecl->getCanonicalDecl();
3347 auto I = NameSpaceCache.find(NSDecl);
3348 if (I != NameSpaceCache.end())
3349 return cast<llvm::MDNamespace>(I->second);
3350
3351 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3352 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3353 llvm::MDScope *Context =
3354 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3355 llvm::DINameSpace NS =
3356 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3357 NameSpaceCache[NSDecl].reset(NS);
3358 return NS;
3359 }
3360
finalize()3361 void CGDebugInfo::finalize() {
3362 // Creating types might create further types - invalidating the current
3363 // element and the size(), so don't cache/reference them.
3364 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3365 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3366 llvm::MDType *Ty = E.Type->getDecl()->getDefinition()
3367 ? CreateTypeDefinition(E.Type, E.Unit)
3368 : E.Decl;
3369 DBuilder.replaceTemporary(llvm::TempMDType(E.Decl), Ty);
3370 }
3371
3372 for (auto p : ReplaceMap) {
3373 assert(p.second);
3374 auto *Ty = cast<llvm::MDType>(p.second);
3375 assert(Ty->isForwardDecl());
3376
3377 auto it = TypeCache.find(p.first);
3378 assert(it != TypeCache.end());
3379 assert(it->second);
3380
3381 DBuilder.replaceTemporary(llvm::TempMDType(Ty),
3382 cast<llvm::MDType>(it->second));
3383 }
3384
3385 for (const auto &p : FwdDeclReplaceMap) {
3386 assert(p.second);
3387 llvm::DIDescriptor FwdDecl(cast<llvm::MDNode>(p.second));
3388 llvm::Metadata *Repl;
3389
3390 auto it = DeclCache.find(p.first);
3391 // If there has been no definition for the declaration, call RAUW
3392 // with ourselves, that will destroy the temporary MDNode and
3393 // replace it with a standard one, avoiding leaking memory.
3394 if (it == DeclCache.end())
3395 Repl = p.second;
3396 else
3397 Repl = it->second;
3398
3399 DBuilder.replaceTemporary(llvm::TempMDNode(FwdDecl),
3400 cast<llvm::MDNode>(Repl));
3401 }
3402
3403 // We keep our own list of retained types, because we need to look
3404 // up the final type in the type cache.
3405 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3406 RE = RetainedTypes.end(); RI != RE; ++RI)
3407 DBuilder.retainType(cast<llvm::MDType>(TypeCache[*RI]));
3408
3409 DBuilder.finalize();
3410 }
3411
EmitExplicitCastType(QualType Ty)3412 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
3413 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3414 return;
3415
3416 if (llvm::DIType DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3417 // Don't ignore in case of explicit cast where it is referenced indirectly.
3418 DBuilder.retainType(DieTy);
3419 }
3420