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