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