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