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