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