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