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