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