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