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