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