xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This coordinates the debug information generation while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGBlocks.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/Basic/CodeGenOptions.h"
30 #include "clang/Basic/FileManager.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/Version.h"
33 #include "clang/Frontend/FrontendOptions.h"
34 #include "clang/Lex/HeaderSearchOptions.h"
35 #include "clang/Lex/ModuleMap.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/MD5.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/TimeProfiler.h"
51 using namespace clang;
52 using namespace clang::CodeGen;
53 
54 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
55   auto TI = Ctx.getTypeInfo(Ty);
56   return TI.isAlignRequired() ? TI.Align : 0;
57 }
58 
59 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
60   return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
61 }
62 
63 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
64   return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
65 }
66 
67 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
68     : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
69       DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
70       DBuilder(CGM.getModule()) {
71   for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
72     DebugPrefixMap[KV.first] = KV.second;
73   CreateCompileUnit();
74 }
75 
76 CGDebugInfo::~CGDebugInfo() {
77   assert(LexicalBlockStack.empty() &&
78          "Region stack mismatch, stack not empty!");
79 }
80 
81 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
82                                        SourceLocation TemporaryLocation)
83     : CGF(&CGF) {
84   init(TemporaryLocation);
85 }
86 
87 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
88                                        bool DefaultToEmpty,
89                                        SourceLocation TemporaryLocation)
90     : CGF(&CGF) {
91   init(TemporaryLocation, DefaultToEmpty);
92 }
93 
94 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
95                               bool DefaultToEmpty) {
96   auto *DI = CGF->getDebugInfo();
97   if (!DI) {
98     CGF = nullptr;
99     return;
100   }
101 
102   OriginalLocation = CGF->Builder.getCurrentDebugLocation();
103 
104   if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
105     return;
106 
107   if (TemporaryLocation.isValid()) {
108     DI->EmitLocation(CGF->Builder, TemporaryLocation);
109     return;
110   }
111 
112   if (DefaultToEmpty) {
113     CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
114     return;
115   }
116 
117   // Construct a location that has a valid scope, but no line info.
118   assert(!DI->LexicalBlockStack.empty());
119   CGF->Builder.SetCurrentDebugLocation(
120       llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
121                             DI->LexicalBlockStack.back(), DI->getInlinedAt()));
122 }
123 
124 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
125     : CGF(&CGF) {
126   init(E->getExprLoc());
127 }
128 
129 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
130     : CGF(&CGF) {
131   if (!CGF.getDebugInfo()) {
132     this->CGF = nullptr;
133     return;
134   }
135   OriginalLocation = CGF.Builder.getCurrentDebugLocation();
136   if (Loc)
137     CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
138 }
139 
140 ApplyDebugLocation::~ApplyDebugLocation() {
141   // Query CGF so the location isn't overwritten when location updates are
142   // temporarily disabled (for C++ default function arguments)
143   if (CGF)
144     CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
145 }
146 
147 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
148                                                    GlobalDecl InlinedFn)
149     : CGF(&CGF) {
150   if (!CGF.getDebugInfo()) {
151     this->CGF = nullptr;
152     return;
153   }
154   auto &DI = *CGF.getDebugInfo();
155   SavedLocation = DI.getLocation();
156   assert((DI.getInlinedAt() ==
157           CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
158          "CGDebugInfo and IRBuilder are out of sync");
159 
160   DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
161 }
162 
163 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
164   if (!CGF)
165     return;
166   auto &DI = *CGF->getDebugInfo();
167   DI.EmitInlineFunctionEnd(CGF->Builder);
168   DI.EmitLocation(CGF->Builder, SavedLocation);
169 }
170 
171 void CGDebugInfo::setLocation(SourceLocation Loc) {
172   // If the new location isn't valid return.
173   if (Loc.isInvalid())
174     return;
175 
176   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
177 
178   // If we've changed files in the middle of a lexical scope go ahead
179   // and create a new lexical scope with file node if it's different
180   // from the one in the scope.
181   if (LexicalBlockStack.empty())
182     return;
183 
184   SourceManager &SM = CGM.getContext().getSourceManager();
185   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
186   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
187   if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
188     return;
189 
190   if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
191     LexicalBlockStack.pop_back();
192     LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
193         LBF->getScope(), getOrCreateFile(CurLoc)));
194   } else if (isa<llvm::DILexicalBlock>(Scope) ||
195              isa<llvm::DISubprogram>(Scope)) {
196     LexicalBlockStack.pop_back();
197     LexicalBlockStack.emplace_back(
198         DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
199   }
200 }
201 
202 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
203   llvm::DIScope *Mod = getParentModuleOrNull(D);
204   return getContextDescriptor(cast<Decl>(D->getDeclContext()),
205                               Mod ? Mod : TheCU);
206 }
207 
208 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
209                                                  llvm::DIScope *Default) {
210   if (!Context)
211     return Default;
212 
213   auto I = RegionMap.find(Context);
214   if (I != RegionMap.end()) {
215     llvm::Metadata *V = I->second;
216     return dyn_cast_or_null<llvm::DIScope>(V);
217   }
218 
219   // Check namespace.
220   if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
221     return getOrCreateNamespace(NSDecl);
222 
223   if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
224     if (!RDecl->isDependentType())
225       return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
226                              TheCU->getFile());
227   return Default;
228 }
229 
230 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
231   PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
232 
233   // If we're emitting codeview, it's important to try to match MSVC's naming so
234   // that visualizers written for MSVC will trigger for our class names. In
235   // particular, we can't have spaces between arguments of standard templates
236   // like basic_string and vector, but we must have spaces between consecutive
237   // angle brackets that close nested template argument lists.
238   if (CGM.getCodeGenOpts().EmitCodeView) {
239     PP.MSVCFormatting = true;
240     PP.SplitTemplateClosers = true;
241   } else {
242     // For DWARF, printing rules are underspecified.
243     // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
244     PP.SplitTemplateClosers = true;
245   }
246 
247   PP.SuppressInlineNamespace = false;
248   PP.PrintCanonicalTypes = true;
249   PP.UsePreferredNames = false;
250   PP.AlwaysIncludeTypeForTemplateArgument = true;
251   PP.UseEnumerators = false;
252 
253   // Apply -fdebug-prefix-map.
254   PP.Callbacks = &PrintCB;
255   return PP;
256 }
257 
258 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
259   return internString(GetName(FD));
260 }
261 
262 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
263   SmallString<256> MethodName;
264   llvm::raw_svector_ostream OS(MethodName);
265   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
266   const DeclContext *DC = OMD->getDeclContext();
267   if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
268     OS << OID->getName();
269   } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
270     OS << OID->getName();
271   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
272     if (OC->IsClassExtension()) {
273       OS << OC->getClassInterface()->getName();
274     } else {
275       OS << OC->getIdentifier()->getNameStart() << '('
276          << OC->getIdentifier()->getNameStart() << ')';
277     }
278   } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
279     OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
280   }
281   OS << ' ' << OMD->getSelector().getAsString() << ']';
282 
283   return internString(OS.str());
284 }
285 
286 StringRef CGDebugInfo::getSelectorName(Selector S) {
287   return internString(S.getAsString());
288 }
289 
290 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
291   if (isa<ClassTemplateSpecializationDecl>(RD)) {
292     // Copy this name on the side and use its reference.
293     return internString(GetName(RD));
294   }
295 
296   // quick optimization to avoid having to intern strings that are already
297   // stored reliably elsewhere
298   if (const IdentifierInfo *II = RD->getIdentifier())
299     return II->getName();
300 
301   // The CodeView printer in LLVM wants to see the names of unnamed types
302   // because they need to have a unique identifier.
303   // These names are used to reconstruct the fully qualified type names.
304   if (CGM.getCodeGenOpts().EmitCodeView) {
305     if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
306       assert(RD->getDeclContext() == D->getDeclContext() &&
307              "Typedef should not be in another decl context!");
308       assert(D->getDeclName().getAsIdentifierInfo() &&
309              "Typedef was not named!");
310       return D->getDeclName().getAsIdentifierInfo()->getName();
311     }
312 
313     if (CGM.getLangOpts().CPlusPlus) {
314       StringRef Name;
315 
316       ASTContext &Context = CGM.getContext();
317       if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
318         // Anonymous types without a name for linkage purposes have their
319         // declarator mangled in if they have one.
320         Name = DD->getName();
321       else if (const TypedefNameDecl *TND =
322                    Context.getTypedefNameForUnnamedTagDecl(RD))
323         // Anonymous types without a name for linkage purposes have their
324         // associate typedef mangled in if they have one.
325         Name = TND->getName();
326 
327       // Give lambdas a display name based on their name mangling.
328       if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
329         if (CXXRD->isLambda())
330           return internString(
331               CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));
332 
333       if (!Name.empty()) {
334         SmallString<256> UnnamedType("<unnamed-type-");
335         UnnamedType += Name;
336         UnnamedType += '>';
337         return internString(UnnamedType);
338       }
339     }
340   }
341 
342   return StringRef();
343 }
344 
345 Optional<llvm::DIFile::ChecksumKind>
346 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
347   Checksum.clear();
348 
349   if (!CGM.getCodeGenOpts().EmitCodeView &&
350       CGM.getCodeGenOpts().DwarfVersion < 5)
351     return None;
352 
353   SourceManager &SM = CGM.getContext().getSourceManager();
354   Optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
355   if (!MemBuffer)
356     return None;
357 
358   llvm::toHex(
359       llvm::MD5::hash(llvm::arrayRefFromStringRef(MemBuffer->getBuffer())),
360       /*LowerCase*/ true, Checksum);
361   return llvm::DIFile::CSK_MD5;
362 }
363 
364 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
365                                            FileID FID) {
366   if (!CGM.getCodeGenOpts().EmbedSource)
367     return None;
368 
369   bool SourceInvalid = false;
370   StringRef Source = SM.getBufferData(FID, &SourceInvalid);
371 
372   if (SourceInvalid)
373     return None;
374 
375   return Source;
376 }
377 
378 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
379   SourceManager &SM = CGM.getContext().getSourceManager();
380   StringRef FileName;
381   FileID FID;
382 
383   if (Loc.isInvalid()) {
384     // The DIFile used by the CU is distinct from the main source file. Call
385     // createFile() below for canonicalization if the source file was specified
386     // with an absolute path.
387     FileName = TheCU->getFile()->getFilename();
388   } else {
389     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
390     FileName = PLoc.getFilename();
391 
392     if (FileName.empty()) {
393       FileName = TheCU->getFile()->getFilename();
394     } else {
395       FileName = PLoc.getFilename();
396     }
397     FID = PLoc.getFileID();
398   }
399 
400   // Cache the results.
401   auto It = DIFileCache.find(FileName.data());
402   if (It != DIFileCache.end()) {
403     // Verify that the information still exists.
404     if (llvm::Metadata *V = It->second)
405       return cast<llvm::DIFile>(V);
406   }
407 
408   SmallString<32> Checksum;
409 
410   Optional<llvm::DIFile::ChecksumKind> CSKind = computeChecksum(FID, Checksum);
411   Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
412   if (CSKind)
413     CSInfo.emplace(*CSKind, Checksum);
414   return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
415 }
416 
417 llvm::DIFile *
418 CGDebugInfo::createFile(StringRef FileName,
419                         Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
420                         Optional<StringRef> Source) {
421   StringRef Dir;
422   StringRef File;
423   std::string RemappedFile = remapDIPath(FileName);
424   std::string CurDir = remapDIPath(getCurrentDirname());
425   SmallString<128> DirBuf;
426   SmallString<128> FileBuf;
427   if (llvm::sys::path::is_absolute(RemappedFile)) {
428     // Strip the common prefix (if it is more than just "/" or "C:\") from
429     // current directory and FileName for a more space-efficient encoding.
430     auto FileIt = llvm::sys::path::begin(RemappedFile);
431     auto FileE = llvm::sys::path::end(RemappedFile);
432     auto CurDirIt = llvm::sys::path::begin(CurDir);
433     auto CurDirE = llvm::sys::path::end(CurDir);
434     for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
435       llvm::sys::path::append(DirBuf, *CurDirIt);
436     if (llvm::sys::path::root_path(DirBuf) == DirBuf) {
437       // Don't strip the common prefix if it is only the root ("/" or "C:\")
438       // since that would make LLVM diagnostic locations confusing.
439       Dir = {};
440       File = RemappedFile;
441     } else {
442       for (; FileIt != FileE; ++FileIt)
443         llvm::sys::path::append(FileBuf, *FileIt);
444       Dir = DirBuf;
445       File = FileBuf;
446     }
447   } else {
448     if (!llvm::sys::path::is_absolute(FileName))
449       Dir = CurDir;
450     File = RemappedFile;
451   }
452   llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
453   DIFileCache[FileName.data()].reset(F);
454   return F;
455 }
456 
457 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
458   if (DebugPrefixMap.empty())
459     return Path.str();
460 
461   SmallString<256> P = Path;
462   for (const auto &Entry : DebugPrefixMap)
463     if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
464       break;
465   return P.str().str();
466 }
467 
468 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
469   if (Loc.isInvalid())
470     return 0;
471   SourceManager &SM = CGM.getContext().getSourceManager();
472   return SM.getPresumedLoc(Loc).getLine();
473 }
474 
475 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
476   // We may not want column information at all.
477   if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
478     return 0;
479 
480   // If the location is invalid then use the current column.
481   if (Loc.isInvalid() && CurLoc.isInvalid())
482     return 0;
483   SourceManager &SM = CGM.getContext().getSourceManager();
484   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
485   return PLoc.isValid() ? PLoc.getColumn() : 0;
486 }
487 
488 StringRef CGDebugInfo::getCurrentDirname() {
489   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
490     return CGM.getCodeGenOpts().DebugCompilationDir;
491 
492   if (!CWDName.empty())
493     return CWDName;
494   SmallString<256> CWD;
495   llvm::sys::fs::current_path(CWD);
496   return CWDName = internString(CWD);
497 }
498 
499 void CGDebugInfo::CreateCompileUnit() {
500   SmallString<32> Checksum;
501   Optional<llvm::DIFile::ChecksumKind> CSKind;
502   Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
503 
504   // Should we be asking the SourceManager for the main file name, instead of
505   // accepting it as an argument? This just causes the main file name to
506   // mismatch with source locations and create extra lexical scopes or
507   // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
508   // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
509   // because that's what the SourceManager says)
510 
511   // Get absolute path name.
512   SourceManager &SM = CGM.getContext().getSourceManager();
513   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
514   if (MainFileName.empty())
515     MainFileName = "<stdin>";
516 
517   // The main file name provided via the "-main-file-name" option contains just
518   // the file name itself with no path information. This file name may have had
519   // a relative path, so we look into the actual file entry for the main
520   // file to determine the real absolute path for the file.
521   std::string MainFileDir;
522   if (Optional<FileEntryRef> MainFile =
523           SM.getFileEntryRefForID(SM.getMainFileID())) {
524     MainFileDir = std::string(MainFile->getDir().getName());
525     if (!llvm::sys::path::is_absolute(MainFileName)) {
526       llvm::SmallString<1024> MainFileDirSS(MainFileDir);
527       llvm::sys::path::append(MainFileDirSS, MainFileName);
528       MainFileName =
529           std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
530     }
531     // If the main file name provided is identical to the input file name, and
532     // if the input file is a preprocessed source, use the module name for
533     // debug info. The module name comes from the name specified in the first
534     // linemarker if the input is a preprocessed source.
535     if (MainFile->getName() == MainFileName &&
536         FrontendOptions::getInputKindForExtension(
537             MainFile->getName().rsplit('.').second)
538             .isPreprocessed())
539       MainFileName = CGM.getModule().getName().str();
540 
541     CSKind = computeChecksum(SM.getMainFileID(), Checksum);
542   }
543 
544   llvm::dwarf::SourceLanguage LangTag;
545   const LangOptions &LO = CGM.getLangOpts();
546   if (LO.CPlusPlus) {
547     if (LO.ObjC)
548       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
549     else if (LO.CPlusPlus14 && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
550                                 CGM.getCodeGenOpts().DwarfVersion >= 5))
551       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
552     else if (LO.CPlusPlus11 && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
553                                 CGM.getCodeGenOpts().DwarfVersion >= 5))
554       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
555     else
556       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
557   } else if (LO.ObjC) {
558     LangTag = llvm::dwarf::DW_LANG_ObjC;
559   } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
560                            CGM.getCodeGenOpts().DwarfVersion >= 5)) {
561     LangTag = llvm::dwarf::DW_LANG_OpenCL;
562   } else if (LO.RenderScript) {
563     LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
564   } else if (LO.C99) {
565     LangTag = llvm::dwarf::DW_LANG_C99;
566   } else {
567     LangTag = llvm::dwarf::DW_LANG_C89;
568   }
569 
570   std::string Producer = getClangFullVersion();
571 
572   // Figure out which version of the ObjC runtime we have.
573   unsigned RuntimeVers = 0;
574   if (LO.ObjC)
575     RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
576 
577   llvm::DICompileUnit::DebugEmissionKind EmissionKind;
578   switch (DebugKind) {
579   case codegenoptions::NoDebugInfo:
580   case codegenoptions::LocTrackingOnly:
581     EmissionKind = llvm::DICompileUnit::NoDebug;
582     break;
583   case codegenoptions::DebugLineTablesOnly:
584     EmissionKind = llvm::DICompileUnit::LineTablesOnly;
585     break;
586   case codegenoptions::DebugDirectivesOnly:
587     EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
588     break;
589   case codegenoptions::DebugInfoConstructor:
590   case codegenoptions::LimitedDebugInfo:
591   case codegenoptions::FullDebugInfo:
592   case codegenoptions::UnusedTypeInfo:
593     EmissionKind = llvm::DICompileUnit::FullDebug;
594     break;
595   }
596 
597   uint64_t DwoId = 0;
598   auto &CGOpts = CGM.getCodeGenOpts();
599   // The DIFile used by the CU is distinct from the main source
600   // file. Its directory part specifies what becomes the
601   // DW_AT_comp_dir (the compilation directory), even if the source
602   // file was specified with an absolute path.
603   if (CSKind)
604     CSInfo.emplace(*CSKind, Checksum);
605   llvm::DIFile *CUFile = DBuilder.createFile(
606       remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
607       getSource(SM, SM.getMainFileID()));
608 
609   StringRef Sysroot, SDK;
610   if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
611     Sysroot = CGM.getHeaderSearchOpts().Sysroot;
612     auto B = llvm::sys::path::rbegin(Sysroot);
613     auto E = llvm::sys::path::rend(Sysroot);
614     auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
615     if (It != E)
616       SDK = *It;
617   }
618 
619   // Create new compile unit.
620   TheCU = DBuilder.createCompileUnit(
621       LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
622       LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
623       CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
624       DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
625       CGM.getTarget().getTriple().isNVPTX()
626           ? llvm::DICompileUnit::DebugNameTableKind::None
627           : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
628                 CGOpts.DebugNameTable),
629       CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
630 }
631 
632 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
633   llvm::dwarf::TypeKind Encoding;
634   StringRef BTName;
635   switch (BT->getKind()) {
636 #define BUILTIN_TYPE(Id, SingletonId)
637 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
638 #include "clang/AST/BuiltinTypes.def"
639   case BuiltinType::Dependent:
640     llvm_unreachable("Unexpected builtin type");
641   case BuiltinType::NullPtr:
642     return DBuilder.createNullPtrType();
643   case BuiltinType::Void:
644     return nullptr;
645   case BuiltinType::ObjCClass:
646     if (!ClassTy)
647       ClassTy =
648           DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
649                                      "objc_class", TheCU, TheCU->getFile(), 0);
650     return ClassTy;
651   case BuiltinType::ObjCId: {
652     // typedef struct objc_class *Class;
653     // typedef struct objc_object {
654     //  Class isa;
655     // } *id;
656 
657     if (ObjTy)
658       return ObjTy;
659 
660     if (!ClassTy)
661       ClassTy =
662           DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
663                                      "objc_class", TheCU, TheCU->getFile(), 0);
664 
665     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
666 
667     auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
668 
669     ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
670                                       0, 0, llvm::DINode::FlagZero, nullptr,
671                                       llvm::DINodeArray());
672 
673     DBuilder.replaceArrays(
674         ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
675                    ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
676                    llvm::DINode::FlagZero, ISATy)));
677     return ObjTy;
678   }
679   case BuiltinType::ObjCSel: {
680     if (!SelTy)
681       SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
682                                          "objc_selector", TheCU,
683                                          TheCU->getFile(), 0);
684     return SelTy;
685   }
686 
687 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
688   case BuiltinType::Id:                                                        \
689     return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t",       \
690                                     SingletonId);
691 #include "clang/Basic/OpenCLImageTypes.def"
692   case BuiltinType::OCLSampler:
693     return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
694   case BuiltinType::OCLEvent:
695     return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
696   case BuiltinType::OCLClkEvent:
697     return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
698   case BuiltinType::OCLQueue:
699     return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
700   case BuiltinType::OCLReserveID:
701     return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
702 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
703   case BuiltinType::Id: \
704     return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
705 #include "clang/Basic/OpenCLExtensionTypes.def"
706 
707 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
708 #include "clang/Basic/AArch64SVEACLETypes.def"
709     {
710       ASTContext::BuiltinVectorTypeInfo Info =
711           CGM.getContext().getBuiltinVectorTypeInfo(BT);
712       unsigned NumElemsPerVG = (Info.EC.getKnownMinValue() * Info.NumVectors) / 2;
713 
714       // Debuggers can't extract 1bit from a vector, so will display a
715       // bitpattern for svbool_t instead.
716       if (Info.ElementType == CGM.getContext().BoolTy) {
717         NumElemsPerVG /= 8;
718         Info.ElementType = CGM.getContext().UnsignedCharTy;
719       }
720 
721       auto *LowerBound =
722           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
723               llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
724       SmallVector<uint64_t, 9> Expr(
725           {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
726            /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
727            llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
728       auto *UpperBound = DBuilder.createExpression(Expr);
729 
730       llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
731           /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
732       llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
733       llvm::DIType *ElemTy =
734           getOrCreateType(Info.ElementType, TheCU->getFile());
735       auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
736       return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
737                                        SubscriptArray);
738     }
739   // It doesn't make sense to generate debug info for PowerPC MMA vector types.
740   // So we return a safe type here to avoid generating an error.
741 #define PPC_VECTOR_TYPE(Name, Id, size) \
742   case BuiltinType::Id:
743 #include "clang/Basic/PPCTypes.def"
744     return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
745 
746 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
747 #include "clang/Basic/RISCVVTypes.def"
748     {
749       ASTContext::BuiltinVectorTypeInfo Info =
750           CGM.getContext().getBuiltinVectorTypeInfo(BT);
751 
752       unsigned ElementCount = Info.EC.getKnownMinValue();
753       unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
754 
755       bool Fractional = false;
756       unsigned LMUL;
757       unsigned FixedSize = ElementCount * SEW;
758       if (Info.ElementType == CGM.getContext().BoolTy) {
759         // Mask type only occupies one vector register.
760         LMUL = 1;
761       } else if (FixedSize < 64) {
762         // In RVV scalable vector types, we encode 64 bits in the fixed part.
763         Fractional = true;
764         LMUL = 64 / FixedSize;
765       } else {
766         LMUL = FixedSize / 64;
767       }
768 
769       // Element count = (VLENB / SEW) x LMUL
770       SmallVector<uint64_t, 12> Expr(
771           // The DW_OP_bregx operation has two operands: a register which is
772           // specified by an unsigned LEB128 number, followed by a signed LEB128
773           // offset.
774           {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
775            4096 + 0xC22,             // RISC-V VLENB CSR register.
776            0, // Offset for DW_OP_bregx. It is dummy here.
777            llvm::dwarf::DW_OP_constu,
778            SEW / 8, // SEW is in bits.
779            llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
780       if (Fractional)
781         Expr.push_back(llvm::dwarf::DW_OP_div);
782       else
783         Expr.push_back(llvm::dwarf::DW_OP_mul);
784       // Element max index = count - 1
785       Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
786 
787       auto *LowerBound =
788           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
789               llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
790       auto *UpperBound = DBuilder.createExpression(Expr);
791       llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
792           /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
793       llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
794       llvm::DIType *ElemTy =
795           getOrCreateType(Info.ElementType, TheCU->getFile());
796 
797       auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
798       return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
799                                        SubscriptArray);
800     }
801   case BuiltinType::UChar:
802   case BuiltinType::Char_U:
803     Encoding = llvm::dwarf::DW_ATE_unsigned_char;
804     break;
805   case BuiltinType::Char_S:
806   case BuiltinType::SChar:
807     Encoding = llvm::dwarf::DW_ATE_signed_char;
808     break;
809   case BuiltinType::Char8:
810   case BuiltinType::Char16:
811   case BuiltinType::Char32:
812     Encoding = llvm::dwarf::DW_ATE_UTF;
813     break;
814   case BuiltinType::UShort:
815   case BuiltinType::UInt:
816   case BuiltinType::UInt128:
817   case BuiltinType::ULong:
818   case BuiltinType::WChar_U:
819   case BuiltinType::ULongLong:
820     Encoding = llvm::dwarf::DW_ATE_unsigned;
821     break;
822   case BuiltinType::Short:
823   case BuiltinType::Int:
824   case BuiltinType::Int128:
825   case BuiltinType::Long:
826   case BuiltinType::WChar_S:
827   case BuiltinType::LongLong:
828     Encoding = llvm::dwarf::DW_ATE_signed;
829     break;
830   case BuiltinType::Bool:
831     Encoding = llvm::dwarf::DW_ATE_boolean;
832     break;
833   case BuiltinType::Half:
834   case BuiltinType::Float:
835   case BuiltinType::LongDouble:
836   case BuiltinType::Float16:
837   case BuiltinType::BFloat16:
838   case BuiltinType::Float128:
839   case BuiltinType::Double:
840   case BuiltinType::Ibm128:
841     // FIXME: For targets where long double, __ibm128 and __float128 have the
842     // same size, they are currently indistinguishable in the debugger without
843     // some special treatment. However, there is currently no consensus on
844     // encoding and this should be updated once a DWARF encoding exists for
845     // distinct floating point types of the same size.
846     Encoding = llvm::dwarf::DW_ATE_float;
847     break;
848   case BuiltinType::ShortAccum:
849   case BuiltinType::Accum:
850   case BuiltinType::LongAccum:
851   case BuiltinType::ShortFract:
852   case BuiltinType::Fract:
853   case BuiltinType::LongFract:
854   case BuiltinType::SatShortFract:
855   case BuiltinType::SatFract:
856   case BuiltinType::SatLongFract:
857   case BuiltinType::SatShortAccum:
858   case BuiltinType::SatAccum:
859   case BuiltinType::SatLongAccum:
860     Encoding = llvm::dwarf::DW_ATE_signed_fixed;
861     break;
862   case BuiltinType::UShortAccum:
863   case BuiltinType::UAccum:
864   case BuiltinType::ULongAccum:
865   case BuiltinType::UShortFract:
866   case BuiltinType::UFract:
867   case BuiltinType::ULongFract:
868   case BuiltinType::SatUShortAccum:
869   case BuiltinType::SatUAccum:
870   case BuiltinType::SatULongAccum:
871   case BuiltinType::SatUShortFract:
872   case BuiltinType::SatUFract:
873   case BuiltinType::SatULongFract:
874     Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
875     break;
876   }
877 
878   BTName = BT->getName(CGM.getLangOpts());
879   // Bit size and offset of the type.
880   uint64_t Size = CGM.getContext().getTypeSize(BT);
881   return DBuilder.createBasicType(BTName, Size, Encoding);
882 }
883 
884 llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
885   return DBuilder.createUnspecifiedType("auto");
886 }
887 
888 llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
889 
890   StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
891   llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
892                                        ? llvm::dwarf::DW_ATE_unsigned
893                                        : llvm::dwarf::DW_ATE_signed;
894 
895   return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
896                                   Encoding);
897 }
898 
899 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
900   // Bit size and offset of the type.
901   llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
902   if (Ty->isComplexIntegerType())
903     Encoding = llvm::dwarf::DW_ATE_lo_user;
904 
905   uint64_t Size = CGM.getContext().getTypeSize(Ty);
906   return DBuilder.createBasicType("complex", Size, Encoding);
907 }
908 
909 static void stripUnusedQualifiers(Qualifiers &Q) {
910   // Ignore these qualifiers for now.
911   Q.removeObjCGCAttr();
912   Q.removeAddressSpace();
913   Q.removeObjCLifetime();
914   Q.removeUnaligned();
915 }
916 
917 static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
918   if (Q.hasConst()) {
919     Q.removeConst();
920     return llvm::dwarf::DW_TAG_const_type;
921   }
922   if (Q.hasVolatile()) {
923     Q.removeVolatile();
924     return llvm::dwarf::DW_TAG_volatile_type;
925   }
926   if (Q.hasRestrict()) {
927     Q.removeRestrict();
928     return llvm::dwarf::DW_TAG_restrict_type;
929   }
930   return (llvm::dwarf::Tag)0;
931 }
932 
933 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
934                                                llvm::DIFile *Unit) {
935   QualifierCollector Qc;
936   const Type *T = Qc.strip(Ty);
937 
938   stripUnusedQualifiers(Qc);
939 
940   // We will create one Derived type for one qualifier and recurse to handle any
941   // additional ones.
942   llvm::dwarf::Tag Tag = getNextQualifier(Qc);
943   if (!Tag) {
944     assert(Qc.empty() && "Unknown type qualifier for debug info");
945     return getOrCreateType(QualType(T, 0), Unit);
946   }
947 
948   auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
949 
950   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
951   // CVR derived types.
952   return DBuilder.createQualifiedType(Tag, FromTy);
953 }
954 
955 llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
956                                                llvm::DIFile *Unit) {
957   FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo();
958   Qualifiers &Q = EPI.TypeQuals;
959   stripUnusedQualifiers(Q);
960 
961   // We will create one Derived type for one qualifier and recurse to handle any
962   // additional ones.
963   llvm::dwarf::Tag Tag = getNextQualifier(Q);
964   if (!Tag) {
965     assert(Q.empty() && "Unknown type qualifier for debug info");
966     return nullptr;
967   }
968 
969   auto *FromTy =
970       getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
971                                                        F->getParamTypes(), EPI),
972                       Unit);
973 
974   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
975   // CVR derived types.
976   return DBuilder.createQualifiedType(Tag, FromTy);
977 }
978 
979 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
980                                       llvm::DIFile *Unit) {
981 
982   // The frontend treats 'id' as a typedef to an ObjCObjectType,
983   // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
984   // debug info, we want to emit 'id' in both cases.
985   if (Ty->isObjCQualifiedIdType())
986     return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
987 
988   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
989                                Ty->getPointeeType(), Unit);
990 }
991 
992 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
993                                       llvm::DIFile *Unit) {
994   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
995                                Ty->getPointeeType(), Unit);
996 }
997 
998 /// \return whether a C++ mangling exists for the type defined by TD.
999 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1000   switch (TheCU->getSourceLanguage()) {
1001   case llvm::dwarf::DW_LANG_C_plus_plus:
1002   case llvm::dwarf::DW_LANG_C_plus_plus_11:
1003   case llvm::dwarf::DW_LANG_C_plus_plus_14:
1004     return true;
1005   case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1006     return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1007   default:
1008     return false;
1009   }
1010 }
1011 
1012 // Determines if the debug info for this tag declaration needs a type
1013 // identifier. The purpose of the unique identifier is to deduplicate type
1014 // information for identical types across TUs. Because of the C++ one definition
1015 // rule (ODR), it is valid to assume that the type is defined the same way in
1016 // every TU and its debug info is equivalent.
1017 //
1018 // C does not have the ODR, and it is common for codebases to contain multiple
1019 // different definitions of a struct with the same name in different TUs.
1020 // Therefore, if the type doesn't have a C++ mangling, don't give it an
1021 // identifer. Type information in C is smaller and simpler than C++ type
1022 // information, so the increase in debug info size is negligible.
1023 //
1024 // If the type is not externally visible, it should be unique to the current TU,
1025 // and should not need an identifier to participate in type deduplication.
1026 // However, when emitting CodeView, the format internally uses these
1027 // unique type name identifers for references between debug info. For example,
1028 // the method of a class in an anonymous namespace uses the identifer to refer
1029 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
1030 // for such types, so when emitting CodeView, always use identifiers for C++
1031 // types. This may create problems when attempting to emit CodeView when the MS
1032 // C++ ABI is not in use.
1033 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1034                                 llvm::DICompileUnit *TheCU) {
1035   // We only add a type identifier for types with C++ name mangling.
1036   if (!hasCXXMangling(TD, TheCU))
1037     return false;
1038 
1039   // Externally visible types with C++ mangling need a type identifier.
1040   if (TD->isExternallyVisible())
1041     return true;
1042 
1043   // CodeView types with C++ mangling need a type identifier.
1044   if (CGM.getCodeGenOpts().EmitCodeView)
1045     return true;
1046 
1047   return false;
1048 }
1049 
1050 // Returns a unique type identifier string if one exists, or an empty string.
1051 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1052                                           llvm::DICompileUnit *TheCU) {
1053   SmallString<256> Identifier;
1054   const TagDecl *TD = Ty->getDecl();
1055 
1056   if (!needsTypeIdentifier(TD, CGM, TheCU))
1057     return Identifier;
1058   if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1059     if (RD->getDefinition())
1060       if (RD->isDynamicClass() &&
1061           CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1062         return Identifier;
1063 
1064   // TODO: This is using the RTTI name. Is there a better way to get
1065   // a unique string for a type?
1066   llvm::raw_svector_ostream Out(Identifier);
1067   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1068   return Identifier;
1069 }
1070 
1071 /// \return the appropriate DWARF tag for a composite type.
1072 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1073   llvm::dwarf::Tag Tag;
1074   if (RD->isStruct() || RD->isInterface())
1075     Tag = llvm::dwarf::DW_TAG_structure_type;
1076   else if (RD->isUnion())
1077     Tag = llvm::dwarf::DW_TAG_union_type;
1078   else {
1079     // FIXME: This could be a struct type giving a default visibility different
1080     // than C++ class type, but needs llvm metadata changes first.
1081     assert(RD->isClass());
1082     Tag = llvm::dwarf::DW_TAG_class_type;
1083   }
1084   return Tag;
1085 }
1086 
1087 llvm::DICompositeType *
1088 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1089                                       llvm::DIScope *Ctx) {
1090   const RecordDecl *RD = Ty->getDecl();
1091   if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1092     return cast<llvm::DICompositeType>(T);
1093   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1094   const unsigned Line =
1095       getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1096   StringRef RDName = getClassName(RD);
1097 
1098   uint64_t Size = 0;
1099   uint32_t Align = 0;
1100 
1101   const RecordDecl *D = RD->getDefinition();
1102   if (D && D->isCompleteDefinition())
1103     Size = CGM.getContext().getTypeSize(Ty);
1104 
1105   llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1106 
1107   // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1108   // add the flag if a record has no definition because we don't know whether
1109   // it will be trivial or not.
1110   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1111     if (!CXXRD->hasDefinition() ||
1112         (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1113       Flags |= llvm::DINode::FlagNonTrivial;
1114 
1115   // Create the type.
1116   SmallString<256> Identifier;
1117   // Don't include a linkage name in line tables only.
1118   if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1119     Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1120   llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1121       getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1122       Identifier);
1123   if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1124     if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1125       DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1126                              CollectCXXTemplateParams(TSpecial, DefUnit));
1127   ReplaceMap.emplace_back(
1128       std::piecewise_construct, std::make_tuple(Ty),
1129       std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1130   return RetTy;
1131 }
1132 
1133 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1134                                                  const Type *Ty,
1135                                                  QualType PointeeTy,
1136                                                  llvm::DIFile *Unit) {
1137   // Bit size, align and offset of the type.
1138   // Size is always the size of a pointer. We can't use getTypeSize here
1139   // because that does not return the correct value for references.
1140   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1141   uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1142   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1143   Optional<unsigned> DWARFAddressSpace =
1144       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1145 
1146   SmallVector<llvm::Metadata *, 4> Annots;
1147   auto *BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);
1148   while (BTFAttrTy) {
1149     StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
1150     if (!Tag.empty()) {
1151       llvm::Metadata *Ops[2] = {
1152           llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
1153           llvm::MDString::get(CGM.getLLVMContext(), Tag)};
1154       Annots.insert(Annots.begin(),
1155                     llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1156     }
1157     BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
1158   }
1159 
1160   llvm::DINodeArray Annotations = nullptr;
1161   if (Annots.size() > 0)
1162     Annotations = DBuilder.getOrCreateArray(Annots);
1163 
1164   if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1165       Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1166     return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1167                                         Size, Align, DWARFAddressSpace);
1168   else
1169     return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1170                                       Align, DWARFAddressSpace, StringRef(),
1171                                       Annotations);
1172 }
1173 
1174 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1175                                                     llvm::DIType *&Cache) {
1176   if (Cache)
1177     return Cache;
1178   Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1179                                      TheCU, TheCU->getFile(), 0);
1180   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1181   Cache = DBuilder.createPointerType(Cache, Size);
1182   return Cache;
1183 }
1184 
1185 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1186     const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1187     unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1188   QualType FType;
1189 
1190   // Advanced by calls to CreateMemberType in increments of FType, then
1191   // returned as the overall size of the default elements.
1192   uint64_t FieldOffset = 0;
1193 
1194   // Blocks in OpenCL have unique constraints which make the standard fields
1195   // redundant while requiring size and align fields for enqueue_kernel. See
1196   // initializeForBlockHeader in CGBlocks.cpp
1197   if (CGM.getLangOpts().OpenCL) {
1198     FType = CGM.getContext().IntTy;
1199     EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1200     EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1201   } else {
1202     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1203     EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1204     FType = CGM.getContext().IntTy;
1205     EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1206     EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1207     FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1208     EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1209     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1210     uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1211     uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1212     EltTys.push_back(DBuilder.createMemberType(
1213         Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1214         FieldOffset, llvm::DINode::FlagZero, DescTy));
1215     FieldOffset += FieldSize;
1216   }
1217 
1218   return FieldOffset;
1219 }
1220 
1221 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1222                                       llvm::DIFile *Unit) {
1223   SmallVector<llvm::Metadata *, 8> EltTys;
1224   QualType FType;
1225   uint64_t FieldOffset;
1226   llvm::DINodeArray Elements;
1227 
1228   FieldOffset = 0;
1229   FType = CGM.getContext().UnsignedLongTy;
1230   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1231   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1232 
1233   Elements = DBuilder.getOrCreateArray(EltTys);
1234   EltTys.clear();
1235 
1236   llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1237 
1238   auto *EltTy =
1239       DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1240                                 FieldOffset, 0, Flags, nullptr, Elements);
1241 
1242   // Bit size, align and offset of the type.
1243   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1244 
1245   auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1246 
1247   FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1248                                                           0, EltTys);
1249 
1250   Elements = DBuilder.getOrCreateArray(EltTys);
1251 
1252   // The __block_literal_generic structs are marked with a special
1253   // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1254   // the debugger needs to know about. To allow type uniquing, emit
1255   // them without a name or a location.
1256   EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1257                                     Flags, nullptr, Elements);
1258 
1259   return DBuilder.createPointerType(EltTy, Size);
1260 }
1261 
1262 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1263                                       llvm::DIFile *Unit) {
1264   assert(Ty->isTypeAlias());
1265   llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1266 
1267   auto *AliasDecl =
1268       cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1269           ->getTemplatedDecl();
1270 
1271   if (AliasDecl->hasAttr<NoDebugAttr>())
1272     return Src;
1273 
1274   SmallString<128> NS;
1275   llvm::raw_svector_ostream OS(NS);
1276   Ty->getTemplateName().print(OS, getPrintingPolicy(),
1277                               TemplateName::Qualified::None);
1278   printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1279 
1280   SourceLocation Loc = AliasDecl->getLocation();
1281   return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1282                                 getLineNumber(Loc),
1283                                 getDeclContextDescriptor(AliasDecl));
1284 }
1285 
1286 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1287                                       llvm::DIFile *Unit) {
1288   llvm::DIType *Underlying =
1289       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1290 
1291   if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1292     return Underlying;
1293 
1294   // We don't set size information, but do specify where the typedef was
1295   // declared.
1296   SourceLocation Loc = Ty->getDecl()->getLocation();
1297 
1298   uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1299   // Typedefs are derived from some other type.
1300   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1301   return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1302                                 getOrCreateFile(Loc), getLineNumber(Loc),
1303                                 getDeclContextDescriptor(Ty->getDecl()), Align,
1304                                 Annotations);
1305 }
1306 
1307 static unsigned getDwarfCC(CallingConv CC) {
1308   switch (CC) {
1309   case CC_C:
1310     // Avoid emitting DW_AT_calling_convention if the C convention was used.
1311     return 0;
1312 
1313   case CC_X86StdCall:
1314     return llvm::dwarf::DW_CC_BORLAND_stdcall;
1315   case CC_X86FastCall:
1316     return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1317   case CC_X86ThisCall:
1318     return llvm::dwarf::DW_CC_BORLAND_thiscall;
1319   case CC_X86VectorCall:
1320     return llvm::dwarf::DW_CC_LLVM_vectorcall;
1321   case CC_X86Pascal:
1322     return llvm::dwarf::DW_CC_BORLAND_pascal;
1323   case CC_Win64:
1324     return llvm::dwarf::DW_CC_LLVM_Win64;
1325   case CC_X86_64SysV:
1326     return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1327   case CC_AAPCS:
1328   case CC_AArch64VectorCall:
1329   case CC_AArch64SVEPCS:
1330     return llvm::dwarf::DW_CC_LLVM_AAPCS;
1331   case CC_AAPCS_VFP:
1332     return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1333   case CC_IntelOclBicc:
1334     return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1335   case CC_SpirFunction:
1336     return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1337   case CC_OpenCLKernel:
1338   case CC_AMDGPUKernelCall:
1339     return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1340   case CC_Swift:
1341     return llvm::dwarf::DW_CC_LLVM_Swift;
1342   case CC_SwiftAsync:
1343     // [FIXME: swiftasynccc] Update to SwiftAsync once LLVM support lands.
1344     return llvm::dwarf::DW_CC_LLVM_Swift;
1345   case CC_PreserveMost:
1346     return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1347   case CC_PreserveAll:
1348     return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1349   case CC_X86RegCall:
1350     return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1351   }
1352   return 0;
1353 }
1354 
1355 static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1356   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1357   if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1358     Flags |= llvm::DINode::FlagLValueReference;
1359   if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1360     Flags |= llvm::DINode::FlagRValueReference;
1361   return Flags;
1362 }
1363 
1364 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1365                                       llvm::DIFile *Unit) {
1366   const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1367   if (FPT) {
1368     if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1369       return QTy;
1370   }
1371 
1372   // Create the type without any qualifiers
1373 
1374   SmallVector<llvm::Metadata *, 16> EltTys;
1375 
1376   // Add the result type at least.
1377   EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1378 
1379   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1380   // Set up remainder of arguments if there is a prototype.
1381   // otherwise emit it as a variadic function.
1382   if (!FPT) {
1383     EltTys.push_back(DBuilder.createUnspecifiedParameter());
1384   } else {
1385     Flags = getRefFlags(FPT);
1386     for (const QualType &ParamType : FPT->param_types())
1387       EltTys.push_back(getOrCreateType(ParamType, Unit));
1388     if (FPT->isVariadic())
1389       EltTys.push_back(DBuilder.createUnspecifiedParameter());
1390   }
1391 
1392   llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1393   llvm::DIType *F = DBuilder.createSubroutineType(
1394       EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1395   return F;
1396 }
1397 
1398 /// Convert an AccessSpecifier into the corresponding DINode flag.
1399 /// As an optimization, return 0 if the access specifier equals the
1400 /// default for the containing type.
1401 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1402                                            const RecordDecl *RD) {
1403   AccessSpecifier Default = clang::AS_none;
1404   if (RD && RD->isClass())
1405     Default = clang::AS_private;
1406   else if (RD && (RD->isStruct() || RD->isUnion()))
1407     Default = clang::AS_public;
1408 
1409   if (Access == Default)
1410     return llvm::DINode::FlagZero;
1411 
1412   switch (Access) {
1413   case clang::AS_private:
1414     return llvm::DINode::FlagPrivate;
1415   case clang::AS_protected:
1416     return llvm::DINode::FlagProtected;
1417   case clang::AS_public:
1418     return llvm::DINode::FlagPublic;
1419   case clang::AS_none:
1420     return llvm::DINode::FlagZero;
1421   }
1422   llvm_unreachable("unexpected access enumerator");
1423 }
1424 
1425 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1426                                               llvm::DIScope *RecordTy,
1427                                               const RecordDecl *RD) {
1428   StringRef Name = BitFieldDecl->getName();
1429   QualType Ty = BitFieldDecl->getType();
1430   SourceLocation Loc = BitFieldDecl->getLocation();
1431   llvm::DIFile *VUnit = getOrCreateFile(Loc);
1432   llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1433 
1434   // Get the location for the field.
1435   llvm::DIFile *File = getOrCreateFile(Loc);
1436   unsigned Line = getLineNumber(Loc);
1437 
1438   const CGBitFieldInfo &BitFieldInfo =
1439       CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1440   uint64_t SizeInBits = BitFieldInfo.Size;
1441   assert(SizeInBits > 0 && "found named 0-width bitfield");
1442   uint64_t StorageOffsetInBits =
1443       CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1444   uint64_t Offset = BitFieldInfo.Offset;
1445   // The bit offsets for big endian machines are reversed for big
1446   // endian target, compensate for that as the DIDerivedType requires
1447   // un-reversed offsets.
1448   if (CGM.getDataLayout().isBigEndian())
1449     Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1450   uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1451   llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1452   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1453   return DBuilder.createBitFieldMemberType(
1454       RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1455       Flags, DebugType, Annotations);
1456 }
1457 
1458 llvm::DIType *CGDebugInfo::createFieldType(
1459     StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1460     uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1461     llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1462   llvm::DIType *debugType = getOrCreateType(type, tunit);
1463 
1464   // Get the location for the field.
1465   llvm::DIFile *file = getOrCreateFile(loc);
1466   const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1467 
1468   uint64_t SizeInBits = 0;
1469   auto Align = AlignInBits;
1470   if (!type->isIncompleteArrayType()) {
1471     TypeInfo TI = CGM.getContext().getTypeInfo(type);
1472     SizeInBits = TI.Width;
1473     if (!Align)
1474       Align = getTypeAlignIfRequired(type, CGM.getContext());
1475   }
1476 
1477   llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1478   return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1479                                    offsetInBits, flags, debugType, Annotations);
1480 }
1481 
1482 void CGDebugInfo::CollectRecordLambdaFields(
1483     const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1484     llvm::DIType *RecordTy) {
1485   // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1486   // has the name and the location of the variable so we should iterate over
1487   // both concurrently.
1488   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1489   RecordDecl::field_iterator Field = CXXDecl->field_begin();
1490   unsigned fieldno = 0;
1491   for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1492                                              E = CXXDecl->captures_end();
1493        I != E; ++I, ++Field, ++fieldno) {
1494     const LambdaCapture &C = *I;
1495     if (C.capturesVariable()) {
1496       SourceLocation Loc = C.getLocation();
1497       assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1498       VarDecl *V = C.getCapturedVar();
1499       StringRef VName = V->getName();
1500       llvm::DIFile *VUnit = getOrCreateFile(Loc);
1501       auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1502       llvm::DIType *FieldType = createFieldType(
1503           VName, Field->getType(), Loc, Field->getAccess(),
1504           layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1505       elements.push_back(FieldType);
1506     } else if (C.capturesThis()) {
1507       // TODO: Need to handle 'this' in some way by probably renaming the
1508       // this of the lambda class and having a field member of 'this' or
1509       // by using AT_object_pointer for the function and having that be
1510       // used as 'this' for semantic references.
1511       FieldDecl *f = *Field;
1512       llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1513       QualType type = f->getType();
1514       llvm::DIType *fieldType = createFieldType(
1515           "this", type, f->getLocation(), f->getAccess(),
1516           layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1517 
1518       elements.push_back(fieldType);
1519     }
1520   }
1521 }
1522 
1523 llvm::DIDerivedType *
1524 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1525                                      const RecordDecl *RD) {
1526   // Create the descriptor for the static variable, with or without
1527   // constant initializers.
1528   Var = Var->getCanonicalDecl();
1529   llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1530   llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1531 
1532   unsigned LineNumber = getLineNumber(Var->getLocation());
1533   StringRef VName = Var->getName();
1534   llvm::Constant *C = nullptr;
1535   if (Var->getInit()) {
1536     const APValue *Value = Var->evaluateValue();
1537     if (Value) {
1538       if (Value->isInt())
1539         C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1540       if (Value->isFloat())
1541         C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1542     }
1543   }
1544 
1545   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1546   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1547   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1548       RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1549   StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1550   return GV;
1551 }
1552 
1553 void CGDebugInfo::CollectRecordNormalField(
1554     const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1555     SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1556     const RecordDecl *RD) {
1557   StringRef name = field->getName();
1558   QualType type = field->getType();
1559 
1560   // Ignore unnamed fields unless they're anonymous structs/unions.
1561   if (name.empty() && !type->isRecordType())
1562     return;
1563 
1564   llvm::DIType *FieldType;
1565   if (field->isBitField()) {
1566     FieldType = createBitFieldType(field, RecordTy, RD);
1567   } else {
1568     auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1569     llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1570     FieldType =
1571         createFieldType(name, type, field->getLocation(), field->getAccess(),
1572                         OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1573   }
1574 
1575   elements.push_back(FieldType);
1576 }
1577 
1578 void CGDebugInfo::CollectRecordNestedType(
1579     const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1580   QualType Ty = CGM.getContext().getTypeDeclType(TD);
1581   // Injected class names are not considered nested records.
1582   if (isa<InjectedClassNameType>(Ty))
1583     return;
1584   SourceLocation Loc = TD->getLocation();
1585   llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1586   elements.push_back(nestedType);
1587 }
1588 
1589 void CGDebugInfo::CollectRecordFields(
1590     const RecordDecl *record, llvm::DIFile *tunit,
1591     SmallVectorImpl<llvm::Metadata *> &elements,
1592     llvm::DICompositeType *RecordTy) {
1593   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1594 
1595   if (CXXDecl && CXXDecl->isLambda())
1596     CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1597   else {
1598     const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1599 
1600     // Field number for non-static fields.
1601     unsigned fieldNo = 0;
1602 
1603     // Static and non-static members should appear in the same order as
1604     // the corresponding declarations in the source program.
1605     for (const auto *I : record->decls())
1606       if (const auto *V = dyn_cast<VarDecl>(I)) {
1607         if (V->hasAttr<NoDebugAttr>())
1608           continue;
1609 
1610         // Skip variable template specializations when emitting CodeView. MSVC
1611         // doesn't emit them.
1612         if (CGM.getCodeGenOpts().EmitCodeView &&
1613             isa<VarTemplateSpecializationDecl>(V))
1614           continue;
1615 
1616         if (isa<VarTemplatePartialSpecializationDecl>(V))
1617           continue;
1618 
1619         // Reuse the existing static member declaration if one exists
1620         auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1621         if (MI != StaticDataMemberCache.end()) {
1622           assert(MI->second &&
1623                  "Static data member declaration should still exist");
1624           elements.push_back(MI->second);
1625         } else {
1626           auto Field = CreateRecordStaticField(V, RecordTy, record);
1627           elements.push_back(Field);
1628         }
1629       } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1630         CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1631                                  elements, RecordTy, record);
1632 
1633         // Bump field number for next field.
1634         ++fieldNo;
1635       } else if (CGM.getCodeGenOpts().EmitCodeView) {
1636         // Debug info for nested types is included in the member list only for
1637         // CodeView.
1638         if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1639           if (!nestedType->isImplicit() &&
1640               nestedType->getDeclContext() == record)
1641             CollectRecordNestedType(nestedType, elements);
1642       }
1643   }
1644 }
1645 
1646 llvm::DISubroutineType *
1647 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1648                                    llvm::DIFile *Unit, bool decl) {
1649   const auto *Func = Method->getType()->castAs<FunctionProtoType>();
1650   if (Method->isStatic())
1651     return cast_or_null<llvm::DISubroutineType>(
1652         getOrCreateType(QualType(Func, 0), Unit));
1653   return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
1654 }
1655 
1656 llvm::DISubroutineType *
1657 CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1658                                            const FunctionProtoType *Func,
1659                                            llvm::DIFile *Unit, bool decl) {
1660   FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1661   Qualifiers &Qc = EPI.TypeQuals;
1662   Qc.removeConst();
1663   Qc.removeVolatile();
1664   Qc.removeRestrict();
1665   Qc.removeUnaligned();
1666   // Keep the removed qualifiers in sync with
1667   // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1668   // On a 'real' member function type, these qualifiers are carried on the type
1669   // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1670   // tags around them. (But, in the raw function types with qualifiers, they have
1671   // to use wrapper types.)
1672 
1673   // Add "this" pointer.
1674   const auto *OriginalFunc = cast<llvm::DISubroutineType>(
1675       getOrCreateType(CGM.getContext().getFunctionType(
1676                           Func->getReturnType(), Func->getParamTypes(), EPI),
1677                       Unit));
1678   llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
1679   assert(Args.size() && "Invalid number of arguments!");
1680 
1681   SmallVector<llvm::Metadata *, 16> Elts;
1682   // First element is always return type. For 'void' functions it is NULL.
1683   QualType temp = Func->getReturnType();
1684   if (temp->getTypeClass() == Type::Auto && decl) {
1685     const AutoType *AT = cast<AutoType>(temp);
1686 
1687     // It may be tricky in some cases to link the specification back the lambda
1688     // call operator and so we skip emitting "auto" for lambdas. This is
1689     // consistent with gcc as well.
1690     if (AT->isDeduced() && ThisPtr->getPointeeCXXRecordDecl()->isLambda())
1691       Elts.push_back(getOrCreateType(AT->getDeducedType(), Unit));
1692     else
1693       Elts.push_back(CreateType(AT));
1694   } else
1695     Elts.push_back(Args[0]);
1696 
1697   // "this" pointer is always first argument.
1698   const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1699   if (isa<ClassTemplateSpecializationDecl>(RD)) {
1700     // Create pointer type directly in this case.
1701     const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1702     QualType PointeeTy = ThisPtrTy->getPointeeType();
1703     unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1704     uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1705     auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1706     llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1707     llvm::DIType *ThisPtrType =
1708         DBuilder.createPointerType(PointeeType, Size, Align);
1709     TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1710     // TODO: This and the artificial type below are misleading, the
1711     // types aren't artificial the argument is, but the current
1712     // metadata doesn't represent that.
1713     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1714     Elts.push_back(ThisPtrType);
1715   } else {
1716     llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1717     TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1718     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1719     Elts.push_back(ThisPtrType);
1720   }
1721 
1722   // Copy rest of the arguments.
1723   for (unsigned i = 1, e = Args.size(); i != e; ++i)
1724     Elts.push_back(Args[i]);
1725 
1726   llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1727 
1728   return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
1729                                        getDwarfCC(Func->getCallConv()));
1730 }
1731 
1732 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1733 /// inside a function.
1734 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1735   if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1736     return isFunctionLocalClass(NRD);
1737   if (isa<FunctionDecl>(RD->getDeclContext()))
1738     return true;
1739   return false;
1740 }
1741 
1742 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1743     const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1744   bool IsCtorOrDtor =
1745       isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1746 
1747   StringRef MethodName = getFunctionName(Method);
1748   llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
1749 
1750   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1751   // make sense to give a single ctor/dtor a linkage name.
1752   StringRef MethodLinkageName;
1753   // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1754   // property to use here. It may've been intended to model "is non-external
1755   // type" but misses cases of non-function-local but non-external classes such
1756   // as those in anonymous namespaces as well as the reverse - external types
1757   // that are function local, such as those in (non-local) inline functions.
1758   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1759     MethodLinkageName = CGM.getMangledName(Method);
1760 
1761   // Get the location for the method.
1762   llvm::DIFile *MethodDefUnit = nullptr;
1763   unsigned MethodLine = 0;
1764   if (!Method->isImplicit()) {
1765     MethodDefUnit = getOrCreateFile(Method->getLocation());
1766     MethodLine = getLineNumber(Method->getLocation());
1767   }
1768 
1769   // Collect virtual method info.
1770   llvm::DIType *ContainingType = nullptr;
1771   unsigned VIndex = 0;
1772   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1773   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1774   int ThisAdjustment = 0;
1775 
1776   if (Method->isVirtual()) {
1777     if (Method->isPure())
1778       SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1779     else
1780       SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1781 
1782     if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1783       // It doesn't make sense to give a virtual destructor a vtable index,
1784       // since a single destructor has two entries in the vtable.
1785       if (!isa<CXXDestructorDecl>(Method))
1786         VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1787     } else {
1788       // Emit MS ABI vftable information.  There is only one entry for the
1789       // deleting dtor.
1790       const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1791       GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1792       MethodVFTableLocation ML =
1793           CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1794       VIndex = ML.Index;
1795 
1796       // CodeView only records the vftable offset in the class that introduces
1797       // the virtual method. This is possible because, unlike Itanium, the MS
1798       // C++ ABI does not include all virtual methods from non-primary bases in
1799       // the vtable for the most derived class. For example, if C inherits from
1800       // A and B, C's primary vftable will not include B's virtual methods.
1801       if (Method->size_overridden_methods() == 0)
1802         Flags |= llvm::DINode::FlagIntroducedVirtual;
1803 
1804       // The 'this' adjustment accounts for both the virtual and non-virtual
1805       // portions of the adjustment. Presumably the debugger only uses it when
1806       // it knows the dynamic type of an object.
1807       ThisAdjustment = CGM.getCXXABI()
1808                            .getVirtualFunctionPrologueThisAdjustment(GD)
1809                            .getQuantity();
1810     }
1811     ContainingType = RecordTy;
1812   }
1813 
1814   // We're checking for deleted C++ special member functions
1815   // [Ctors,Dtors, Copy/Move]
1816   auto checkAttrDeleted = [&](const auto *Method) {
1817     if (Method->getCanonicalDecl()->isDeleted())
1818       SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1819   };
1820 
1821   switch (Method->getKind()) {
1822 
1823   case Decl::CXXConstructor:
1824   case Decl::CXXDestructor:
1825     checkAttrDeleted(Method);
1826     break;
1827   case Decl::CXXMethod:
1828     if (Method->isCopyAssignmentOperator() ||
1829         Method->isMoveAssignmentOperator())
1830       checkAttrDeleted(Method);
1831     break;
1832   default:
1833     break;
1834   }
1835 
1836   if (Method->isNoReturn())
1837     Flags |= llvm::DINode::FlagNoReturn;
1838 
1839   if (Method->isStatic())
1840     Flags |= llvm::DINode::FlagStaticMember;
1841   if (Method->isImplicit())
1842     Flags |= llvm::DINode::FlagArtificial;
1843   Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1844   if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1845     if (CXXC->isExplicit())
1846       Flags |= llvm::DINode::FlagExplicit;
1847   } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1848     if (CXXC->isExplicit())
1849       Flags |= llvm::DINode::FlagExplicit;
1850   }
1851   if (Method->hasPrototype())
1852     Flags |= llvm::DINode::FlagPrototyped;
1853   if (Method->getRefQualifier() == RQ_LValue)
1854     Flags |= llvm::DINode::FlagLValueReference;
1855   if (Method->getRefQualifier() == RQ_RValue)
1856     Flags |= llvm::DINode::FlagRValueReference;
1857   if (!Method->isExternallyVisible())
1858     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
1859   if (CGM.getLangOpts().Optimize)
1860     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1861 
1862   // In this debug mode, emit type info for a class when its constructor type
1863   // info is emitted.
1864   if (DebugKind == codegenoptions::DebugInfoConstructor)
1865     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1866       completeUnusedClass(*CD->getParent());
1867 
1868   llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1869   llvm::DISubprogram *SP = DBuilder.createMethod(
1870       RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1871       MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1872       TParamsArray.get());
1873 
1874   SPCache[Method->getCanonicalDecl()].reset(SP);
1875 
1876   return SP;
1877 }
1878 
1879 void CGDebugInfo::CollectCXXMemberFunctions(
1880     const CXXRecordDecl *RD, llvm::DIFile *Unit,
1881     SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1882 
1883   // Since we want more than just the individual member decls if we
1884   // have templated functions iterate over every declaration to gather
1885   // the functions.
1886   for (const auto *I : RD->decls()) {
1887     const auto *Method = dyn_cast<CXXMethodDecl>(I);
1888     // If the member is implicit, don't add it to the member list. This avoids
1889     // the member being added to type units by LLVM, while still allowing it
1890     // to be emitted into the type declaration/reference inside the compile
1891     // unit.
1892     // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1893     // FIXME: Handle Using(Shadow?)Decls here to create
1894     // DW_TAG_imported_declarations inside the class for base decls brought into
1895     // derived classes. GDB doesn't seem to notice/leverage these when I tried
1896     // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1897     // referenced)
1898     if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1899       continue;
1900 
1901     if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1902       continue;
1903 
1904     // Reuse the existing member function declaration if it exists.
1905     // It may be associated with the declaration of the type & should be
1906     // reused as we're building the definition.
1907     //
1908     // This situation can arise in the vtable-based debug info reduction where
1909     // implicit members are emitted in a non-vtable TU.
1910     auto MI = SPCache.find(Method->getCanonicalDecl());
1911     EltTys.push_back(MI == SPCache.end()
1912                          ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1913                          : static_cast<llvm::Metadata *>(MI->second));
1914   }
1915 }
1916 
1917 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1918                                   SmallVectorImpl<llvm::Metadata *> &EltTys,
1919                                   llvm::DIType *RecordTy) {
1920   llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1921   CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1922                      llvm::DINode::FlagZero);
1923 
1924   // If we are generating CodeView debug info, we also need to emit records for
1925   // indirect virtual base classes.
1926   if (CGM.getCodeGenOpts().EmitCodeView) {
1927     CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1928                        llvm::DINode::FlagIndirectVirtualBase);
1929   }
1930 }
1931 
1932 void CGDebugInfo::CollectCXXBasesAux(
1933     const CXXRecordDecl *RD, llvm::DIFile *Unit,
1934     SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1935     const CXXRecordDecl::base_class_const_range &Bases,
1936     llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1937     llvm::DINode::DIFlags StartingFlags) {
1938   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1939   for (const auto &BI : Bases) {
1940     const auto *Base =
1941         cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1942     if (!SeenTypes.insert(Base).second)
1943       continue;
1944     auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1945     llvm::DINode::DIFlags BFlags = StartingFlags;
1946     uint64_t BaseOffset;
1947     uint32_t VBPtrOffset = 0;
1948 
1949     if (BI.isVirtual()) {
1950       if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1951         // virtual base offset offset is -ve. The code generator emits dwarf
1952         // expression where it expects +ve number.
1953         BaseOffset = 0 - CGM.getItaniumVTableContext()
1954                              .getVirtualBaseOffsetOffset(RD, Base)
1955                              .getQuantity();
1956       } else {
1957         // In the MS ABI, store the vbtable offset, which is analogous to the
1958         // vbase offset offset in Itanium.
1959         BaseOffset =
1960             4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1961         VBPtrOffset = CGM.getContext()
1962                           .getASTRecordLayout(RD)
1963                           .getVBPtrOffset()
1964                           .getQuantity();
1965       }
1966       BFlags |= llvm::DINode::FlagVirtual;
1967     } else
1968       BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1969     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1970     // BI->isVirtual() and bits when not.
1971 
1972     BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1973     llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1974                                                    VBPtrOffset, BFlags);
1975     EltTys.push_back(DTy);
1976   }
1977 }
1978 
1979 llvm::DINodeArray
1980 CGDebugInfo::CollectTemplateParams(Optional<TemplateArgs> OArgs,
1981                                    llvm::DIFile *Unit) {
1982   if (!OArgs)
1983     return llvm::DINodeArray();
1984   TemplateArgs &Args = *OArgs;
1985   SmallVector<llvm::Metadata *, 16> TemplateParams;
1986   for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
1987     const TemplateArgument &TA = Args.Args[i];
1988     StringRef Name;
1989     bool defaultParameter = false;
1990     if (Args.TList)
1991       Name = Args.TList->getParam(i)->getName();
1992     switch (TA.getKind()) {
1993     case TemplateArgument::Type: {
1994       llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1995 
1996       if (Args.TList)
1997         if (auto *templateType =
1998                 dyn_cast_or_null<TemplateTypeParmDecl>(Args.TList->getParam(i)))
1999           if (templateType->hasDefaultArgument())
2000             defaultParameter =
2001                 templateType->getDefaultArgument() == TA.getAsType();
2002 
2003       TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2004           TheCU, Name, TTy, defaultParameter));
2005 
2006     } break;
2007     case TemplateArgument::Integral: {
2008       llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2009       if (Args.TList && CGM.getCodeGenOpts().DwarfVersion >= 5)
2010         if (auto *templateType = dyn_cast_or_null<NonTypeTemplateParmDecl>(
2011                 Args.TList->getParam(i)))
2012           if (templateType->hasDefaultArgument() &&
2013               !templateType->getDefaultArgument()->isValueDependent())
2014             defaultParameter = llvm::APSInt::isSameValue(
2015                 templateType->getDefaultArgument()->EvaluateKnownConstInt(
2016                     CGM.getContext()),
2017                 TA.getAsIntegral());
2018 
2019       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2020           TheCU, Name, TTy, defaultParameter,
2021           llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2022     } break;
2023     case TemplateArgument::Declaration: {
2024       const ValueDecl *D = TA.getAsDecl();
2025       QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
2026       llvm::DIType *TTy = getOrCreateType(T, Unit);
2027       llvm::Constant *V = nullptr;
2028       // Skip retrieve the value if that template parameter has cuda device
2029       // attribute, i.e. that value is not available at the host side.
2030       if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2031           !D->hasAttr<CUDADeviceAttr>()) {
2032         const CXXMethodDecl *MD;
2033         // Variable pointer template parameters have a value that is the address
2034         // of the variable.
2035         if (const auto *VD = dyn_cast<VarDecl>(D))
2036           V = CGM.GetAddrOfGlobalVar(VD);
2037         // Member function pointers have special support for building them,
2038         // though this is currently unsupported in LLVM CodeGen.
2039         else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
2040           V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
2041         else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2042           V = CGM.GetAddrOfFunction(FD);
2043         // Member data pointers have special handling too to compute the fixed
2044         // offset within the object.
2045         else if (const auto *MPT =
2046                      dyn_cast<MemberPointerType>(T.getTypePtr())) {
2047           // These five lines (& possibly the above member function pointer
2048           // handling) might be able to be refactored to use similar code in
2049           // CodeGenModule::getMemberPointerConstant
2050           uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2051           CharUnits chars =
2052               CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2053           V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2054         } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2055           V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2056         } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2057           if (T->isRecordType())
2058             V = ConstantEmitter(CGM).emitAbstract(
2059                 SourceLocation(), TPO->getValue(), TPO->getType());
2060           else
2061             V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
2062         }
2063         assert(V && "Failed to find template parameter pointer");
2064         V = V->stripPointerCasts();
2065       }
2066       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2067           TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2068     } break;
2069     case TemplateArgument::NullPtr: {
2070       QualType T = TA.getNullPtrType();
2071       llvm::DIType *TTy = getOrCreateType(T, Unit);
2072       llvm::Constant *V = nullptr;
2073       // Special case member data pointer null values since they're actually -1
2074       // instead of zero.
2075       if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2076         // But treat member function pointers as simple zero integers because
2077         // it's easier than having a special case in LLVM's CodeGen. If LLVM
2078         // CodeGen grows handling for values of non-null member function
2079         // pointers then perhaps we could remove this special case and rely on
2080         // EmitNullMemberPointer for member function pointers.
2081         if (MPT->isMemberDataPointer())
2082           V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2083       if (!V)
2084         V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2085       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2086           TheCU, Name, TTy, defaultParameter, V));
2087     } break;
2088     case TemplateArgument::Template: {
2089       std::string QualName;
2090       llvm::raw_string_ostream OS(QualName);
2091       TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName(
2092           OS, getPrintingPolicy());
2093       TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2094           TheCU, Name, nullptr, OS.str()));
2095       break;
2096     }
2097     case TemplateArgument::Pack:
2098       TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2099           TheCU, Name, nullptr,
2100           CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2101       break;
2102     case TemplateArgument::Expression: {
2103       const Expr *E = TA.getAsExpr();
2104       QualType T = E->getType();
2105       if (E->isGLValue())
2106         T = CGM.getContext().getLValueReferenceType(T);
2107       llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2108       assert(V && "Expression in template argument isn't constant");
2109       llvm::DIType *TTy = getOrCreateType(T, Unit);
2110       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2111           TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2112     } break;
2113     // And the following should never occur:
2114     case TemplateArgument::TemplateExpansion:
2115     case TemplateArgument::Null:
2116       llvm_unreachable(
2117           "These argument types shouldn't exist in concrete types");
2118     }
2119   }
2120   return DBuilder.getOrCreateArray(TemplateParams);
2121 }
2122 
2123 Optional<CGDebugInfo::TemplateArgs>
2124 CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2125   if (FD->getTemplatedKind() ==
2126       FunctionDecl::TK_FunctionTemplateSpecialization) {
2127     const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2128                                              ->getTemplate()
2129                                              ->getTemplateParameters();
2130     return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2131   }
2132   return None;
2133 }
2134 Optional<CGDebugInfo::TemplateArgs>
2135 CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2136   // Always get the full list of parameters, not just the ones from the
2137   // specialization. A partial specialization may have fewer parameters than
2138   // there are arguments.
2139   auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2140   if (!TS)
2141     return None;
2142   VarTemplateDecl *T = TS->getSpecializedTemplate();
2143   const TemplateParameterList *TList = T->getTemplateParameters();
2144   auto TA = TS->getTemplateArgs().asArray();
2145   return {{TList, TA}};
2146 }
2147 Optional<CGDebugInfo::TemplateArgs>
2148 CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2149   if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2150     // Always get the full list of parameters, not just the ones from the
2151     // specialization. A partial specialization may have fewer parameters than
2152     // there are arguments.
2153     TemplateParameterList *TPList =
2154         TSpecial->getSpecializedTemplate()->getTemplateParameters();
2155     const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2156     return {{TPList, TAList.asArray()}};
2157   }
2158   return None;
2159 }
2160 
2161 llvm::DINodeArray
2162 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2163                                            llvm::DIFile *Unit) {
2164   return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2165 }
2166 
2167 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2168                                                         llvm::DIFile *Unit) {
2169   return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2170 }
2171 
2172 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2173                                                         llvm::DIFile *Unit) {
2174   return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2175 }
2176 
2177 llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2178   if (!D->hasAttr<BTFDeclTagAttr>())
2179     return nullptr;
2180 
2181   SmallVector<llvm::Metadata *, 4> Annotations;
2182   for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2183     llvm::Metadata *Ops[2] = {
2184         llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2185         llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2186     Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2187   }
2188   return DBuilder.getOrCreateArray(Annotations);
2189 }
2190 
2191 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2192   if (VTablePtrType)
2193     return VTablePtrType;
2194 
2195   ASTContext &Context = CGM.getContext();
2196 
2197   /* Function type */
2198   llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2199   llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2200   llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2201   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2202   unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2203   Optional<unsigned> DWARFAddressSpace =
2204       CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2205 
2206   llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2207       SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2208   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2209   return VTablePtrType;
2210 }
2211 
2212 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2213   // Copy the gdb compatible name on the side and use its reference.
2214   return internString("_vptr$", RD->getNameAsString());
2215 }
2216 
2217 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2218                                                  DynamicInitKind StubKind,
2219                                                  llvm::Function *InitFn) {
2220   // If we're not emitting codeview, use the mangled name. For Itanium, this is
2221   // arbitrary.
2222   if (!CGM.getCodeGenOpts().EmitCodeView ||
2223       StubKind == DynamicInitKind::GlobalArrayDestructor)
2224     return InitFn->getName();
2225 
2226   // Print the normal qualified name for the variable, then break off the last
2227   // NNS, and add the appropriate other text. Clang always prints the global
2228   // variable name without template arguments, so we can use rsplit("::") and
2229   // then recombine the pieces.
2230   SmallString<128> QualifiedGV;
2231   StringRef Quals;
2232   StringRef GVName;
2233   {
2234     llvm::raw_svector_ostream OS(QualifiedGV);
2235     VD->printQualifiedName(OS, getPrintingPolicy());
2236     std::tie(Quals, GVName) = OS.str().rsplit("::");
2237     if (GVName.empty())
2238       std::swap(Quals, GVName);
2239   }
2240 
2241   SmallString<128> InitName;
2242   llvm::raw_svector_ostream OS(InitName);
2243   if (!Quals.empty())
2244     OS << Quals << "::";
2245 
2246   switch (StubKind) {
2247   case DynamicInitKind::NoStub:
2248   case DynamicInitKind::GlobalArrayDestructor:
2249     llvm_unreachable("not an initializer");
2250   case DynamicInitKind::Initializer:
2251     OS << "`dynamic initializer for '";
2252     break;
2253   case DynamicInitKind::AtExit:
2254     OS << "`dynamic atexit destructor for '";
2255     break;
2256   }
2257 
2258   OS << GVName;
2259 
2260   // Add any template specialization args.
2261   if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2262     printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2263                               getPrintingPolicy());
2264   }
2265 
2266   OS << '\'';
2267 
2268   return internString(OS.str());
2269 }
2270 
2271 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2272                                     SmallVectorImpl<llvm::Metadata *> &EltTys) {
2273   // If this class is not dynamic then there is not any vtable info to collect.
2274   if (!RD->isDynamicClass())
2275     return;
2276 
2277   // Don't emit any vtable shape or vptr info if this class doesn't have an
2278   // extendable vfptr. This can happen if the class doesn't have virtual
2279   // methods, or in the MS ABI if those virtual methods only come from virtually
2280   // inherited bases.
2281   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2282   if (!RL.hasExtendableVFPtr())
2283     return;
2284 
2285   // CodeView needs to know how large the vtable of every dynamic class is, so
2286   // emit a special named pointer type into the element list. The vptr type
2287   // points to this type as well.
2288   llvm::DIType *VPtrTy = nullptr;
2289   bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2290                          CGM.getTarget().getCXXABI().isMicrosoft();
2291   if (NeedVTableShape) {
2292     uint64_t PtrWidth =
2293         CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2294     const VTableLayout &VFTLayout =
2295         CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2296     unsigned VSlotCount =
2297         VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2298     unsigned VTableWidth = PtrWidth * VSlotCount;
2299     unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2300     Optional<unsigned> DWARFAddressSpace =
2301         CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2302 
2303     // Create a very wide void* type and insert it directly in the element list.
2304     llvm::DIType *VTableType = DBuilder.createPointerType(
2305         nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2306     EltTys.push_back(VTableType);
2307 
2308     // The vptr is a pointer to this special vtable type.
2309     VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2310   }
2311 
2312   // If there is a primary base then the artificial vptr member lives there.
2313   if (RL.getPrimaryBase())
2314     return;
2315 
2316   if (!VPtrTy)
2317     VPtrTy = getOrCreateVTablePtrType(Unit);
2318 
2319   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2320   llvm::DIType *VPtrMember =
2321       DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2322                                 llvm::DINode::FlagArtificial, VPtrTy);
2323   EltTys.push_back(VPtrMember);
2324 }
2325 
2326 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2327                                                  SourceLocation Loc) {
2328   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2329   llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2330   return T;
2331 }
2332 
2333 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2334                                                     SourceLocation Loc) {
2335   return getOrCreateStandaloneType(D, Loc);
2336 }
2337 
2338 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2339                                                      SourceLocation Loc) {
2340   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2341   assert(!D.isNull() && "null type");
2342   llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2343   assert(T && "could not create debug info for type");
2344 
2345   RetainedTypes.push_back(D.getAsOpaquePtr());
2346   return T;
2347 }
2348 
2349 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2350                                            QualType AllocatedTy,
2351                                            SourceLocation Loc) {
2352   if (CGM.getCodeGenOpts().getDebugInfo() <=
2353       codegenoptions::DebugLineTablesOnly)
2354     return;
2355   llvm::MDNode *node;
2356   if (AllocatedTy->isVoidType())
2357     node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2358   else
2359     node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2360 
2361   CI->setMetadata("heapallocsite", node);
2362 }
2363 
2364 void CGDebugInfo::completeType(const EnumDecl *ED) {
2365   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2366     return;
2367   QualType Ty = CGM.getContext().getEnumType(ED);
2368   void *TyPtr = Ty.getAsOpaquePtr();
2369   auto I = TypeCache.find(TyPtr);
2370   if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2371     return;
2372   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2373   assert(!Res->isForwardDecl());
2374   TypeCache[TyPtr].reset(Res);
2375 }
2376 
2377 void CGDebugInfo::completeType(const RecordDecl *RD) {
2378   if (DebugKind > codegenoptions::LimitedDebugInfo ||
2379       !CGM.getLangOpts().CPlusPlus)
2380     completeRequiredType(RD);
2381 }
2382 
2383 /// Return true if the class or any of its methods are marked dllimport.
2384 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2385   if (RD->hasAttr<DLLImportAttr>())
2386     return true;
2387   for (const CXXMethodDecl *MD : RD->methods())
2388     if (MD->hasAttr<DLLImportAttr>())
2389       return true;
2390   return false;
2391 }
2392 
2393 /// Does a type definition exist in an imported clang module?
2394 static bool isDefinedInClangModule(const RecordDecl *RD) {
2395   // Only definitions that where imported from an AST file come from a module.
2396   if (!RD || !RD->isFromASTFile())
2397     return false;
2398   // Anonymous entities cannot be addressed. Treat them as not from module.
2399   if (!RD->isExternallyVisible() && RD->getName().empty())
2400     return false;
2401   if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2402     if (!CXXDecl->isCompleteDefinition())
2403       return false;
2404     // Check wether RD is a template.
2405     auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2406     if (TemplateKind != TSK_Undeclared) {
2407       // Unfortunately getOwningModule() isn't accurate enough to find the
2408       // owning module of a ClassTemplateSpecializationDecl that is inside a
2409       // namespace spanning multiple modules.
2410       bool Explicit = false;
2411       if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2412         Explicit = TD->isExplicitInstantiationOrSpecialization();
2413       if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2414         return false;
2415       // This is a template, check the origin of the first member.
2416       if (CXXDecl->field_begin() == CXXDecl->field_end())
2417         return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2418       if (!CXXDecl->field_begin()->isFromASTFile())
2419         return false;
2420     }
2421   }
2422   return true;
2423 }
2424 
2425 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2426   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2427     if (CXXRD->isDynamicClass() &&
2428         CGM.getVTableLinkage(CXXRD) ==
2429             llvm::GlobalValue::AvailableExternallyLinkage &&
2430         !isClassOrMethodDLLImport(CXXRD))
2431       return;
2432 
2433   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2434     return;
2435 
2436   completeClass(RD);
2437 }
2438 
2439 void CGDebugInfo::completeClass(const RecordDecl *RD) {
2440   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2441     return;
2442   QualType Ty = CGM.getContext().getRecordType(RD);
2443   void *TyPtr = Ty.getAsOpaquePtr();
2444   auto I = TypeCache.find(TyPtr);
2445   if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2446     return;
2447   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2448   assert(!Res->isForwardDecl());
2449   TypeCache[TyPtr].reset(Res);
2450 }
2451 
2452 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2453                                         CXXRecordDecl::method_iterator End) {
2454   for (CXXMethodDecl *MD : llvm::make_range(I, End))
2455     if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2456       if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2457           !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2458         return true;
2459   return false;
2460 }
2461 
2462 static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2463   // Constructor homing can be used for classes that cannnot be constructed
2464   // without emitting code for one of their constructors. This is classes that
2465   // don't have trivial or constexpr constructors, or can be created from
2466   // aggregate initialization. Also skip lambda objects because they don't call
2467   // constructors.
2468 
2469   // Skip this optimization if the class or any of its methods are marked
2470   // dllimport.
2471   if (isClassOrMethodDLLImport(RD))
2472     return false;
2473 
2474   return !RD->isLambda() && !RD->isAggregate() &&
2475          !RD->hasTrivialDefaultConstructor() &&
2476          !RD->hasConstexprNonCopyMoveConstructor();
2477 }
2478 
2479 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2480                                  bool DebugTypeExtRefs, const RecordDecl *RD,
2481                                  const LangOptions &LangOpts) {
2482   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2483     return true;
2484 
2485   if (auto *ES = RD->getASTContext().getExternalSource())
2486     if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2487       return true;
2488 
2489   // Only emit forward declarations in line tables only to keep debug info size
2490   // small. This only applies to CodeView, since we don't emit types in DWARF
2491   // line tables only.
2492   if (DebugKind == codegenoptions::DebugLineTablesOnly)
2493     return true;
2494 
2495   if (DebugKind > codegenoptions::LimitedDebugInfo ||
2496       RD->hasAttr<StandaloneDebugAttr>())
2497     return false;
2498 
2499   if (!LangOpts.CPlusPlus)
2500     return false;
2501 
2502   if (!RD->isCompleteDefinitionRequired())
2503     return true;
2504 
2505   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2506 
2507   if (!CXXDecl)
2508     return false;
2509 
2510   // Only emit complete debug info for a dynamic class when its vtable is
2511   // emitted.  However, Microsoft debuggers don't resolve type information
2512   // across DLL boundaries, so skip this optimization if the class or any of its
2513   // methods are marked dllimport. This isn't a complete solution, since objects
2514   // without any dllimport methods can be used in one DLL and constructed in
2515   // another, but it is the current behavior of LimitedDebugInfo.
2516   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2517       !isClassOrMethodDLLImport(CXXDecl))
2518     return true;
2519 
2520   TemplateSpecializationKind Spec = TSK_Undeclared;
2521   if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2522     Spec = SD->getSpecializationKind();
2523 
2524   if (Spec == TSK_ExplicitInstantiationDeclaration &&
2525       hasExplicitMemberDefinition(CXXDecl->method_begin(),
2526                                   CXXDecl->method_end()))
2527     return true;
2528 
2529   // In constructor homing mode, only emit complete debug info for a class
2530   // when its constructor is emitted.
2531   if ((DebugKind == codegenoptions::DebugInfoConstructor) &&
2532       canUseCtorHoming(CXXDecl))
2533     return true;
2534 
2535   return false;
2536 }
2537 
2538 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2539   if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2540     return;
2541 
2542   QualType Ty = CGM.getContext().getRecordType(RD);
2543   llvm::DIType *T = getTypeOrNull(Ty);
2544   if (T && T->isForwardDecl())
2545     completeClassData(RD);
2546 }
2547 
2548 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2549   RecordDecl *RD = Ty->getDecl();
2550   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2551   if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2552                                 CGM.getLangOpts())) {
2553     if (!T)
2554       T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2555     return T;
2556   }
2557 
2558   return CreateTypeDefinition(Ty);
2559 }
2560 
2561 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2562   RecordDecl *RD = Ty->getDecl();
2563 
2564   // Get overall information about the record type for the debug info.
2565   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2566 
2567   // Records and classes and unions can all be recursive.  To handle them, we
2568   // first generate a debug descriptor for the struct as a forward declaration.
2569   // Then (if it is a definition) we go through and get debug info for all of
2570   // its members.  Finally, we create a descriptor for the complete type (which
2571   // may refer to the forward decl if the struct is recursive) and replace all
2572   // uses of the forward declaration with the final definition.
2573   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2574 
2575   const RecordDecl *D = RD->getDefinition();
2576   if (!D || !D->isCompleteDefinition())
2577     return FwdDecl;
2578 
2579   if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2580     CollectContainingType(CXXDecl, FwdDecl);
2581 
2582   // Push the struct on region stack.
2583   LexicalBlockStack.emplace_back(&*FwdDecl);
2584   RegionMap[Ty->getDecl()].reset(FwdDecl);
2585 
2586   // Convert all the elements.
2587   SmallVector<llvm::Metadata *, 16> EltTys;
2588   // what about nested types?
2589 
2590   // Note: The split of CXXDecl information here is intentional, the
2591   // gdb tests will depend on a certain ordering at printout. The debug
2592   // information offsets are still correct if we merge them all together
2593   // though.
2594   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2595   if (CXXDecl) {
2596     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2597     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2598   }
2599 
2600   // Collect data fields (including static variables and any initializers).
2601   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2602   if (CXXDecl)
2603     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2604 
2605   LexicalBlockStack.pop_back();
2606   RegionMap.erase(Ty->getDecl());
2607 
2608   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2609   DBuilder.replaceArrays(FwdDecl, Elements);
2610 
2611   if (FwdDecl->isTemporary())
2612     FwdDecl =
2613         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2614 
2615   RegionMap[Ty->getDecl()].reset(FwdDecl);
2616   return FwdDecl;
2617 }
2618 
2619 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2620                                       llvm::DIFile *Unit) {
2621   // Ignore protocols.
2622   return getOrCreateType(Ty->getBaseType(), Unit);
2623 }
2624 
2625 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2626                                       llvm::DIFile *Unit) {
2627   // Ignore protocols.
2628   SourceLocation Loc = Ty->getDecl()->getLocation();
2629 
2630   // Use Typedefs to represent ObjCTypeParamType.
2631   return DBuilder.createTypedef(
2632       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2633       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2634       getDeclContextDescriptor(Ty->getDecl()));
2635 }
2636 
2637 /// \return true if Getter has the default name for the property PD.
2638 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2639                                  const ObjCMethodDecl *Getter) {
2640   assert(PD);
2641   if (!Getter)
2642     return true;
2643 
2644   assert(Getter->getDeclName().isObjCZeroArgSelector());
2645   return PD->getName() ==
2646          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2647 }
2648 
2649 /// \return true if Setter has the default name for the property PD.
2650 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2651                                  const ObjCMethodDecl *Setter) {
2652   assert(PD);
2653   if (!Setter)
2654     return true;
2655 
2656   assert(Setter->getDeclName().isObjCOneArgSelector());
2657   return SelectorTable::constructSetterName(PD->getName()) ==
2658          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2659 }
2660 
2661 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2662                                       llvm::DIFile *Unit) {
2663   ObjCInterfaceDecl *ID = Ty->getDecl();
2664   if (!ID)
2665     return nullptr;
2666 
2667   // Return a forward declaration if this type was imported from a clang module,
2668   // and this is not the compile unit with the implementation of the type (which
2669   // may contain hidden ivars).
2670   if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2671       !ID->getImplementation())
2672     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2673                                       ID->getName(),
2674                                       getDeclContextDescriptor(ID), Unit, 0);
2675 
2676   // Get overall information about the record type for the debug info.
2677   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2678   unsigned Line = getLineNumber(ID->getLocation());
2679   auto RuntimeLang =
2680       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2681 
2682   // If this is just a forward declaration return a special forward-declaration
2683   // debug type since we won't be able to lay out the entire type.
2684   ObjCInterfaceDecl *Def = ID->getDefinition();
2685   if (!Def || !Def->getImplementation()) {
2686     llvm::DIScope *Mod = getParentModuleOrNull(ID);
2687     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2688         llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2689         DefUnit, Line, RuntimeLang);
2690     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2691     return FwdDecl;
2692   }
2693 
2694   return CreateTypeDefinition(Ty, Unit);
2695 }
2696 
2697 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2698                                                   bool CreateSkeletonCU) {
2699   // Use the Module pointer as the key into the cache. This is a
2700   // nullptr if the "Module" is a PCH, which is safe because we don't
2701   // support chained PCH debug info, so there can only be a single PCH.
2702   const Module *M = Mod.getModuleOrNull();
2703   auto ModRef = ModuleCache.find(M);
2704   if (ModRef != ModuleCache.end())
2705     return cast<llvm::DIModule>(ModRef->second);
2706 
2707   // Macro definitions that were defined with "-D" on the command line.
2708   SmallString<128> ConfigMacros;
2709   {
2710     llvm::raw_svector_ostream OS(ConfigMacros);
2711     const auto &PPOpts = CGM.getPreprocessorOpts();
2712     unsigned I = 0;
2713     // Translate the macro definitions back into a command line.
2714     for (auto &M : PPOpts.Macros) {
2715       if (++I > 1)
2716         OS << " ";
2717       const std::string &Macro = M.first;
2718       bool Undef = M.second;
2719       OS << "\"-" << (Undef ? 'U' : 'D');
2720       for (char c : Macro)
2721         switch (c) {
2722         case '\\':
2723           OS << "\\\\";
2724           break;
2725         case '"':
2726           OS << "\\\"";
2727           break;
2728         default:
2729           OS << c;
2730         }
2731       OS << '\"';
2732     }
2733   }
2734 
2735   bool IsRootModule = M ? !M->Parent : true;
2736   // When a module name is specified as -fmodule-name, that module gets a
2737   // clang::Module object, but it won't actually be built or imported; it will
2738   // be textual.
2739   if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2740     assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2741            "clang module without ASTFile must be specified by -fmodule-name");
2742 
2743   // Return a StringRef to the remapped Path.
2744   auto RemapPath = [this](StringRef Path) -> std::string {
2745     std::string Remapped = remapDIPath(Path);
2746     StringRef Relative(Remapped);
2747     StringRef CompDir = TheCU->getDirectory();
2748     if (Relative.consume_front(CompDir))
2749       Relative.consume_front(llvm::sys::path::get_separator());
2750 
2751     return Relative.str();
2752   };
2753 
2754   if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2755     // PCH files don't have a signature field in the control block,
2756     // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2757     // We use the lower 64 bits for debug info.
2758 
2759     uint64_t Signature = 0;
2760     if (const auto &ModSig = Mod.getSignature())
2761       Signature = ModSig.truncatedValue();
2762     else
2763       Signature = ~1ULL;
2764 
2765     llvm::DIBuilder DIB(CGM.getModule());
2766     SmallString<0> PCM;
2767     if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2768       PCM = Mod.getPath();
2769     llvm::sys::path::append(PCM, Mod.getASTFile());
2770     DIB.createCompileUnit(
2771         TheCU->getSourceLanguage(),
2772         // TODO: Support "Source" from external AST providers?
2773         DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2774         TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2775         llvm::DICompileUnit::FullDebug, Signature);
2776     DIB.finalize();
2777   }
2778 
2779   llvm::DIModule *Parent =
2780       IsRootModule ? nullptr
2781                    : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2782                                           CreateSkeletonCU);
2783   std::string IncludePath = Mod.getPath().str();
2784   llvm::DIModule *DIMod =
2785       DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2786                             RemapPath(IncludePath));
2787   ModuleCache[M].reset(DIMod);
2788   return DIMod;
2789 }
2790 
2791 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2792                                                 llvm::DIFile *Unit) {
2793   ObjCInterfaceDecl *ID = Ty->getDecl();
2794   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2795   unsigned Line = getLineNumber(ID->getLocation());
2796   unsigned RuntimeLang = TheCU->getSourceLanguage();
2797 
2798   // Bit size, align and offset of the type.
2799   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2800   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2801 
2802   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2803   if (ID->getImplementation())
2804     Flags |= llvm::DINode::FlagObjcClassComplete;
2805 
2806   llvm::DIScope *Mod = getParentModuleOrNull(ID);
2807   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2808       Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2809       nullptr, llvm::DINodeArray(), RuntimeLang);
2810 
2811   QualType QTy(Ty, 0);
2812   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2813 
2814   // Push the struct on region stack.
2815   LexicalBlockStack.emplace_back(RealDecl);
2816   RegionMap[Ty->getDecl()].reset(RealDecl);
2817 
2818   // Convert all the elements.
2819   SmallVector<llvm::Metadata *, 16> EltTys;
2820 
2821   ObjCInterfaceDecl *SClass = ID->getSuperClass();
2822   if (SClass) {
2823     llvm::DIType *SClassTy =
2824         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2825     if (!SClassTy)
2826       return nullptr;
2827 
2828     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2829                                                       llvm::DINode::FlagZero);
2830     EltTys.push_back(InhTag);
2831   }
2832 
2833   // Create entries for all of the properties.
2834   auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2835     SourceLocation Loc = PD->getLocation();
2836     llvm::DIFile *PUnit = getOrCreateFile(Loc);
2837     unsigned PLine = getLineNumber(Loc);
2838     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2839     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2840     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2841         PD->getName(), PUnit, PLine,
2842         hasDefaultGetterName(PD, Getter) ? ""
2843                                          : getSelectorName(PD->getGetterName()),
2844         hasDefaultSetterName(PD, Setter) ? ""
2845                                          : getSelectorName(PD->getSetterName()),
2846         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2847     EltTys.push_back(PropertyNode);
2848   };
2849   {
2850     // Use 'char' for the isClassProperty bit as DenseSet requires space for
2851     // empty/tombstone keys in the data type (and bool is too small for that).
2852     typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
2853     /// List of already emitted properties. Two distinct class and instance
2854     /// properties can share the same identifier (but not two instance
2855     /// properties or two class properties).
2856     llvm::DenseSet<IsClassAndIdent> PropertySet;
2857     /// Returns the IsClassAndIdent key for the given property.
2858     auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
2859       return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
2860     };
2861     for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2862       for (auto *PD : ClassExt->properties()) {
2863         PropertySet.insert(GetIsClassAndIdent(PD));
2864         AddProperty(PD);
2865       }
2866     for (const auto *PD : ID->properties()) {
2867       // Don't emit duplicate metadata for properties that were already in a
2868       // class extension.
2869       if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
2870         continue;
2871       AddProperty(PD);
2872     }
2873   }
2874 
2875   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2876   unsigned FieldNo = 0;
2877   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2878        Field = Field->getNextIvar(), ++FieldNo) {
2879     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2880     if (!FieldTy)
2881       return nullptr;
2882 
2883     StringRef FieldName = Field->getName();
2884 
2885     // Ignore unnamed fields.
2886     if (FieldName.empty())
2887       continue;
2888 
2889     // Get the location for the field.
2890     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2891     unsigned FieldLine = getLineNumber(Field->getLocation());
2892     QualType FType = Field->getType();
2893     uint64_t FieldSize = 0;
2894     uint32_t FieldAlign = 0;
2895 
2896     if (!FType->isIncompleteArrayType()) {
2897 
2898       // Bit size, align and offset of the type.
2899       FieldSize = Field->isBitField()
2900                       ? Field->getBitWidthValue(CGM.getContext())
2901                       : CGM.getContext().getTypeSize(FType);
2902       FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2903     }
2904 
2905     uint64_t FieldOffset;
2906     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2907       // We don't know the runtime offset of an ivar if we're using the
2908       // non-fragile ABI.  For bitfields, use the bit offset into the first
2909       // byte of storage of the bitfield.  For other fields, use zero.
2910       if (Field->isBitField()) {
2911         FieldOffset =
2912             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2913         FieldOffset %= CGM.getContext().getCharWidth();
2914       } else {
2915         FieldOffset = 0;
2916       }
2917     } else {
2918       FieldOffset = RL.getFieldOffset(FieldNo);
2919     }
2920 
2921     llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2922     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2923       Flags = llvm::DINode::FlagProtected;
2924     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2925       Flags = llvm::DINode::FlagPrivate;
2926     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2927       Flags = llvm::DINode::FlagPublic;
2928 
2929     llvm::MDNode *PropertyNode = nullptr;
2930     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2931       if (ObjCPropertyImplDecl *PImpD =
2932               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2933         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2934           SourceLocation Loc = PD->getLocation();
2935           llvm::DIFile *PUnit = getOrCreateFile(Loc);
2936           unsigned PLine = getLineNumber(Loc);
2937           ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2938           ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2939           PropertyNode = DBuilder.createObjCProperty(
2940               PD->getName(), PUnit, PLine,
2941               hasDefaultGetterName(PD, Getter)
2942                   ? ""
2943                   : getSelectorName(PD->getGetterName()),
2944               hasDefaultSetterName(PD, Setter)
2945                   ? ""
2946                   : getSelectorName(PD->getSetterName()),
2947               PD->getPropertyAttributes(),
2948               getOrCreateType(PD->getType(), PUnit));
2949         }
2950       }
2951     }
2952     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2953                                       FieldSize, FieldAlign, FieldOffset, Flags,
2954                                       FieldTy, PropertyNode);
2955     EltTys.push_back(FieldTy);
2956   }
2957 
2958   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2959   DBuilder.replaceArrays(RealDecl, Elements);
2960 
2961   LexicalBlockStack.pop_back();
2962   return RealDecl;
2963 }
2964 
2965 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2966                                       llvm::DIFile *Unit) {
2967   if (Ty->isExtVectorBoolType()) {
2968     // Boolean ext_vector_type(N) are special because their real element type
2969     // (bits of bit size) is not their Clang element type (_Bool of size byte).
2970     // For now, we pretend the boolean vector were actually a vector of bytes
2971     // (where each byte represents 8 bits of the actual vector).
2972     // FIXME Debug info should actually represent this proper as a vector mask
2973     // type.
2974     auto &Ctx = CGM.getContext();
2975     uint64_t Size = CGM.getContext().getTypeSize(Ty);
2976     uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
2977 
2978     // Construct the vector of 'char' type.
2979     QualType CharVecTy = Ctx.getVectorType(Ctx.CharTy, NumVectorBytes,
2980                                            VectorType::GenericVector);
2981     return CreateType(CharVecTy->getAs<VectorType>(), Unit);
2982   }
2983 
2984   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2985   int64_t Count = Ty->getNumElements();
2986 
2987   llvm::Metadata *Subscript;
2988   QualType QTy(Ty, 0);
2989   auto SizeExpr = SizeExprCache.find(QTy);
2990   if (SizeExpr != SizeExprCache.end())
2991     Subscript = DBuilder.getOrCreateSubrange(
2992         SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2993         nullptr /*upperBound*/, nullptr /*stride*/);
2994   else {
2995     auto *CountNode =
2996         llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2997             llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
2998     Subscript = DBuilder.getOrCreateSubrange(
2999         CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3000         nullptr /*stride*/);
3001   }
3002   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3003 
3004   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3005   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3006 
3007   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3008 }
3009 
3010 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3011                                       llvm::DIFile *Unit) {
3012   // FIXME: Create another debug type for matrices
3013   // For the time being, it treats it like a nested ArrayType.
3014 
3015   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3016   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3017   uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3018 
3019   // Create ranges for both dimensions.
3020   llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
3021   auto *ColumnCountNode =
3022       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3023           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3024   auto *RowCountNode =
3025       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3026           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3027   Subscripts.push_back(DBuilder.getOrCreateSubrange(
3028       ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3029       nullptr /*stride*/));
3030   Subscripts.push_back(DBuilder.getOrCreateSubrange(
3031       RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3032       nullptr /*stride*/));
3033   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3034   return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3035 }
3036 
3037 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3038   uint64_t Size;
3039   uint32_t Align;
3040 
3041   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3042   if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3043     Size = 0;
3044     Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
3045                                    CGM.getContext());
3046   } else if (Ty->isIncompleteArrayType()) {
3047     Size = 0;
3048     if (Ty->getElementType()->isIncompleteType())
3049       Align = 0;
3050     else
3051       Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3052   } else if (Ty->isIncompleteType()) {
3053     Size = 0;
3054     Align = 0;
3055   } else {
3056     // Size and align of the whole array, not the element type.
3057     Size = CGM.getContext().getTypeSize(Ty);
3058     Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3059   }
3060 
3061   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
3062   // interior arrays, do we care?  Why aren't nested arrays represented the
3063   // obvious/recursive way?
3064   SmallVector<llvm::Metadata *, 8> Subscripts;
3065   QualType EltTy(Ty, 0);
3066   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3067     // If the number of elements is known, then count is that number. Otherwise,
3068     // it's -1. This allows us to represent a subrange with an array of 0
3069     // elements, like this:
3070     //
3071     //   struct foo {
3072     //     int x[0];
3073     //   };
3074     int64_t Count = -1; // Count == -1 is an unbounded array.
3075     if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3076       Count = CAT->getSize().getZExtValue();
3077     else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3078       if (Expr *Size = VAT->getSizeExpr()) {
3079         Expr::EvalResult Result;
3080         if (Size->EvaluateAsInt(Result, CGM.getContext()))
3081           Count = Result.Val.getInt().getExtValue();
3082       }
3083     }
3084 
3085     auto SizeNode = SizeExprCache.find(EltTy);
3086     if (SizeNode != SizeExprCache.end())
3087       Subscripts.push_back(DBuilder.getOrCreateSubrange(
3088           SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3089           nullptr /*upperBound*/, nullptr /*stride*/));
3090     else {
3091       auto *CountNode =
3092           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3093               llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3094       Subscripts.push_back(DBuilder.getOrCreateSubrange(
3095           CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3096           nullptr /*stride*/));
3097     }
3098     EltTy = Ty->getElementType();
3099   }
3100 
3101   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3102 
3103   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3104                                   SubscriptArray);
3105 }
3106 
3107 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3108                                       llvm::DIFile *Unit) {
3109   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3110                                Ty->getPointeeType(), Unit);
3111 }
3112 
3113 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3114                                       llvm::DIFile *Unit) {
3115   llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3116   // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3117   if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3118       CGM.getCodeGenOpts().DwarfVersion < 4)
3119     Tag = llvm::dwarf::DW_TAG_reference_type;
3120 
3121   return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3122 }
3123 
3124 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3125                                       llvm::DIFile *U) {
3126   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3127   uint64_t Size = 0;
3128 
3129   if (!Ty->isIncompleteType()) {
3130     Size = CGM.getContext().getTypeSize(Ty);
3131 
3132     // Set the MS inheritance model. There is no flag for the unspecified model.
3133     if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3134       switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3135       case MSInheritanceModel::Single:
3136         Flags |= llvm::DINode::FlagSingleInheritance;
3137         break;
3138       case MSInheritanceModel::Multiple:
3139         Flags |= llvm::DINode::FlagMultipleInheritance;
3140         break;
3141       case MSInheritanceModel::Virtual:
3142         Flags |= llvm::DINode::FlagVirtualInheritance;
3143         break;
3144       case MSInheritanceModel::Unspecified:
3145         break;
3146       }
3147     }
3148   }
3149 
3150   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3151   if (Ty->isMemberDataPointerType())
3152     return DBuilder.createMemberPointerType(
3153         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3154         Flags);
3155 
3156   const FunctionProtoType *FPT =
3157       Ty->getPointeeType()->getAs<FunctionProtoType>();
3158   return DBuilder.createMemberPointerType(
3159       getOrCreateInstanceMethodType(
3160           CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
3161           FPT, U, false),
3162       ClassType, Size, /*Align=*/0, Flags);
3163 }
3164 
3165 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3166   auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3167   return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3168 }
3169 
3170 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3171   return getOrCreateType(Ty->getElementType(), U);
3172 }
3173 
3174 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3175   const EnumDecl *ED = Ty->getDecl();
3176 
3177   uint64_t Size = 0;
3178   uint32_t Align = 0;
3179   if (!ED->getTypeForDecl()->isIncompleteType()) {
3180     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3181     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3182   }
3183 
3184   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3185 
3186   bool isImportedFromModule =
3187       DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3188 
3189   // If this is just a forward declaration, construct an appropriately
3190   // marked node and just return it.
3191   if (isImportedFromModule || !ED->getDefinition()) {
3192     // Note that it is possible for enums to be created as part of
3193     // their own declcontext. In this case a FwdDecl will be created
3194     // twice. This doesn't cause a problem because both FwdDecls are
3195     // entered into the ReplaceMap: finalize() will replace the first
3196     // FwdDecl with the second and then replace the second with
3197     // complete type.
3198     llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3199     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3200     llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3201         llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3202 
3203     unsigned Line = getLineNumber(ED->getLocation());
3204     StringRef EDName = ED->getName();
3205     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3206         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3207         0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3208 
3209     ReplaceMap.emplace_back(
3210         std::piecewise_construct, std::make_tuple(Ty),
3211         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3212     return RetTy;
3213   }
3214 
3215   return CreateTypeDefinition(Ty);
3216 }
3217 
3218 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3219   const EnumDecl *ED = Ty->getDecl();
3220   uint64_t Size = 0;
3221   uint32_t Align = 0;
3222   if (!ED->getTypeForDecl()->isIncompleteType()) {
3223     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3224     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3225   }
3226 
3227   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3228 
3229   SmallVector<llvm::Metadata *, 16> Enumerators;
3230   ED = ED->getDefinition();
3231   for (const auto *Enum : ED->enumerators()) {
3232     Enumerators.push_back(
3233         DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3234   }
3235 
3236   // Return a CompositeType for the enum itself.
3237   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3238 
3239   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3240   unsigned Line = getLineNumber(ED->getLocation());
3241   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3242   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3243   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3244                                         Line, Size, Align, EltArray, ClassTy,
3245                                         Identifier, ED->isScoped());
3246 }
3247 
3248 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3249                                         unsigned MType, SourceLocation LineLoc,
3250                                         StringRef Name, StringRef Value) {
3251   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3252   return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3253 }
3254 
3255 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3256                                                     SourceLocation LineLoc,
3257                                                     SourceLocation FileLoc) {
3258   llvm::DIFile *FName = getOrCreateFile(FileLoc);
3259   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3260   return DBuilder.createTempMacroFile(Parent, Line, FName);
3261 }
3262 
3263 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3264   Qualifiers Quals;
3265   do {
3266     Qualifiers InnerQuals = T.getLocalQualifiers();
3267     // Qualifiers::operator+() doesn't like it if you add a Qualifier
3268     // that is already there.
3269     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3270     Quals += InnerQuals;
3271     QualType LastT = T;
3272     switch (T->getTypeClass()) {
3273     default:
3274       return C.getQualifiedType(T.getTypePtr(), Quals);
3275     case Type::TemplateSpecialization: {
3276       const auto *Spec = cast<TemplateSpecializationType>(T);
3277       if (Spec->isTypeAlias())
3278         return C.getQualifiedType(T.getTypePtr(), Quals);
3279       T = Spec->desugar();
3280       break;
3281     }
3282     case Type::TypeOfExpr:
3283       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3284       break;
3285     case Type::TypeOf:
3286       T = cast<TypeOfType>(T)->getUnderlyingType();
3287       break;
3288     case Type::Decltype:
3289       T = cast<DecltypeType>(T)->getUnderlyingType();
3290       break;
3291     case Type::UnaryTransform:
3292       T = cast<UnaryTransformType>(T)->getUnderlyingType();
3293       break;
3294     case Type::Attributed:
3295       T = cast<AttributedType>(T)->getEquivalentType();
3296       break;
3297     case Type::BTFTagAttributed:
3298       T = cast<BTFTagAttributedType>(T)->getWrappedType();
3299       break;
3300     case Type::Elaborated:
3301       T = cast<ElaboratedType>(T)->getNamedType();
3302       break;
3303     case Type::Using:
3304       T = cast<UsingType>(T)->getUnderlyingType();
3305       break;
3306     case Type::Paren:
3307       T = cast<ParenType>(T)->getInnerType();
3308       break;
3309     case Type::MacroQualified:
3310       T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3311       break;
3312     case Type::SubstTemplateTypeParm:
3313       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3314       break;
3315     case Type::Auto:
3316     case Type::DeducedTemplateSpecialization: {
3317       QualType DT = cast<DeducedType>(T)->getDeducedType();
3318       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3319       T = DT;
3320       break;
3321     }
3322     case Type::Adjusted:
3323     case Type::Decayed:
3324       // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3325       T = cast<AdjustedType>(T)->getAdjustedType();
3326       break;
3327     }
3328 
3329     assert(T != LastT && "Type unwrapping failed to unwrap!");
3330     (void)LastT;
3331   } while (true);
3332 }
3333 
3334 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3335   assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3336   auto It = TypeCache.find(Ty.getAsOpaquePtr());
3337   if (It != TypeCache.end()) {
3338     // Verify that the debug info still exists.
3339     if (llvm::Metadata *V = It->second)
3340       return cast<llvm::DIType>(V);
3341   }
3342 
3343   return nullptr;
3344 }
3345 
3346 void CGDebugInfo::completeTemplateDefinition(
3347     const ClassTemplateSpecializationDecl &SD) {
3348   completeUnusedClass(SD);
3349 }
3350 
3351 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3352   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3353     return;
3354 
3355   completeClassData(&D);
3356   // In case this type has no member function definitions being emitted, ensure
3357   // it is retained
3358   RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3359 }
3360 
3361 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3362   if (Ty.isNull())
3363     return nullptr;
3364 
3365   llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3366     std::string Name;
3367     llvm::raw_string_ostream OS(Name);
3368     Ty.print(OS, getPrintingPolicy());
3369     return Name;
3370   });
3371 
3372   // Unwrap the type as needed for debug information.
3373   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3374 
3375   if (auto *T = getTypeOrNull(Ty))
3376     return T;
3377 
3378   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3379   void *TyPtr = Ty.getAsOpaquePtr();
3380 
3381   // And update the type cache.
3382   TypeCache[TyPtr].reset(Res);
3383 
3384   return Res;
3385 }
3386 
3387 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3388   // A forward declaration inside a module header does not belong to the module.
3389   if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3390     return nullptr;
3391   if (DebugTypeExtRefs && D->isFromASTFile()) {
3392     // Record a reference to an imported clang module or precompiled header.
3393     auto *Reader = CGM.getContext().getExternalSource();
3394     auto Idx = D->getOwningModuleID();
3395     auto Info = Reader->getSourceDescriptor(Idx);
3396     if (Info)
3397       return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3398   } else if (ClangModuleMap) {
3399     // We are building a clang module or a precompiled header.
3400     //
3401     // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3402     // and it wouldn't be necessary to specify the parent scope
3403     // because the type is already unique by definition (it would look
3404     // like the output of -fno-standalone-debug). On the other hand,
3405     // the parent scope helps a consumer to quickly locate the object
3406     // file where the type's definition is located, so it might be
3407     // best to make this behavior a command line or debugger tuning
3408     // option.
3409     if (Module *M = D->getOwningModule()) {
3410       // This is a (sub-)module.
3411       auto Info = ASTSourceDescriptor(*M);
3412       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3413     } else {
3414       // This the precompiled header being built.
3415       return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3416     }
3417   }
3418 
3419   return nullptr;
3420 }
3421 
3422 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3423   // Handle qualifiers, which recursively handles what they refer to.
3424   if (Ty.hasLocalQualifiers())
3425     return CreateQualifiedType(Ty, Unit);
3426 
3427   // Work out details of type.
3428   switch (Ty->getTypeClass()) {
3429 #define TYPE(Class, Base)
3430 #define ABSTRACT_TYPE(Class, Base)
3431 #define NON_CANONICAL_TYPE(Class, Base)
3432 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3433 #include "clang/AST/TypeNodes.inc"
3434     llvm_unreachable("Dependent types cannot show up in debug information");
3435 
3436   case Type::ExtVector:
3437   case Type::Vector:
3438     return CreateType(cast<VectorType>(Ty), Unit);
3439   case Type::ConstantMatrix:
3440     return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3441   case Type::ObjCObjectPointer:
3442     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3443   case Type::ObjCObject:
3444     return CreateType(cast<ObjCObjectType>(Ty), Unit);
3445   case Type::ObjCTypeParam:
3446     return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3447   case Type::ObjCInterface:
3448     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3449   case Type::Builtin:
3450     return CreateType(cast<BuiltinType>(Ty));
3451   case Type::Complex:
3452     return CreateType(cast<ComplexType>(Ty));
3453   case Type::Pointer:
3454     return CreateType(cast<PointerType>(Ty), Unit);
3455   case Type::BlockPointer:
3456     return CreateType(cast<BlockPointerType>(Ty), Unit);
3457   case Type::Typedef:
3458     return CreateType(cast<TypedefType>(Ty), Unit);
3459   case Type::Record:
3460     return CreateType(cast<RecordType>(Ty));
3461   case Type::Enum:
3462     return CreateEnumType(cast<EnumType>(Ty));
3463   case Type::FunctionProto:
3464   case Type::FunctionNoProto:
3465     return CreateType(cast<FunctionType>(Ty), Unit);
3466   case Type::ConstantArray:
3467   case Type::VariableArray:
3468   case Type::IncompleteArray:
3469     return CreateType(cast<ArrayType>(Ty), Unit);
3470 
3471   case Type::LValueReference:
3472     return CreateType(cast<LValueReferenceType>(Ty), Unit);
3473   case Type::RValueReference:
3474     return CreateType(cast<RValueReferenceType>(Ty), Unit);
3475 
3476   case Type::MemberPointer:
3477     return CreateType(cast<MemberPointerType>(Ty), Unit);
3478 
3479   case Type::Atomic:
3480     return CreateType(cast<AtomicType>(Ty), Unit);
3481 
3482   case Type::BitInt:
3483     return CreateType(cast<BitIntType>(Ty));
3484   case Type::Pipe:
3485     return CreateType(cast<PipeType>(Ty), Unit);
3486 
3487   case Type::TemplateSpecialization:
3488     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3489 
3490   case Type::Auto:
3491   case Type::Attributed:
3492   case Type::BTFTagAttributed:
3493   case Type::Adjusted:
3494   case Type::Decayed:
3495   case Type::DeducedTemplateSpecialization:
3496   case Type::Elaborated:
3497   case Type::Using:
3498   case Type::Paren:
3499   case Type::MacroQualified:
3500   case Type::SubstTemplateTypeParm:
3501   case Type::TypeOfExpr:
3502   case Type::TypeOf:
3503   case Type::Decltype:
3504   case Type::UnaryTransform:
3505     break;
3506   }
3507 
3508   llvm_unreachable("type should have been unwrapped!");
3509 }
3510 
3511 llvm::DICompositeType *
3512 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3513   QualType QTy(Ty, 0);
3514 
3515   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3516 
3517   // We may have cached a forward decl when we could have created
3518   // a non-forward decl. Go ahead and create a non-forward decl
3519   // now.
3520   if (T && !T->isForwardDecl())
3521     return T;
3522 
3523   // Otherwise create the type.
3524   llvm::DICompositeType *Res = CreateLimitedType(Ty);
3525 
3526   // Propagate members from the declaration to the definition
3527   // CreateType(const RecordType*) will overwrite this with the members in the
3528   // correct order if the full type is needed.
3529   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3530 
3531   // And update the type cache.
3532   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3533   return Res;
3534 }
3535 
3536 // TODO: Currently used for context chains when limiting debug info.
3537 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3538   RecordDecl *RD = Ty->getDecl();
3539 
3540   // Get overall information about the record type for the debug info.
3541   StringRef RDName = getClassName(RD);
3542   const SourceLocation Loc = RD->getLocation();
3543   llvm::DIFile *DefUnit = nullptr;
3544   unsigned Line = 0;
3545   if (Loc.isValid()) {
3546     DefUnit = getOrCreateFile(Loc);
3547     Line = getLineNumber(Loc);
3548   }
3549 
3550   llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3551 
3552   // If we ended up creating the type during the context chain construction,
3553   // just return that.
3554   auto *T = cast_or_null<llvm::DICompositeType>(
3555       getTypeOrNull(CGM.getContext().getRecordType(RD)));
3556   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3557     return T;
3558 
3559   // If this is just a forward or incomplete declaration, construct an
3560   // appropriately marked node and just return it.
3561   const RecordDecl *D = RD->getDefinition();
3562   if (!D || !D->isCompleteDefinition())
3563     return getOrCreateRecordFwdDecl(Ty, RDContext);
3564 
3565   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3566   // __attribute__((aligned)) can increase or decrease alignment *except* on a
3567   // struct or struct member, where it only increases  alignment unless 'packed'
3568   // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3569   // to be used.
3570   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3571 
3572   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3573 
3574   // Explicitly record the calling convention and export symbols for C++
3575   // records.
3576   auto Flags = llvm::DINode::FlagZero;
3577   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3578     if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3579       Flags |= llvm::DINode::FlagTypePassByReference;
3580     else
3581       Flags |= llvm::DINode::FlagTypePassByValue;
3582 
3583     // Record if a C++ record is non-trivial type.
3584     if (!CXXRD->isTrivial())
3585       Flags |= llvm::DINode::FlagNonTrivial;
3586 
3587     // Record exports it symbols to the containing structure.
3588     if (CXXRD->isAnonymousStructOrUnion())
3589         Flags |= llvm::DINode::FlagExportSymbols;
3590 
3591     Flags |= getAccessFlag(CXXRD->getAccess(),
3592                            dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3593   }
3594 
3595   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3596   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3597       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3598       Flags, Identifier, Annotations);
3599 
3600   // Elements of composite types usually have back to the type, creating
3601   // uniquing cycles.  Distinct nodes are more efficient.
3602   switch (RealDecl->getTag()) {
3603   default:
3604     llvm_unreachable("invalid composite type tag");
3605 
3606   case llvm::dwarf::DW_TAG_array_type:
3607   case llvm::dwarf::DW_TAG_enumeration_type:
3608     // Array elements and most enumeration elements don't have back references,
3609     // so they don't tend to be involved in uniquing cycles and there is some
3610     // chance of merging them when linking together two modules.  Only make
3611     // them distinct if they are ODR-uniqued.
3612     if (Identifier.empty())
3613       break;
3614     LLVM_FALLTHROUGH;
3615 
3616   case llvm::dwarf::DW_TAG_structure_type:
3617   case llvm::dwarf::DW_TAG_union_type:
3618   case llvm::dwarf::DW_TAG_class_type:
3619     // Immediately resolve to a distinct node.
3620     RealDecl =
3621         llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3622     break;
3623   }
3624 
3625   RegionMap[Ty->getDecl()].reset(RealDecl);
3626   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3627 
3628   if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3629     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3630                            CollectCXXTemplateParams(TSpecial, DefUnit));
3631   return RealDecl;
3632 }
3633 
3634 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3635                                         llvm::DICompositeType *RealDecl) {
3636   // A class's primary base or the class itself contains the vtable.
3637   llvm::DICompositeType *ContainingType = nullptr;
3638   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3639   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3640     // Seek non-virtual primary base root.
3641     while (true) {
3642       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3643       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3644       if (PBT && !BRL.isPrimaryBaseVirtual())
3645         PBase = PBT;
3646       else
3647         break;
3648     }
3649     ContainingType = cast<llvm::DICompositeType>(
3650         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3651                         getOrCreateFile(RD->getLocation())));
3652   } else if (RD->isDynamicClass())
3653     ContainingType = RealDecl;
3654 
3655   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3656 }
3657 
3658 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3659                                             StringRef Name, uint64_t *Offset) {
3660   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3661   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3662   auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3663   llvm::DIType *Ty =
3664       DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3665                                 *Offset, llvm::DINode::FlagZero, FieldTy);
3666   *Offset += FieldSize;
3667   return Ty;
3668 }
3669 
3670 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3671                                            StringRef &Name,
3672                                            StringRef &LinkageName,
3673                                            llvm::DIScope *&FDContext,
3674                                            llvm::DINodeArray &TParamsArray,
3675                                            llvm::DINode::DIFlags &Flags) {
3676   const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
3677   Name = getFunctionName(FD);
3678   // Use mangled name as linkage name for C/C++ functions.
3679   if (FD->getType()->getAs<FunctionProtoType>())
3680     LinkageName = CGM.getMangledName(GD);
3681   if (FD->hasPrototype())
3682     Flags |= llvm::DINode::FlagPrototyped;
3683   // No need to replicate the linkage name if it isn't different from the
3684   // subprogram name, no need to have it at all unless coverage is enabled or
3685   // debug is set to more than just line tables or extra debug info is needed.
3686   if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3687                               !CGM.getCodeGenOpts().EmitGcovNotes &&
3688                               !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3689                               !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
3690                               DebugKind <= codegenoptions::DebugLineTablesOnly))
3691     LinkageName = StringRef();
3692 
3693   // Emit the function scope in line tables only mode (if CodeView) to
3694   // differentiate between function names.
3695   if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3696       (DebugKind == codegenoptions::DebugLineTablesOnly &&
3697        CGM.getCodeGenOpts().EmitCodeView)) {
3698     if (const NamespaceDecl *NSDecl =
3699             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3700       FDContext = getOrCreateNamespace(NSDecl);
3701     else if (const RecordDecl *RDecl =
3702                  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3703       llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3704       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3705     }
3706   }
3707   if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3708     // Check if it is a noreturn-marked function
3709     if (FD->isNoReturn())
3710       Flags |= llvm::DINode::FlagNoReturn;
3711     // Collect template parameters.
3712     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3713   }
3714 }
3715 
3716 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3717                                       unsigned &LineNo, QualType &T,
3718                                       StringRef &Name, StringRef &LinkageName,
3719                                       llvm::MDTuple *&TemplateParameters,
3720                                       llvm::DIScope *&VDContext) {
3721   Unit = getOrCreateFile(VD->getLocation());
3722   LineNo = getLineNumber(VD->getLocation());
3723 
3724   setLocation(VD->getLocation());
3725 
3726   T = VD->getType();
3727   if (T->isIncompleteArrayType()) {
3728     // CodeGen turns int[] into int[1] so we'll do the same here.
3729     llvm::APInt ConstVal(32, 1);
3730     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3731 
3732     T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3733                                               ArrayType::Normal, 0);
3734   }
3735 
3736   Name = VD->getName();
3737   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3738       !isa<ObjCMethodDecl>(VD->getDeclContext()))
3739     LinkageName = CGM.getMangledName(VD);
3740   if (LinkageName == Name)
3741     LinkageName = StringRef();
3742 
3743   if (isa<VarTemplateSpecializationDecl>(VD)) {
3744     llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3745     TemplateParameters = parameterNodes.get();
3746   } else {
3747     TemplateParameters = nullptr;
3748   }
3749 
3750   // Since we emit declarations (DW_AT_members) for static members, place the
3751   // definition of those static members in the namespace they were declared in
3752   // in the source code (the lexical decl context).
3753   // FIXME: Generalize this for even non-member global variables where the
3754   // declaration and definition may have different lexical decl contexts, once
3755   // we have support for emitting declarations of (non-member) global variables.
3756   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3757                                                    : VD->getDeclContext();
3758   // When a record type contains an in-line initialization of a static data
3759   // member, and the record type is marked as __declspec(dllexport), an implicit
3760   // definition of the member will be created in the record context.  DWARF
3761   // doesn't seem to have a nice way to describe this in a form that consumers
3762   // are likely to understand, so fake the "normal" situation of a definition
3763   // outside the class by putting it in the global scope.
3764   if (DC->isRecord())
3765     DC = CGM.getContext().getTranslationUnitDecl();
3766 
3767   llvm::DIScope *Mod = getParentModuleOrNull(VD);
3768   VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3769 }
3770 
3771 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3772                                                           bool Stub) {
3773   llvm::DINodeArray TParamsArray;
3774   StringRef Name, LinkageName;
3775   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3776   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3777   SourceLocation Loc = GD.getDecl()->getLocation();
3778   llvm::DIFile *Unit = getOrCreateFile(Loc);
3779   llvm::DIScope *DContext = Unit;
3780   unsigned Line = getLineNumber(Loc);
3781   collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3782                            Flags);
3783   auto *FD = cast<FunctionDecl>(GD.getDecl());
3784 
3785   // Build function type.
3786   SmallVector<QualType, 16> ArgTypes;
3787   for (const ParmVarDecl *Parm : FD->parameters())
3788     ArgTypes.push_back(Parm->getType());
3789 
3790   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3791   QualType FnType = CGM.getContext().getFunctionType(
3792       FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3793   if (!FD->isExternallyVisible())
3794     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3795   if (CGM.getLangOpts().Optimize)
3796     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3797 
3798   if (Stub) {
3799     Flags |= getCallSiteRelatedAttrs();
3800     SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3801     return DBuilder.createFunction(
3802         DContext, Name, LinkageName, Unit, Line,
3803         getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3804         TParamsArray.get(), getFunctionDeclaration(FD));
3805   }
3806 
3807   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3808       DContext, Name, LinkageName, Unit, Line,
3809       getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3810       TParamsArray.get(), getFunctionDeclaration(FD));
3811   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3812   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3813                                  std::make_tuple(CanonDecl),
3814                                  std::make_tuple(SP));
3815   return SP;
3816 }
3817 
3818 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3819   return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3820 }
3821 
3822 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3823   return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3824 }
3825 
3826 llvm::DIGlobalVariable *
3827 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3828   QualType T;
3829   StringRef Name, LinkageName;
3830   SourceLocation Loc = VD->getLocation();
3831   llvm::DIFile *Unit = getOrCreateFile(Loc);
3832   llvm::DIScope *DContext = Unit;
3833   unsigned Line = getLineNumber(Loc);
3834   llvm::MDTuple *TemplateParameters = nullptr;
3835 
3836   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3837                       DContext);
3838   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3839   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3840       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3841       !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3842   FwdDeclReplaceMap.emplace_back(
3843       std::piecewise_construct,
3844       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3845       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3846   return GV;
3847 }
3848 
3849 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3850   // We only need a declaration (not a definition) of the type - so use whatever
3851   // we would otherwise do to get a type for a pointee. (forward declarations in
3852   // limited debug info, full definitions (if the type definition is available)
3853   // in unlimited debug info)
3854   if (const auto *TD = dyn_cast<TypeDecl>(D))
3855     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3856                            getOrCreateFile(TD->getLocation()));
3857   auto I = DeclCache.find(D->getCanonicalDecl());
3858 
3859   if (I != DeclCache.end()) {
3860     auto N = I->second;
3861     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3862       return GVE->getVariable();
3863     return cast<llvm::DINode>(N);
3864   }
3865 
3866   // Search imported declaration cache if it is already defined
3867   // as imported declaration.
3868   auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
3869 
3870   if (IE != ImportedDeclCache.end()) {
3871     auto N = IE->second;
3872     if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
3873       return cast<llvm::DINode>(GVE);
3874     return dyn_cast_or_null<llvm::DINode>(N);
3875   }
3876 
3877   // No definition for now. Emit a forward definition that might be
3878   // merged with a potential upcoming definition.
3879   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3880     return getFunctionForwardDeclaration(FD);
3881   else if (const auto *VD = dyn_cast<VarDecl>(D))
3882     return getGlobalVariableForwardDeclaration(VD);
3883 
3884   return nullptr;
3885 }
3886 
3887 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3888   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3889     return nullptr;
3890 
3891   const auto *FD = dyn_cast<FunctionDecl>(D);
3892   if (!FD)
3893     return nullptr;
3894 
3895   // Setup context.
3896   auto *S = getDeclContextDescriptor(D);
3897 
3898   auto MI = SPCache.find(FD->getCanonicalDecl());
3899   if (MI == SPCache.end()) {
3900     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3901       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3902                                      cast<llvm::DICompositeType>(S));
3903     }
3904   }
3905   if (MI != SPCache.end()) {
3906     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3907     if (SP && !SP->isDefinition())
3908       return SP;
3909   }
3910 
3911   for (auto NextFD : FD->redecls()) {
3912     auto MI = SPCache.find(NextFD->getCanonicalDecl());
3913     if (MI != SPCache.end()) {
3914       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3915       if (SP && !SP->isDefinition())
3916         return SP;
3917     }
3918   }
3919   return nullptr;
3920 }
3921 
3922 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3923     const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3924     llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3925   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3926     return nullptr;
3927 
3928   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3929   if (!OMD)
3930     return nullptr;
3931 
3932   if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3933     return nullptr;
3934 
3935   if (OMD->isDirectMethod())
3936     SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3937 
3938   // Starting with DWARF V5 method declarations are emitted as children of
3939   // the interface type.
3940   auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3941   if (!ID)
3942     ID = OMD->getClassInterface();
3943   if (!ID)
3944     return nullptr;
3945   QualType QTy(ID->getTypeForDecl(), 0);
3946   auto It = TypeCache.find(QTy.getAsOpaquePtr());
3947   if (It == TypeCache.end())
3948     return nullptr;
3949   auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3950   llvm::DISubprogram *FD = DBuilder.createFunction(
3951       InterfaceType, getObjCMethodName(OMD), StringRef(),
3952       InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3953   DBuilder.finalizeSubprogram(FD);
3954   ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3955   return FD;
3956 }
3957 
3958 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3959 // implicit parameter "this".
3960 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3961                                                              QualType FnType,
3962                                                              llvm::DIFile *F) {
3963   // In CodeView, we emit the function types in line tables only because the
3964   // only way to distinguish between functions is by display name and type.
3965   if (!D || (DebugKind <= codegenoptions::DebugLineTablesOnly &&
3966              !CGM.getCodeGenOpts().EmitCodeView))
3967     // Create fake but valid subroutine type. Otherwise -verify would fail, and
3968     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3969     return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3970 
3971   if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3972     return getOrCreateMethodType(Method, F, false);
3973 
3974   const auto *FTy = FnType->getAs<FunctionType>();
3975   CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3976 
3977   if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3978     // Add "self" and "_cmd"
3979     SmallVector<llvm::Metadata *, 16> Elts;
3980 
3981     // First element is always return type. For 'void' functions it is NULL.
3982     QualType ResultTy = OMethod->getReturnType();
3983 
3984     // Replace the instancetype keyword with the actual type.
3985     if (ResultTy == CGM.getContext().getObjCInstanceType())
3986       ResultTy = CGM.getContext().getPointerType(
3987           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3988 
3989     Elts.push_back(getOrCreateType(ResultTy, F));
3990     // "self" pointer is always first argument.
3991     QualType SelfDeclTy;
3992     if (auto *SelfDecl = OMethod->getSelfDecl())
3993       SelfDeclTy = SelfDecl->getType();
3994     else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3995       if (FPT->getNumParams() > 1)
3996         SelfDeclTy = FPT->getParamType(0);
3997     if (!SelfDeclTy.isNull())
3998       Elts.push_back(
3999           CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4000     // "_cmd" pointer is always second argument.
4001     Elts.push_back(DBuilder.createArtificialType(
4002         getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4003     // Get rest of the arguments.
4004     for (const auto *PI : OMethod->parameters())
4005       Elts.push_back(getOrCreateType(PI->getType(), F));
4006     // Variadic methods need a special marker at the end of the type list.
4007     if (OMethod->isVariadic())
4008       Elts.push_back(DBuilder.createUnspecifiedParameter());
4009 
4010     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4011     return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4012                                          getDwarfCC(CC));
4013   }
4014 
4015   // Handle variadic function types; they need an additional
4016   // unspecified parameter.
4017   if (const auto *FD = dyn_cast<FunctionDecl>(D))
4018     if (FD->isVariadic()) {
4019       SmallVector<llvm::Metadata *, 16> EltTys;
4020       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4021       if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4022         for (QualType ParamType : FPT->param_types())
4023           EltTys.push_back(getOrCreateType(ParamType, F));
4024       EltTys.push_back(DBuilder.createUnspecifiedParameter());
4025       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4026       return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4027                                            getDwarfCC(CC));
4028     }
4029 
4030   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4031 }
4032 
4033 QualType
4034 CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy,
4035                              const SmallVectorImpl<const VarDecl *> &Args) {
4036   CallingConv CC = CallingConv::CC_C;
4037   if (FD)
4038     if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4039       CC = SrcFnTy->getCallConv();
4040   SmallVector<QualType, 16> ArgTypes;
4041   for (const VarDecl *VD : Args)
4042     ArgTypes.push_back(VD->getType());
4043   return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4044                                           FunctionProtoType::ExtProtoInfo(CC));
4045 }
4046 
4047 void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
4048                                     SourceLocation ScopeLoc, QualType FnType,
4049                                     llvm::Function *Fn, bool CurFuncIsThunk) {
4050   StringRef Name;
4051   StringRef LinkageName;
4052 
4053   FnBeginRegionCount.push_back(LexicalBlockStack.size());
4054 
4055   const Decl *D = GD.getDecl();
4056   bool HasDecl = (D != nullptr);
4057 
4058   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4059   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4060   llvm::DIFile *Unit = getOrCreateFile(Loc);
4061   llvm::DIScope *FDContext = Unit;
4062   llvm::DINodeArray TParamsArray;
4063   if (!HasDecl) {
4064     // Use llvm function name.
4065     LinkageName = Fn->getName();
4066   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4067     // If there is a subprogram for this function available then use it.
4068     auto FI = SPCache.find(FD->getCanonicalDecl());
4069     if (FI != SPCache.end()) {
4070       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4071       if (SP && SP->isDefinition()) {
4072         LexicalBlockStack.emplace_back(SP);
4073         RegionMap[D].reset(SP);
4074         return;
4075       }
4076     }
4077     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4078                              TParamsArray, Flags);
4079   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4080     Name = getObjCMethodName(OMD);
4081     Flags |= llvm::DINode::FlagPrototyped;
4082   } else if (isa<VarDecl>(D) &&
4083              GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
4084     // This is a global initializer or atexit destructor for a global variable.
4085     Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4086                                      Fn);
4087   } else {
4088     Name = Fn->getName();
4089 
4090     if (isa<BlockDecl>(D))
4091       LinkageName = Name;
4092 
4093     Flags |= llvm::DINode::FlagPrototyped;
4094   }
4095   if (Name.startswith("\01"))
4096     Name = Name.substr(1);
4097 
4098   if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4099       (isa<VarDecl>(D) && GD.getDynamicInitKind() != DynamicInitKind::NoStub)) {
4100     Flags |= llvm::DINode::FlagArtificial;
4101     // Artificial functions should not silently reuse CurLoc.
4102     CurLoc = SourceLocation();
4103   }
4104 
4105   if (CurFuncIsThunk)
4106     Flags |= llvm::DINode::FlagThunk;
4107 
4108   if (Fn->hasLocalLinkage())
4109     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4110   if (CGM.getLangOpts().Optimize)
4111     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4112 
4113   llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4114   llvm::DISubprogram::DISPFlags SPFlagsForDef =
4115       SPFlags | llvm::DISubprogram::SPFlagDefinition;
4116 
4117   const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4118   unsigned ScopeLine = getLineNumber(ScopeLoc);
4119   llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4120   llvm::DISubprogram *Decl = nullptr;
4121   llvm::DINodeArray Annotations = nullptr;
4122   if (D) {
4123     Decl = isa<ObjCMethodDecl>(D)
4124                ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4125                : getFunctionDeclaration(D);
4126     Annotations = CollectBTFDeclTagAnnotations(D);
4127   }
4128 
4129   // FIXME: The function declaration we're constructing here is mostly reusing
4130   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4131   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4132   // all subprograms instead of the actual context since subprogram definitions
4133   // are emitted as CU level entities by the backend.
4134   llvm::DISubprogram *SP = DBuilder.createFunction(
4135       FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4136       FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4137       Annotations);
4138   Fn->setSubprogram(SP);
4139   // We might get here with a VarDecl in the case we're generating
4140   // code for the initialization of globals. Do not record these decls
4141   // as they will overwrite the actual VarDecl Decl in the cache.
4142   if (HasDecl && isa<FunctionDecl>(D))
4143     DeclCache[D->getCanonicalDecl()].reset(SP);
4144 
4145   // Push the function onto the lexical block stack.
4146   LexicalBlockStack.emplace_back(SP);
4147 
4148   if (HasDecl)
4149     RegionMap[D].reset(SP);
4150 }
4151 
4152 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
4153                                    QualType FnType, llvm::Function *Fn) {
4154   StringRef Name;
4155   StringRef LinkageName;
4156 
4157   const Decl *D = GD.getDecl();
4158   if (!D)
4159     return;
4160 
4161   llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4162     return GetName(D, true);
4163   });
4164 
4165   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4166   llvm::DIFile *Unit = getOrCreateFile(Loc);
4167   bool IsDeclForCallSite = Fn ? true : false;
4168   llvm::DIScope *FDContext =
4169       IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4170   llvm::DINodeArray TParamsArray;
4171   if (isa<FunctionDecl>(D)) {
4172     // If there is a DISubprogram for this function available then use it.
4173     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4174                              TParamsArray, Flags);
4175   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4176     Name = getObjCMethodName(OMD);
4177     Flags |= llvm::DINode::FlagPrototyped;
4178   } else {
4179     llvm_unreachable("not a function or ObjC method");
4180   }
4181   if (!Name.empty() && Name[0] == '\01')
4182     Name = Name.substr(1);
4183 
4184   if (D->isImplicit()) {
4185     Flags |= llvm::DINode::FlagArtificial;
4186     // Artificial functions without a location should not silently reuse CurLoc.
4187     if (Loc.isInvalid())
4188       CurLoc = SourceLocation();
4189   }
4190   unsigned LineNo = getLineNumber(Loc);
4191   unsigned ScopeLine = 0;
4192   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4193   if (CGM.getLangOpts().Optimize)
4194     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4195 
4196   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4197   llvm::DISubprogram *SP = DBuilder.createFunction(
4198       FDContext, Name, LinkageName, Unit, LineNo,
4199       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
4200       TParamsArray.get(), getFunctionDeclaration(D), nullptr, Annotations);
4201 
4202   if (IsDeclForCallSite)
4203     Fn->setSubprogram(SP);
4204 
4205   DBuilder.finalizeSubprogram(SP);
4206 }
4207 
4208 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4209                                           QualType CalleeType,
4210                                           const FunctionDecl *CalleeDecl) {
4211   if (!CallOrInvoke)
4212     return;
4213   auto *Func = CallOrInvoke->getCalledFunction();
4214   if (!Func)
4215     return;
4216   if (Func->getSubprogram())
4217     return;
4218 
4219   // Do not emit a declaration subprogram for a builtin, a function with nodebug
4220   // attribute, or if call site info isn't required. Also, elide declarations
4221   // for functions with reserved names, as call site-related features aren't
4222   // interesting in this case (& also, the compiler may emit calls to these
4223   // functions without debug locations, which makes the verifier complain).
4224   if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() ||
4225       getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4226     return;
4227   if (CalleeDecl->isReserved(CGM.getLangOpts()) !=
4228       ReservedIdentifierStatus::NotReserved)
4229     return;
4230 
4231   // If there is no DISubprogram attached to the function being called,
4232   // create the one describing the function in order to have complete
4233   // call site debug info.
4234   if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4235     EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4236 }
4237 
4238 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
4239   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4240   // If there is a subprogram for this function available then use it.
4241   auto FI = SPCache.find(FD->getCanonicalDecl());
4242   llvm::DISubprogram *SP = nullptr;
4243   if (FI != SPCache.end())
4244     SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4245   if (!SP || !SP->isDefinition())
4246     SP = getFunctionStub(GD);
4247   FnBeginRegionCount.push_back(LexicalBlockStack.size());
4248   LexicalBlockStack.emplace_back(SP);
4249   setInlinedAt(Builder.getCurrentDebugLocation());
4250   EmitLocation(Builder, FD->getLocation());
4251 }
4252 
4253 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
4254   assert(CurInlinedAt && "unbalanced inline scope stack");
4255   EmitFunctionEnd(Builder, nullptr);
4256   setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4257 }
4258 
4259 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
4260   // Update our current location
4261   setLocation(Loc);
4262 
4263   if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4264     return;
4265 
4266   llvm::MDNode *Scope = LexicalBlockStack.back();
4267   Builder.SetCurrentDebugLocation(
4268       llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4269                             getColumnNumber(CurLoc), Scope, CurInlinedAt));
4270 }
4271 
4272 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4273   llvm::MDNode *Back = nullptr;
4274   if (!LexicalBlockStack.empty())
4275     Back = LexicalBlockStack.back().get();
4276   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4277       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4278       getColumnNumber(CurLoc)));
4279 }
4280 
4281 void CGDebugInfo::AppendAddressSpaceXDeref(
4282     unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4283   Optional<unsigned> DWARFAddressSpace =
4284       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4285   if (!DWARFAddressSpace)
4286     return;
4287 
4288   Expr.push_back(llvm::dwarf::DW_OP_constu);
4289   Expr.push_back(*DWARFAddressSpace);
4290   Expr.push_back(llvm::dwarf::DW_OP_swap);
4291   Expr.push_back(llvm::dwarf::DW_OP_xderef);
4292 }
4293 
4294 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4295                                         SourceLocation Loc) {
4296   // Set our current location.
4297   setLocation(Loc);
4298 
4299   // Emit a line table change for the current location inside the new scope.
4300   Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4301       CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4302       LexicalBlockStack.back(), CurInlinedAt));
4303 
4304   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4305     return;
4306 
4307   // Create a new lexical block and push it on the stack.
4308   CreateLexicalBlock(Loc);
4309 }
4310 
4311 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4312                                       SourceLocation Loc) {
4313   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4314 
4315   // Provide an entry in the line table for the end of the block.
4316   EmitLocation(Builder, Loc);
4317 
4318   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4319     return;
4320 
4321   LexicalBlockStack.pop_back();
4322 }
4323 
4324 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4325   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4326   unsigned RCount = FnBeginRegionCount.back();
4327   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4328 
4329   // Pop all regions for this function.
4330   while (LexicalBlockStack.size() != RCount) {
4331     // Provide an entry in the line table for the end of the block.
4332     EmitLocation(Builder, CurLoc);
4333     LexicalBlockStack.pop_back();
4334   }
4335   FnBeginRegionCount.pop_back();
4336 
4337   if (Fn && Fn->getSubprogram())
4338     DBuilder.finalizeSubprogram(Fn->getSubprogram());
4339 }
4340 
4341 CGDebugInfo::BlockByRefType
4342 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4343                                           uint64_t *XOffset) {
4344   SmallVector<llvm::Metadata *, 5> EltTys;
4345   QualType FType;
4346   uint64_t FieldSize, FieldOffset;
4347   uint32_t FieldAlign;
4348 
4349   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4350   QualType Type = VD->getType();
4351 
4352   FieldOffset = 0;
4353   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4354   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4355   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4356   FType = CGM.getContext().IntTy;
4357   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4358   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4359 
4360   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4361   if (HasCopyAndDispose) {
4362     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4363     EltTys.push_back(
4364         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4365     EltTys.push_back(
4366         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4367   }
4368   bool HasByrefExtendedLayout;
4369   Qualifiers::ObjCLifetime Lifetime;
4370   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4371                                         HasByrefExtendedLayout) &&
4372       HasByrefExtendedLayout) {
4373     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4374     EltTys.push_back(
4375         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4376   }
4377 
4378   CharUnits Align = CGM.getContext().getDeclAlign(VD);
4379   if (Align > CGM.getContext().toCharUnitsFromBits(
4380                   CGM.getTarget().getPointerAlign(0))) {
4381     CharUnits FieldOffsetInBytes =
4382         CGM.getContext().toCharUnitsFromBits(FieldOffset);
4383     CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4384     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4385 
4386     if (NumPaddingBytes.isPositive()) {
4387       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4388       FType = CGM.getContext().getConstantArrayType(
4389           CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4390       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4391     }
4392   }
4393 
4394   FType = Type;
4395   llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4396   FieldSize = CGM.getContext().getTypeSize(FType);
4397   FieldAlign = CGM.getContext().toBits(Align);
4398 
4399   *XOffset = FieldOffset;
4400   llvm::DIType *FieldTy = DBuilder.createMemberType(
4401       Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4402       llvm::DINode::FlagZero, WrappedTy);
4403   EltTys.push_back(FieldTy);
4404   FieldOffset += FieldSize;
4405 
4406   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4407   return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4408                                     llvm::DINode::FlagZero, nullptr, Elements),
4409           WrappedTy};
4410 }
4411 
4412 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4413                                                 llvm::Value *Storage,
4414                                                 llvm::Optional<unsigned> ArgNo,
4415                                                 CGBuilderTy &Builder,
4416                                                 const bool UsePointerValue) {
4417   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4418   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4419   if (VD->hasAttr<NoDebugAttr>())
4420     return nullptr;
4421 
4422   bool Unwritten =
4423       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4424                            cast<Decl>(VD->getDeclContext())->isImplicit());
4425   llvm::DIFile *Unit = nullptr;
4426   if (!Unwritten)
4427     Unit = getOrCreateFile(VD->getLocation());
4428   llvm::DIType *Ty;
4429   uint64_t XOffset = 0;
4430   if (VD->hasAttr<BlocksAttr>())
4431     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4432   else
4433     Ty = getOrCreateType(VD->getType(), Unit);
4434 
4435   // If there is no debug info for this type then do not emit debug info
4436   // for this variable.
4437   if (!Ty)
4438     return nullptr;
4439 
4440   // Get location information.
4441   unsigned Line = 0;
4442   unsigned Column = 0;
4443   if (!Unwritten) {
4444     Line = getLineNumber(VD->getLocation());
4445     Column = getColumnNumber(VD->getLocation());
4446   }
4447   SmallVector<uint64_t, 13> Expr;
4448   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4449   if (VD->isImplicit())
4450     Flags |= llvm::DINode::FlagArtificial;
4451 
4452   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4453 
4454   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4455   AppendAddressSpaceXDeref(AddressSpace, Expr);
4456 
4457   // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4458   // object pointer flag.
4459   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4460     if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4461         IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4462       Flags |= llvm::DINode::FlagObjectPointer;
4463   }
4464 
4465   // Note: Older versions of clang used to emit byval references with an extra
4466   // DW_OP_deref, because they referenced the IR arg directly instead of
4467   // referencing an alloca. Newer versions of LLVM don't treat allocas
4468   // differently from other function arguments when used in a dbg.declare.
4469   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4470   StringRef Name = VD->getName();
4471   if (!Name.empty()) {
4472     // __block vars are stored on the heap if they are captured by a block that
4473     // can escape the local scope.
4474     if (VD->isEscapingByref()) {
4475       // Here, we need an offset *into* the alloca.
4476       CharUnits offset = CharUnits::fromQuantity(32);
4477       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4478       // offset of __forwarding field
4479       offset = CGM.getContext().toCharUnitsFromBits(
4480           CGM.getTarget().getPointerWidth(0));
4481       Expr.push_back(offset.getQuantity());
4482       Expr.push_back(llvm::dwarf::DW_OP_deref);
4483       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4484       // offset of x field
4485       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4486       Expr.push_back(offset.getQuantity());
4487     }
4488   } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4489     // If VD is an anonymous union then Storage represents value for
4490     // all union fields.
4491     const RecordDecl *RD = RT->getDecl();
4492     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4493       // GDB has trouble finding local variables in anonymous unions, so we emit
4494       // artificial local variables for each of the members.
4495       //
4496       // FIXME: Remove this code as soon as GDB supports this.
4497       // The debug info verifier in LLVM operates based on the assumption that a
4498       // variable has the same size as its storage and we had to disable the
4499       // check for artificial variables.
4500       for (const auto *Field : RD->fields()) {
4501         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4502         StringRef FieldName = Field->getName();
4503 
4504         // Ignore unnamed fields. Do not ignore unnamed records.
4505         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4506           continue;
4507 
4508         // Use VarDecl's Tag, Scope and Line number.
4509         auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4510         auto *D = DBuilder.createAutoVariable(
4511             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4512             Flags | llvm::DINode::FlagArtificial, FieldAlign);
4513 
4514         // Insert an llvm.dbg.declare into the current block.
4515         DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4516                                llvm::DILocation::get(CGM.getLLVMContext(), Line,
4517                                                      Column, Scope,
4518                                                      CurInlinedAt),
4519                                Builder.GetInsertBlock());
4520       }
4521     }
4522   }
4523 
4524   // Clang stores the sret pointer provided by the caller in a static alloca.
4525   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4526   // the address of the variable.
4527   if (UsePointerValue) {
4528     assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4529            "Debug info already contains DW_OP_deref.");
4530     Expr.push_back(llvm::dwarf::DW_OP_deref);
4531   }
4532 
4533   // Create the descriptor for the variable.
4534   llvm::DILocalVariable *D = nullptr;
4535   if (ArgNo) {
4536     llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4537     D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4538                                          CGM.getLangOpts().Optimize, Flags,
4539                                          Annotations);
4540   } else {
4541     // For normal local variable, we will try to find out whether 'VD' is the
4542     // copy parameter of coroutine.
4543     // If yes, we are going to use DIVariable of the origin parameter instead
4544     // of creating the new one.
4545     // If no, it might be a normal alloc, we just create a new one for it.
4546 
4547     // Check whether the VD is move parameters.
4548     auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4549       // The scope of parameter and move-parameter should be distinct
4550       // DISubprogram.
4551       if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4552         return nullptr;
4553 
4554       auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4555         Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4556         if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4557           DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4558           Decl *Decl = DeclGroup.getSingleDecl();
4559           if (VD == dyn_cast_or_null<VarDecl>(Decl))
4560             return true;
4561         }
4562         return false;
4563       });
4564 
4565       if (Iter != CoroutineParameterMappings.end()) {
4566         ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4567         auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4568           return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4569         });
4570         if (Iter2 != ParamDbgMappings.end())
4571           return const_cast<llvm::DILocalVariable *>(Iter2->second);
4572       }
4573       return nullptr;
4574     };
4575 
4576     // If we couldn't find a move param DIVariable, create a new one.
4577     D = RemapCoroArgToLocalVar();
4578     // Or we will create a new DIVariable for this Decl if D dose not exists.
4579     if (!D)
4580       D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4581                                       CGM.getLangOpts().Optimize, Flags, Align);
4582   }
4583   // Insert an llvm.dbg.declare into the current block.
4584   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4585                          llvm::DILocation::get(CGM.getLLVMContext(), Line,
4586                                                Column, Scope, CurInlinedAt),
4587                          Builder.GetInsertBlock());
4588 
4589   return D;
4590 }
4591 
4592 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4593                                                 llvm::Value *Storage,
4594                                                 llvm::Optional<unsigned> ArgNo,
4595                                                 CGBuilderTy &Builder,
4596                                                 const bool UsePointerValue) {
4597   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4598   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4599   if (BD->hasAttr<NoDebugAttr>())
4600     return nullptr;
4601 
4602   // Skip the tuple like case, we don't handle that here
4603   if (isa<DeclRefExpr>(BD->getBinding()))
4604     return nullptr;
4605 
4606   llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4607   llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
4608 
4609   // If there is no debug info for this type then do not emit debug info
4610   // for this variable.
4611   if (!Ty)
4612     return nullptr;
4613 
4614   auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4615   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(BD->getType());
4616 
4617   SmallVector<uint64_t, 3> Expr;
4618   AppendAddressSpaceXDeref(AddressSpace, Expr);
4619 
4620   // Clang stores the sret pointer provided by the caller in a static alloca.
4621   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4622   // the address of the variable.
4623   if (UsePointerValue) {
4624     assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4625            "Debug info already contains DW_OP_deref.");
4626     Expr.push_back(llvm::dwarf::DW_OP_deref);
4627   }
4628 
4629   unsigned Line = getLineNumber(BD->getLocation());
4630   unsigned Column = getColumnNumber(BD->getLocation());
4631   StringRef Name = BD->getName();
4632   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4633   // Create the descriptor for the variable.
4634   llvm::DILocalVariable *D = DBuilder.createAutoVariable(
4635       Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
4636       llvm::DINode::FlagZero, Align);
4637 
4638   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
4639     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
4640       const unsigned fieldIndex = FD->getFieldIndex();
4641       const clang::CXXRecordDecl *parent =
4642           (const CXXRecordDecl *)FD->getParent();
4643       const ASTRecordLayout &layout =
4644           CGM.getContext().getASTRecordLayout(parent);
4645       const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
4646 
4647       if (fieldOffset != 0) {
4648         Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4649         Expr.push_back(
4650             CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
4651       }
4652     }
4653   } else if (const ArraySubscriptExpr *ASE =
4654                  dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
4655     if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
4656       const uint64_t value = IL->getValue().getZExtValue();
4657       const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
4658 
4659       if (value != 0) {
4660         Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4661         Expr.push_back(CGM.getContext()
4662                            .toCharUnitsFromBits(value * typeSize)
4663                            .getQuantity());
4664       }
4665     }
4666   }
4667 
4668   // Insert an llvm.dbg.declare into the current block.
4669   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4670                          llvm::DILocation::get(CGM.getLLVMContext(), Line,
4671                                                Column, Scope, CurInlinedAt),
4672                          Builder.GetInsertBlock());
4673 
4674   return D;
4675 }
4676 
4677 llvm::DILocalVariable *
4678 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4679                                        CGBuilderTy &Builder,
4680                                        const bool UsePointerValue) {
4681   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4682 
4683   if (auto *DD = dyn_cast<DecompositionDecl>(VD))
4684     for (auto *B : DD->bindings()) {
4685       EmitDeclare(B, Storage, llvm::None, Builder,
4686                   VD->getType()->isReferenceType());
4687     }
4688 
4689   return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4690 }
4691 
4692 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4693   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4694   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4695 
4696   if (D->hasAttr<NoDebugAttr>())
4697     return;
4698 
4699   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4700   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4701 
4702   // Get location information.
4703   unsigned Line = getLineNumber(D->getLocation());
4704   unsigned Column = getColumnNumber(D->getLocation());
4705 
4706   StringRef Name = D->getName();
4707 
4708   // Create the descriptor for the label.
4709   auto *L =
4710       DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4711 
4712   // Insert an llvm.dbg.label into the current block.
4713   DBuilder.insertLabel(L,
4714                        llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4715                                              Scope, CurInlinedAt),
4716                        Builder.GetInsertBlock());
4717 }
4718 
4719 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4720                                           llvm::DIType *Ty) {
4721   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4722   if (CachedTy)
4723     Ty = CachedTy;
4724   return DBuilder.createObjectPointerType(Ty);
4725 }
4726 
4727 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4728     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4729     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4730   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4731   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4732 
4733   if (Builder.GetInsertBlock() == nullptr)
4734     return;
4735   if (VD->hasAttr<NoDebugAttr>())
4736     return;
4737 
4738   bool isByRef = VD->hasAttr<BlocksAttr>();
4739 
4740   uint64_t XOffset = 0;
4741   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4742   llvm::DIType *Ty;
4743   if (isByRef)
4744     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4745   else
4746     Ty = getOrCreateType(VD->getType(), Unit);
4747 
4748   // Self is passed along as an implicit non-arg variable in a
4749   // block. Mark it as the object pointer.
4750   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4751     if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4752       Ty = CreateSelfType(VD->getType(), Ty);
4753 
4754   // Get location information.
4755   const unsigned Line =
4756       getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
4757   unsigned Column = getColumnNumber(VD->getLocation());
4758 
4759   const llvm::DataLayout &target = CGM.getDataLayout();
4760 
4761   CharUnits offset = CharUnits::fromQuantity(
4762       target.getStructLayout(blockInfo.StructureType)
4763           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4764 
4765   SmallVector<uint64_t, 9> addr;
4766   addr.push_back(llvm::dwarf::DW_OP_deref);
4767   addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4768   addr.push_back(offset.getQuantity());
4769   if (isByRef) {
4770     addr.push_back(llvm::dwarf::DW_OP_deref);
4771     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4772     // offset of __forwarding field
4773     offset =
4774         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4775     addr.push_back(offset.getQuantity());
4776     addr.push_back(llvm::dwarf::DW_OP_deref);
4777     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4778     // offset of x field
4779     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4780     addr.push_back(offset.getQuantity());
4781   }
4782 
4783   // Create the descriptor for the variable.
4784   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4785   auto *D = DBuilder.createAutoVariable(
4786       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4787       Line, Ty, false, llvm::DINode::FlagZero, Align);
4788 
4789   // Insert an llvm.dbg.declare into the current block.
4790   auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4791                                   LexicalBlockStack.back(), CurInlinedAt);
4792   auto *Expr = DBuilder.createExpression(addr);
4793   if (InsertPoint)
4794     DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4795   else
4796     DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4797 }
4798 
4799 llvm::DILocalVariable *
4800 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4801                                       unsigned ArgNo, CGBuilderTy &Builder) {
4802   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4803   return EmitDeclare(VD, AI, ArgNo, Builder);
4804 }
4805 
4806 namespace {
4807 struct BlockLayoutChunk {
4808   uint64_t OffsetInBits;
4809   const BlockDecl::Capture *Capture;
4810 };
4811 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4812   return l.OffsetInBits < r.OffsetInBits;
4813 }
4814 } // namespace
4815 
4816 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4817     const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4818     const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4819     SmallVectorImpl<llvm::Metadata *> &Fields) {
4820   // Blocks in OpenCL have unique constraints which make the standard fields
4821   // redundant while requiring size and align fields for enqueue_kernel. See
4822   // initializeForBlockHeader in CGBlocks.cpp
4823   if (CGM.getLangOpts().OpenCL) {
4824     Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4825                                      BlockLayout.getElementOffsetInBits(0),
4826                                      Unit, Unit));
4827     Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4828                                      BlockLayout.getElementOffsetInBits(1),
4829                                      Unit, Unit));
4830   } else {
4831     Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4832                                      BlockLayout.getElementOffsetInBits(0),
4833                                      Unit, Unit));
4834     Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4835                                      BlockLayout.getElementOffsetInBits(1),
4836                                      Unit, Unit));
4837     Fields.push_back(
4838         createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4839                         BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4840     auto *FnTy = Block.getBlockExpr()->getFunctionType();
4841     auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4842     Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4843                                      BlockLayout.getElementOffsetInBits(3),
4844                                      Unit, Unit));
4845     Fields.push_back(createFieldType(
4846         "__descriptor",
4847         Context.getPointerType(Block.NeedsCopyDispose
4848                                    ? Context.getBlockDescriptorExtendedType()
4849                                    : Context.getBlockDescriptorType()),
4850         Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4851   }
4852 }
4853 
4854 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4855                                                        StringRef Name,
4856                                                        unsigned ArgNo,
4857                                                        llvm::AllocaInst *Alloca,
4858                                                        CGBuilderTy &Builder) {
4859   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4860   ASTContext &C = CGM.getContext();
4861   const BlockDecl *blockDecl = block.getBlockDecl();
4862 
4863   // Collect some general information about the block's location.
4864   SourceLocation loc = blockDecl->getCaretLocation();
4865   llvm::DIFile *tunit = getOrCreateFile(loc);
4866   unsigned line = getLineNumber(loc);
4867   unsigned column = getColumnNumber(loc);
4868 
4869   // Build the debug-info type for the block literal.
4870   getDeclContextDescriptor(blockDecl);
4871 
4872   const llvm::StructLayout *blockLayout =
4873       CGM.getDataLayout().getStructLayout(block.StructureType);
4874 
4875   SmallVector<llvm::Metadata *, 16> fields;
4876   collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4877                                              fields);
4878 
4879   // We want to sort the captures by offset, not because DWARF
4880   // requires this, but because we're paranoid about debuggers.
4881   SmallVector<BlockLayoutChunk, 8> chunks;
4882 
4883   // 'this' capture.
4884   if (blockDecl->capturesCXXThis()) {
4885     BlockLayoutChunk chunk;
4886     chunk.OffsetInBits =
4887         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4888     chunk.Capture = nullptr;
4889     chunks.push_back(chunk);
4890   }
4891 
4892   // Variable captures.
4893   for (const auto &capture : blockDecl->captures()) {
4894     const VarDecl *variable = capture.getVariable();
4895     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4896 
4897     // Ignore constant captures.
4898     if (captureInfo.isConstant())
4899       continue;
4900 
4901     BlockLayoutChunk chunk;
4902     chunk.OffsetInBits =
4903         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4904     chunk.Capture = &capture;
4905     chunks.push_back(chunk);
4906   }
4907 
4908   // Sort by offset.
4909   llvm::array_pod_sort(chunks.begin(), chunks.end());
4910 
4911   for (const BlockLayoutChunk &Chunk : chunks) {
4912     uint64_t offsetInBits = Chunk.OffsetInBits;
4913     const BlockDecl::Capture *capture = Chunk.Capture;
4914 
4915     // If we have a null capture, this must be the C++ 'this' capture.
4916     if (!capture) {
4917       QualType type;
4918       if (auto *Method =
4919               cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4920         type = Method->getThisType();
4921       else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4922         type = QualType(RDecl->getTypeForDecl(), 0);
4923       else
4924         llvm_unreachable("unexpected block declcontext");
4925 
4926       fields.push_back(createFieldType("this", type, loc, AS_public,
4927                                        offsetInBits, tunit, tunit));
4928       continue;
4929     }
4930 
4931     const VarDecl *variable = capture->getVariable();
4932     StringRef name = variable->getName();
4933 
4934     llvm::DIType *fieldType;
4935     if (capture->isByRef()) {
4936       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4937       auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
4938       // FIXME: This recomputes the layout of the BlockByRefWrapper.
4939       uint64_t xoffset;
4940       fieldType =
4941           EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4942       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4943       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4944                                             PtrInfo.Width, Align, offsetInBits,
4945                                             llvm::DINode::FlagZero, fieldType);
4946     } else {
4947       auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4948       fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4949                                   offsetInBits, Align, tunit, tunit);
4950     }
4951     fields.push_back(fieldType);
4952   }
4953 
4954   SmallString<36> typeName;
4955   llvm::raw_svector_ostream(typeName)
4956       << "__block_literal_" << CGM.getUniqueBlockCount();
4957 
4958   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4959 
4960   llvm::DIType *type =
4961       DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4962                                 CGM.getContext().toBits(block.BlockSize), 0,
4963                                 llvm::DINode::FlagZero, nullptr, fieldsArray);
4964   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4965 
4966   // Get overall information about the block.
4967   llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4968   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4969 
4970   // Create the descriptor for the parameter.
4971   auto *debugVar = DBuilder.createParameterVariable(
4972       scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4973 
4974   // Insert an llvm.dbg.declare into the current block.
4975   DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4976                          llvm::DILocation::get(CGM.getLLVMContext(), line,
4977                                                column, scope, CurInlinedAt),
4978                          Builder.GetInsertBlock());
4979 }
4980 
4981 llvm::DIDerivedType *
4982 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4983   if (!D || !D->isStaticDataMember())
4984     return nullptr;
4985 
4986   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4987   if (MI != StaticDataMemberCache.end()) {
4988     assert(MI->second && "Static data member declaration should still exist");
4989     return MI->second;
4990   }
4991 
4992   // If the member wasn't found in the cache, lazily construct and add it to the
4993   // type (used when a limited form of the type is emitted).
4994   auto DC = D->getDeclContext();
4995   auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4996   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4997 }
4998 
4999 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5000     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5001     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5002   llvm::DIGlobalVariableExpression *GVE = nullptr;
5003 
5004   for (const auto *Field : RD->fields()) {
5005     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5006     StringRef FieldName = Field->getName();
5007 
5008     // Ignore unnamed fields, but recurse into anonymous records.
5009     if (FieldName.empty()) {
5010       if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5011         GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
5012                                      Var, DContext);
5013       continue;
5014     }
5015     // Use VarDecl's Tag, Scope and Line number.
5016     GVE = DBuilder.createGlobalVariableExpression(
5017         DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5018         Var->hasLocalLinkage());
5019     Var->addDebugInfo(GVE);
5020   }
5021   return GVE;
5022 }
5023 
5024 static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args);
5025 static bool ReferencesAnonymousEntity(RecordType *RT) {
5026   // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5027   // info we produce in the DWARF, so we can't get Clang's full name back.
5028   // But so long as it's not one of those, it doesn't matter if some sub-type
5029   // of the record (a template parameter) can't be reconstituted - because the
5030   // un-reconstitutable type itself will carry its own name.
5031   const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5032   if (!RD)
5033     return false;
5034   if (!RD->getIdentifier())
5035     return true;
5036   auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5037   if (!TSpecial)
5038     return false;
5039   return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5040 }
5041 static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args) {
5042   return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5043     switch (TA.getKind()) {
5044     case TemplateArgument::Pack:
5045       return ReferencesAnonymousEntity(TA.getPackAsArray());
5046     case TemplateArgument::Type: {
5047       struct ReferencesAnonymous
5048           : public RecursiveASTVisitor<ReferencesAnonymous> {
5049         bool RefAnon = false;
5050         bool VisitRecordType(RecordType *RT) {
5051           if (ReferencesAnonymousEntity(RT)) {
5052             RefAnon = true;
5053             return false;
5054           }
5055           return true;
5056         }
5057       };
5058       ReferencesAnonymous RT;
5059       RT.TraverseType(TA.getAsType());
5060       if (RT.RefAnon)
5061         return true;
5062       break;
5063     }
5064     default:
5065       break;
5066     }
5067     return false;
5068   });
5069 }
5070 namespace {
5071 struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5072   bool Reconstitutable = true;
5073   bool VisitVectorType(VectorType *FT) {
5074     Reconstitutable = false;
5075     return false;
5076   }
5077   bool VisitAtomicType(AtomicType *FT) {
5078     Reconstitutable = false;
5079     return false;
5080   }
5081   bool VisitType(Type *T) {
5082     // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5083     // the DWARF, only the byte width.
5084     if (T->isBitIntType()) {
5085       Reconstitutable = false;
5086       return false;
5087     }
5088     return true;
5089   }
5090   bool TraverseEnumType(EnumType *ET) {
5091     // Unnamed enums can't be reconstituted due to a lack of column info we
5092     // produce in the DWARF, so we can't get Clang's full name back.
5093     if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5094       if (!ED->getIdentifier()) {
5095         Reconstitutable = false;
5096         return false;
5097       }
5098       if (!ED->isExternallyVisible()) {
5099         Reconstitutable = false;
5100         return false;
5101       }
5102     }
5103     return true;
5104   }
5105   bool VisitFunctionProtoType(FunctionProtoType *FT) {
5106     // noexcept is not encoded in DWARF, so the reversi
5107     Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5108     Reconstitutable &= !FT->getNoReturnAttr();
5109     return Reconstitutable;
5110   }
5111   bool VisitRecordType(RecordType *RT) {
5112     if (ReferencesAnonymousEntity(RT)) {
5113       Reconstitutable = false;
5114       return false;
5115     }
5116     return true;
5117   }
5118 };
5119 } // anonymous namespace
5120 
5121 // Test whether a type name could be rebuilt from emitted debug info.
5122 static bool IsReconstitutableType(QualType QT) {
5123   ReconstitutableType T;
5124   T.TraverseType(QT);
5125   return T.Reconstitutable;
5126 }
5127 
5128 std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5129   std::string Name;
5130   llvm::raw_string_ostream OS(Name);
5131   const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5132   if (!ND)
5133     return Name;
5134   codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5135       CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5136 
5137   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5138     TemplateNamesKind = codegenoptions::DebugTemplateNamesKind::Full;
5139 
5140   Optional<TemplateArgs> Args;
5141 
5142   bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5143   if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5144     Args = GetTemplateArgs(RD);
5145   } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5146     Args = GetTemplateArgs(FD);
5147     auto NameKind = ND->getDeclName().getNameKind();
5148     IsOperatorOverload |=
5149         NameKind == DeclarationName::CXXOperatorName ||
5150         NameKind == DeclarationName::CXXConversionFunctionName;
5151   } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5152     Args = GetTemplateArgs(VD);
5153   }
5154   std::function<bool(ArrayRef<TemplateArgument>)> HasReconstitutableArgs =
5155       [&](ArrayRef<TemplateArgument> Args) {
5156         return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5157           switch (TA.getKind()) {
5158           case TemplateArgument::Template:
5159             // Easy to reconstitute - the value of the parameter in the debug
5160             // info is the string name of the template. (so the template name
5161             // itself won't benefit from any name rebuilding, but that's a
5162             // representational limitation - maybe DWARF could be
5163             // changed/improved to use some more structural representation)
5164             return true;
5165           case TemplateArgument::Declaration:
5166             // Reference and pointer non-type template parameters point to
5167             // variables, functions, etc and their value is, at best (for
5168             // variables) represented as an address - not a reference to the
5169             // DWARF describing the variable/function/etc. This makes it hard,
5170             // possibly impossible to rebuild the original name - looking up the
5171             // address in the executable file's symbol table would be needed.
5172             return false;
5173           case TemplateArgument::NullPtr:
5174             // These could be rebuilt, but figured they're close enough to the
5175             // declaration case, and not worth rebuilding.
5176             return false;
5177           case TemplateArgument::Pack:
5178             // A pack is invalid if any of the elements of the pack are invalid.
5179             return HasReconstitutableArgs(TA.getPackAsArray());
5180           case TemplateArgument::Integral:
5181             // Larger integers get encoded as DWARF blocks which are a bit
5182             // harder to parse back into a large integer, etc - so punting on
5183             // this for now. Re-parsing the integers back into APInt is probably
5184             // feasible some day.
5185             return TA.getAsIntegral().getBitWidth() <= 64 &&
5186                    IsReconstitutableType(TA.getIntegralType());
5187           case TemplateArgument::Type:
5188             return IsReconstitutableType(TA.getAsType());
5189           default:
5190             llvm_unreachable("Other, unresolved, template arguments should "
5191                              "not be seen here");
5192           }
5193         });
5194       };
5195   // A conversion operator presents complications/ambiguity if there's a
5196   // conversion to class template that is itself a template, eg:
5197   // template<typename T>
5198   // operator ns::t1<T, int>();
5199   // This should be named, eg: "operator ns::t1<float, int><float>"
5200   // (ignoring clang bug that means this is currently "operator t1<float>")
5201   // but if the arguments were stripped, the consumer couldn't differentiate
5202   // whether the template argument list for the conversion type was the
5203   // function's argument list (& no reconstitution was needed) or not.
5204   // This could be handled if reconstitutable names had a separate attribute
5205   // annotating them as such - this would remove the ambiguity.
5206   //
5207   // Alternatively the template argument list could be parsed enough to check
5208   // whether there's one list or two, then compare that with the DWARF
5209   // description of the return type and the template argument lists to determine
5210   // how many lists there should be and if one is missing it could be assumed(?)
5211   // to be the function's template argument list  & then be rebuilt.
5212   //
5213   // Other operator overloads that aren't conversion operators could be
5214   // reconstituted but would require a bit more nuance about detecting the
5215   // difference between these different operators during that rebuilding.
5216   bool Reconstitutable =
5217       Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
5218 
5219   PrintingPolicy PP = getPrintingPolicy();
5220 
5221   if (TemplateNamesKind == codegenoptions::DebugTemplateNamesKind::Full ||
5222       !Reconstitutable) {
5223     ND->getNameForDiagnostic(OS, PP, Qualified);
5224   } else {
5225     bool Mangled =
5226         TemplateNamesKind == codegenoptions::DebugTemplateNamesKind::Mangled;
5227     // check if it's a template
5228     if (Mangled)
5229       OS << "_STN|";
5230 
5231     OS << ND->getDeclName();
5232     std::string EncodedOriginalName;
5233     llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
5234     EncodedOriginalNameOS << ND->getDeclName();
5235 
5236     if (Mangled) {
5237       OS << "|";
5238       printTemplateArgumentList(OS, Args->Args, PP);
5239       printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
5240 #ifndef NDEBUG
5241       std::string CanonicalOriginalName;
5242       llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
5243       ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
5244       assert(EncodedOriginalNameOS.str() == OriginalOS.str());
5245 #endif
5246     }
5247   }
5248   return Name;
5249 }
5250 
5251 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
5252                                      const VarDecl *D) {
5253   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5254   if (D->hasAttr<NoDebugAttr>())
5255     return;
5256 
5257   llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
5258     return GetName(D, true);
5259   });
5260 
5261   // If we already created a DIGlobalVariable for this declaration, just attach
5262   // it to the llvm::GlobalVariable.
5263   auto Cached = DeclCache.find(D->getCanonicalDecl());
5264   if (Cached != DeclCache.end())
5265     return Var->addDebugInfo(
5266         cast<llvm::DIGlobalVariableExpression>(Cached->second));
5267 
5268   // Create global variable debug descriptor.
5269   llvm::DIFile *Unit = nullptr;
5270   llvm::DIScope *DContext = nullptr;
5271   unsigned LineNo;
5272   StringRef DeclName, LinkageName;
5273   QualType T;
5274   llvm::MDTuple *TemplateParameters = nullptr;
5275   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
5276                       TemplateParameters, DContext);
5277 
5278   // Attempt to store one global variable for the declaration - even if we
5279   // emit a lot of fields.
5280   llvm::DIGlobalVariableExpression *GVE = nullptr;
5281 
5282   // If this is an anonymous union then we'll want to emit a global
5283   // variable for each member of the anonymous union so that it's possible
5284   // to find the name of any field in the union.
5285   if (T->isUnionType() && DeclName.empty()) {
5286     const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5287     assert(RD->isAnonymousStructOrUnion() &&
5288            "unnamed non-anonymous struct or union?");
5289     GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
5290   } else {
5291     auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5292 
5293     SmallVector<uint64_t, 4> Expr;
5294     unsigned AddressSpace =
5295         CGM.getContext().getTargetAddressSpace(D->getType());
5296     if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
5297       if (D->hasAttr<CUDASharedAttr>())
5298         AddressSpace =
5299             CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
5300       else if (D->hasAttr<CUDAConstantAttr>())
5301         AddressSpace =
5302             CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
5303     }
5304     AppendAddressSpaceXDeref(AddressSpace, Expr);
5305 
5306     llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5307     GVE = DBuilder.createGlobalVariableExpression(
5308         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
5309         Var->hasLocalLinkage(), true,
5310         Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
5311         getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
5312         Align, Annotations);
5313     Var->addDebugInfo(GVE);
5314   }
5315   DeclCache[D->getCanonicalDecl()].reset(GVE);
5316 }
5317 
5318 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
5319   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5320   if (VD->hasAttr<NoDebugAttr>())
5321     return;
5322   llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
5323     return GetName(VD, true);
5324   });
5325 
5326   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5327   // Create the descriptor for the variable.
5328   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5329   StringRef Name = VD->getName();
5330   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
5331 
5332   if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
5333     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
5334     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
5335 
5336     if (CGM.getCodeGenOpts().EmitCodeView) {
5337       // If CodeView, emit enums as global variables, unless they are defined
5338       // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5339       // enums in classes, and because it is difficult to attach this scope
5340       // information to the global variable.
5341       if (isa<RecordDecl>(ED->getDeclContext()))
5342         return;
5343     } else {
5344       // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5345       // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5346       // first time `ZERO` is referenced in a function.
5347       llvm::DIType *EDTy =
5348           getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
5349       assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
5350       (void)EDTy;
5351       return;
5352     }
5353   }
5354 
5355   // Do not emit separate definitions for function local consts.
5356   if (isa<FunctionDecl>(VD->getDeclContext()))
5357     return;
5358 
5359   VD = cast<ValueDecl>(VD->getCanonicalDecl());
5360   auto *VarD = dyn_cast<VarDecl>(VD);
5361   if (VarD && VarD->isStaticDataMember()) {
5362     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
5363     getDeclContextDescriptor(VarD);
5364     // Ensure that the type is retained even though it's otherwise unreferenced.
5365     //
5366     // FIXME: This is probably unnecessary, since Ty should reference RD
5367     // through its scope.
5368     RetainedTypes.push_back(
5369         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
5370 
5371     return;
5372   }
5373   llvm::DIScope *DContext = getDeclContextDescriptor(VD);
5374 
5375   auto &GV = DeclCache[VD];
5376   if (GV)
5377     return;
5378   llvm::DIExpression *InitExpr = nullptr;
5379   if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
5380     // FIXME: Add a representation for integer constants wider than 64 bits.
5381     if (Init.isInt())
5382       InitExpr =
5383           DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
5384     else if (Init.isFloat())
5385       InitExpr = DBuilder.createConstantValueExpression(
5386           Init.getFloat().bitcastToAPInt().getZExtValue());
5387   }
5388 
5389   llvm::MDTuple *TemplateParameters = nullptr;
5390 
5391   if (isa<VarTemplateSpecializationDecl>(VD))
5392     if (VarD) {
5393       llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
5394       TemplateParameters = parameterNodes.get();
5395     }
5396 
5397   GV.reset(DBuilder.createGlobalVariableExpression(
5398       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
5399       true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
5400       TemplateParameters, Align));
5401 }
5402 
5403 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
5404                                        const VarDecl *D) {
5405   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5406   if (D->hasAttr<NoDebugAttr>())
5407     return;
5408 
5409   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5410   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5411   StringRef Name = D->getName();
5412   llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
5413 
5414   llvm::DIScope *DContext = getDeclContextDescriptor(D);
5415   llvm::DIGlobalVariableExpression *GVE =
5416       DBuilder.createGlobalVariableExpression(
5417           DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
5418           Ty, false, false, nullptr, nullptr, nullptr, Align);
5419   Var->addDebugInfo(GVE);
5420 }
5421 
5422 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
5423                                   const GlobalDecl GD) {
5424 
5425   assert(GV);
5426 
5427   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5428     return;
5429 
5430   const auto *D = cast<ValueDecl>(GD.getDecl());
5431   if (D->hasAttr<NoDebugAttr>())
5432     return;
5433 
5434   auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
5435   llvm::DINode *DI;
5436 
5437   if (!AliaseeDecl)
5438     // FIXME: Aliasee not declared yet - possibly declared later
5439     // For example,
5440     //
5441     //   1 extern int newname __attribute__((alias("oldname")));
5442     //   2 int oldname = 1;
5443     //
5444     // No debug info would be generated for 'newname' in this case.
5445     //
5446     // Fix compiler to generate "newname" as imported_declaration
5447     // pointing to the DIE of "oldname".
5448     return;
5449   if (!(DI = getDeclarationOrDefinition(
5450             AliaseeDecl.getCanonicalDecl().getDecl())))
5451     return;
5452 
5453   llvm::DIScope *DContext = getDeclContextDescriptor(D);
5454   auto Loc = D->getLocation();
5455 
5456   llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
5457       DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
5458 
5459   // Record this DIE in the cache for nested declaration reference.
5460   ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
5461 }
5462 
5463 void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
5464                                             const StringLiteral *S) {
5465   SourceLocation Loc = S->getStrTokenLoc(0);
5466   PresumedLoc PLoc = CGM.getContext().getSourceManager().getPresumedLoc(Loc);
5467   if (!PLoc.isValid())
5468     return;
5469 
5470   llvm::DIFile *File = getOrCreateFile(Loc);
5471   llvm::DIGlobalVariableExpression *Debug =
5472       DBuilder.createGlobalVariableExpression(
5473           nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
5474           getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
5475   GV->addDebugInfo(Debug);
5476 }
5477 
5478 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
5479   if (!LexicalBlockStack.empty())
5480     return LexicalBlockStack.back();
5481   llvm::DIScope *Mod = getParentModuleOrNull(D);
5482   return getContextDescriptor(D, Mod ? Mod : TheCU);
5483 }
5484 
5485 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
5486   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5487     return;
5488   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
5489   if (!NSDecl->isAnonymousNamespace() ||
5490       CGM.getCodeGenOpts().DebugExplicitImport) {
5491     auto Loc = UD.getLocation();
5492     if (!Loc.isValid())
5493       Loc = CurLoc;
5494     DBuilder.createImportedModule(
5495         getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
5496         getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
5497   }
5498 }
5499 
5500 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {
5501   if (llvm::DINode *Target =
5502           getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
5503     auto Loc = USD.getLocation();
5504     DBuilder.createImportedDeclaration(
5505         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
5506         getOrCreateFile(Loc), getLineNumber(Loc));
5507   }
5508 }
5509 
5510 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
5511   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5512     return;
5513   assert(UD.shadow_size() &&
5514          "We shouldn't be codegening an invalid UsingDecl containing no decls");
5515 
5516   for (const auto *USD : UD.shadows()) {
5517     // FIXME: Skip functions with undeduced auto return type for now since we
5518     // don't currently have the plumbing for separate declarations & definitions
5519     // of free functions and mismatched types (auto in the declaration, concrete
5520     // return type in the definition)
5521     if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
5522       if (const auto *AT = FD->getType()
5523                                ->castAs<FunctionProtoType>()
5524                                ->getContainedAutoType())
5525         if (AT->getDeducedType().isNull())
5526           continue;
5527 
5528     EmitUsingShadowDecl(*USD);
5529     // Emitting one decl is sufficient - debuggers can detect that this is an
5530     // overloaded name & provide lookup for all the overloads.
5531     break;
5532   }
5533 }
5534 
5535 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
5536   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5537     return;
5538   assert(UD.shadow_size() &&
5539          "We shouldn't be codegening an invalid UsingEnumDecl"
5540          " containing no decls");
5541 
5542   for (const auto *USD : UD.shadows())
5543     EmitUsingShadowDecl(*USD);
5544 }
5545 
5546 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
5547   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5548     return;
5549   if (Module *M = ID.getImportedModule()) {
5550     auto Info = ASTSourceDescriptor(*M);
5551     auto Loc = ID.getLocation();
5552     DBuilder.createImportedDeclaration(
5553         getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5554         getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5555         getLineNumber(Loc));
5556   }
5557 }
5558 
5559 llvm::DIImportedEntity *
5560 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
5561   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5562     return nullptr;
5563   auto &VH = NamespaceAliasCache[&NA];
5564   if (VH)
5565     return cast<llvm::DIImportedEntity>(VH);
5566   llvm::DIImportedEntity *R;
5567   auto Loc = NA.getLocation();
5568   if (const auto *Underlying =
5569           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
5570     // This could cache & dedup here rather than relying on metadata deduping.
5571     R = DBuilder.createImportedDeclaration(
5572         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5573         EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
5574         getLineNumber(Loc), NA.getName());
5575   else
5576     R = DBuilder.createImportedDeclaration(
5577         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5578         getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
5579         getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
5580   VH.reset(R);
5581   return R;
5582 }
5583 
5584 llvm::DINamespace *
5585 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
5586   // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
5587   // if necessary, and this way multiple declarations of the same namespace in
5588   // different parent modules stay distinct.
5589   auto I = NamespaceCache.find(NSDecl);
5590   if (I != NamespaceCache.end())
5591     return cast<llvm::DINamespace>(I->second);
5592 
5593   llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
5594   // Don't trust the context if it is a DIModule (see comment above).
5595   llvm::DINamespace *NS =
5596       DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
5597   NamespaceCache[NSDecl].reset(NS);
5598   return NS;
5599 }
5600 
5601 void CGDebugInfo::setDwoId(uint64_t Signature) {
5602   assert(TheCU && "no main compile unit");
5603   TheCU->setDWOId(Signature);
5604 }
5605 
5606 void CGDebugInfo::finalize() {
5607   // Creating types might create further types - invalidating the current
5608   // element and the size(), so don't cache/reference them.
5609   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
5610     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
5611     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
5612                            ? CreateTypeDefinition(E.Type, E.Unit)
5613                            : E.Decl;
5614     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
5615   }
5616 
5617   // Add methods to interface.
5618   for (const auto &P : ObjCMethodCache) {
5619     if (P.second.empty())
5620       continue;
5621 
5622     QualType QTy(P.first->getTypeForDecl(), 0);
5623     auto It = TypeCache.find(QTy.getAsOpaquePtr());
5624     assert(It != TypeCache.end());
5625 
5626     llvm::DICompositeType *InterfaceDecl =
5627         cast<llvm::DICompositeType>(It->second);
5628 
5629     auto CurElts = InterfaceDecl->getElements();
5630     SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
5631 
5632     // For DWARF v4 or earlier, only add objc_direct methods.
5633     for (auto &SubprogramDirect : P.second)
5634       if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
5635         EltTys.push_back(SubprogramDirect.getPointer());
5636 
5637     llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5638     DBuilder.replaceArrays(InterfaceDecl, Elements);
5639   }
5640 
5641   for (const auto &P : ReplaceMap) {
5642     assert(P.second);
5643     auto *Ty = cast<llvm::DIType>(P.second);
5644     assert(Ty->isForwardDecl());
5645 
5646     auto It = TypeCache.find(P.first);
5647     assert(It != TypeCache.end());
5648     assert(It->second);
5649 
5650     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
5651                               cast<llvm::DIType>(It->second));
5652   }
5653 
5654   for (const auto &P : FwdDeclReplaceMap) {
5655     assert(P.second);
5656     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
5657     llvm::Metadata *Repl;
5658 
5659     auto It = DeclCache.find(P.first);
5660     // If there has been no definition for the declaration, call RAUW
5661     // with ourselves, that will destroy the temporary MDNode and
5662     // replace it with a standard one, avoiding leaking memory.
5663     if (It == DeclCache.end())
5664       Repl = P.second;
5665     else
5666       Repl = It->second;
5667 
5668     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
5669       Repl = GVE->getVariable();
5670     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
5671   }
5672 
5673   // We keep our own list of retained types, because we need to look
5674   // up the final type in the type cache.
5675   for (auto &RT : RetainedTypes)
5676     if (auto MD = TypeCache[RT])
5677       DBuilder.retainType(cast<llvm::DIType>(MD));
5678 
5679   DBuilder.finalize();
5680 }
5681 
5682 // Don't ignore in case of explicit cast where it is referenced indirectly.
5683 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
5684   if (CGM.getCodeGenOpts().hasReducedDebugInfo())
5685     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5686       DBuilder.retainType(DieTy);
5687 }
5688 
5689 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
5690   if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
5691     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5692       DBuilder.retainType(DieTy);
5693 }
5694 
5695 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
5696   if (LexicalBlockStack.empty())
5697     return llvm::DebugLoc();
5698 
5699   llvm::MDNode *Scope = LexicalBlockStack.back();
5700   return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
5701                                getColumnNumber(Loc), Scope);
5702 }
5703 
5704 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
5705   // Call site-related attributes are only useful in optimized programs, and
5706   // when there's a possibility of debugging backtraces.
5707   if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
5708       DebugKind == codegenoptions::LocTrackingOnly)
5709     return llvm::DINode::FlagZero;
5710 
5711   // Call site-related attributes are available in DWARF v5. Some debuggers,
5712   // while not fully DWARF v5-compliant, may accept these attributes as if they
5713   // were part of DWARF v4.
5714   bool SupportsDWARFv4Ext =
5715       CGM.getCodeGenOpts().DwarfVersion == 4 &&
5716       (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
5717        CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
5718 
5719   if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
5720     return llvm::DINode::FlagZero;
5721 
5722   return llvm::DINode::FlagAllCallsDescribed;
5723 }
5724