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