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