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