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() && CurLoc.isInvalid())
485     return 0;
486   SourceManager &SM = CGM.getContext().getSourceManager();
487   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
488   return PLoc.isValid() ? PLoc.getLine() : 0;
489 }
490 
491 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
492   // We may not want column information at all.
493   if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
494     return 0;
495 
496   // If the location is invalid then use the current column.
497   if (Loc.isInvalid() && CurLoc.isInvalid())
498     return 0;
499   SourceManager &SM = CGM.getContext().getSourceManager();
500   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
501   return PLoc.isValid() ? PLoc.getColumn() : 0;
502 }
503 
504 StringRef CGDebugInfo::getCurrentDirname() {
505   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
506     return CGM.getCodeGenOpts().DebugCompilationDir;
507 
508   if (!CWDName.empty())
509     return CWDName;
510   SmallString<256> CWD;
511   llvm::sys::fs::current_path(CWD);
512   return CWDName = internString(CWD);
513 }
514 
515 void CGDebugInfo::CreateCompileUnit() {
516   SmallString<32> Checksum;
517   Optional<llvm::DIFile::ChecksumKind> CSKind;
518   Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
519 
520   // Should we be asking the SourceManager for the main file name, instead of
521   // accepting it as an argument? This just causes the main file name to
522   // mismatch with source locations and create extra lexical scopes or
523   // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
524   // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
525   // because that's what the SourceManager says)
526 
527   // Get absolute path name.
528   SourceManager &SM = CGM.getContext().getSourceManager();
529   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
530   if (MainFileName.empty())
531     MainFileName = "<stdin>";
532 
533   // The main file name provided via the "-main-file-name" option contains just
534   // the file name itself with no path information. This file name may have had
535   // a relative path, so we look into the actual file entry for the main
536   // file to determine the real absolute path for the file.
537   std::string MainFileDir;
538   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
539     MainFileDir = std::string(MainFile->getDir()->getName());
540     if (!llvm::sys::path::is_absolute(MainFileName)) {
541       llvm::SmallString<1024> MainFileDirSS(MainFileDir);
542       llvm::sys::path::append(MainFileDirSS, MainFileName);
543       MainFileName =
544           std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
545     }
546     // If the main file name provided is identical to the input file name, and
547     // if the input file is a preprocessed source, use the module name for
548     // debug info. The module name comes from the name specified in the first
549     // linemarker if the input is a preprocessed source.
550     if (MainFile->getName() == MainFileName &&
551         FrontendOptions::getInputKindForExtension(
552             MainFile->getName().rsplit('.').second)
553             .isPreprocessed())
554       MainFileName = CGM.getModule().getName().str();
555 
556     CSKind = computeChecksum(SM.getMainFileID(), Checksum);
557   }
558 
559   llvm::dwarf::SourceLanguage LangTag;
560   const LangOptions &LO = CGM.getLangOpts();
561   if (LO.CPlusPlus) {
562     if (LO.ObjC)
563       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
564     else if (LO.CPlusPlus14)
565       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
566     else if (LO.CPlusPlus11)
567       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
568     else
569       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
570   } else if (LO.ObjC) {
571     LangTag = llvm::dwarf::DW_LANG_ObjC;
572   } else if (LO.RenderScript) {
573     LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
574   } else if (LO.C99) {
575     LangTag = llvm::dwarf::DW_LANG_C99;
576   } else {
577     LangTag = llvm::dwarf::DW_LANG_C89;
578   }
579 
580   std::string Producer = getClangFullVersion();
581 
582   // Figure out which version of the ObjC runtime we have.
583   unsigned RuntimeVers = 0;
584   if (LO.ObjC)
585     RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
586 
587   llvm::DICompileUnit::DebugEmissionKind EmissionKind;
588   switch (DebugKind) {
589   case codegenoptions::NoDebugInfo:
590   case codegenoptions::LocTrackingOnly:
591     EmissionKind = llvm::DICompileUnit::NoDebug;
592     break;
593   case codegenoptions::DebugLineTablesOnly:
594     EmissionKind = llvm::DICompileUnit::LineTablesOnly;
595     break;
596   case codegenoptions::DebugDirectivesOnly:
597     EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
598     break;
599   case codegenoptions::DebugInfoConstructor:
600   case codegenoptions::LimitedDebugInfo:
601   case codegenoptions::FullDebugInfo:
602   case codegenoptions::UnusedTypeInfo:
603     EmissionKind = llvm::DICompileUnit::FullDebug;
604     break;
605   }
606 
607   uint64_t DwoId = 0;
608   auto &CGOpts = CGM.getCodeGenOpts();
609   // The DIFile used by the CU is distinct from the main source
610   // file. Its directory part specifies what becomes the
611   // DW_AT_comp_dir (the compilation directory), even if the source
612   // file was specified with an absolute path.
613   if (CSKind)
614     CSInfo.emplace(*CSKind, Checksum);
615   llvm::DIFile *CUFile = DBuilder.createFile(
616       remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
617       getSource(SM, SM.getMainFileID()));
618 
619   StringRef Sysroot, SDK;
620   if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
621     Sysroot = CGM.getHeaderSearchOpts().Sysroot;
622     auto B = llvm::sys::path::rbegin(Sysroot);
623     auto E = llvm::sys::path::rend(Sysroot);
624     auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
625     if (It != E)
626       SDK = *It;
627   }
628 
629   // Create new compile unit.
630   TheCU = DBuilder.createCompileUnit(
631       LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
632       LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
633       CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
634       DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
635       CGM.getTarget().getTriple().isNVPTX()
636           ? llvm::DICompileUnit::DebugNameTableKind::None
637           : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
638                 CGOpts.DebugNameTable),
639       CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
640 }
641 
642 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
643   llvm::dwarf::TypeKind Encoding;
644   StringRef BTName;
645   switch (BT->getKind()) {
646 #define BUILTIN_TYPE(Id, SingletonId)
647 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
648 #include "clang/AST/BuiltinTypes.def"
649   case BuiltinType::Dependent:
650     llvm_unreachable("Unexpected builtin type");
651   case BuiltinType::NullPtr:
652     return DBuilder.createNullPtrType();
653   case BuiltinType::Void:
654     return nullptr;
655   case BuiltinType::ObjCClass:
656     if (!ClassTy)
657       ClassTy =
658           DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
659                                      "objc_class", TheCU, TheCU->getFile(), 0);
660     return ClassTy;
661   case BuiltinType::ObjCId: {
662     // typedef struct objc_class *Class;
663     // typedef struct objc_object {
664     //  Class isa;
665     // } *id;
666 
667     if (ObjTy)
668       return ObjTy;
669 
670     if (!ClassTy)
671       ClassTy =
672           DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
673                                      "objc_class", TheCU, TheCU->getFile(), 0);
674 
675     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
676 
677     auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
678 
679     ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
680                                       0, 0, llvm::DINode::FlagZero, nullptr,
681                                       llvm::DINodeArray());
682 
683     DBuilder.replaceArrays(
684         ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
685                    ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
686                    llvm::DINode::FlagZero, ISATy)));
687     return ObjTy;
688   }
689   case BuiltinType::ObjCSel: {
690     if (!SelTy)
691       SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
692                                          "objc_selector", TheCU,
693                                          TheCU->getFile(), 0);
694     return SelTy;
695   }
696 
697 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
698   case BuiltinType::Id:                                                        \
699     return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t",       \
700                                     SingletonId);
701 #include "clang/Basic/OpenCLImageTypes.def"
702   case BuiltinType::OCLSampler:
703     return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
704   case BuiltinType::OCLEvent:
705     return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
706   case BuiltinType::OCLClkEvent:
707     return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
708   case BuiltinType::OCLQueue:
709     return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
710   case BuiltinType::OCLReserveID:
711     return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
712 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
713   case BuiltinType::Id: \
714     return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
715 #include "clang/Basic/OpenCLExtensionTypes.def"
716 
717 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
718 #include "clang/Basic/AArch64SVEACLETypes.def"
719     {
720       ASTContext::BuiltinVectorTypeInfo Info =
721           CGM.getContext().getBuiltinVectorTypeInfo(BT);
722       unsigned NumElemsPerVG = (Info.EC.getKnownMinValue() * Info.NumVectors) / 2;
723 
724       // Debuggers can't extract 1bit from a vector, so will display a
725       // bitpattern for svbool_t instead.
726       if (Info.ElementType == CGM.getContext().BoolTy) {
727         NumElemsPerVG /= 8;
728         Info.ElementType = CGM.getContext().UnsignedCharTy;
729       }
730 
731       auto *LowerBound =
732           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
733               llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
734       SmallVector<int64_t, 9> Expr(
735           {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
736            /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
737            llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
738       auto *UpperBound = DBuilder.createExpression(Expr);
739 
740       llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
741           /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
742       llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
743       llvm::DIType *ElemTy =
744           getOrCreateType(Info.ElementType, TheCU->getFile());
745       auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
746       return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
747                                        SubscriptArray);
748     }
749   // It doesn't make sense to generate debug info for PowerPC MMA vector types.
750   // So we return a safe type here to avoid generating an error.
751 #define PPC_VECTOR_TYPE(Name, Id, size) \
752   case BuiltinType::Id:
753 #include "clang/Basic/PPCTypes.def"
754     return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
755 
756   case BuiltinType::UChar:
757   case BuiltinType::Char_U:
758     Encoding = llvm::dwarf::DW_ATE_unsigned_char;
759     break;
760   case BuiltinType::Char_S:
761   case BuiltinType::SChar:
762     Encoding = llvm::dwarf::DW_ATE_signed_char;
763     break;
764   case BuiltinType::Char8:
765   case BuiltinType::Char16:
766   case BuiltinType::Char32:
767     Encoding = llvm::dwarf::DW_ATE_UTF;
768     break;
769   case BuiltinType::UShort:
770   case BuiltinType::UInt:
771   case BuiltinType::UInt128:
772   case BuiltinType::ULong:
773   case BuiltinType::WChar_U:
774   case BuiltinType::ULongLong:
775     Encoding = llvm::dwarf::DW_ATE_unsigned;
776     break;
777   case BuiltinType::Short:
778   case BuiltinType::Int:
779   case BuiltinType::Int128:
780   case BuiltinType::Long:
781   case BuiltinType::WChar_S:
782   case BuiltinType::LongLong:
783     Encoding = llvm::dwarf::DW_ATE_signed;
784     break;
785   case BuiltinType::Bool:
786     Encoding = llvm::dwarf::DW_ATE_boolean;
787     break;
788   case BuiltinType::Half:
789   case BuiltinType::Float:
790   case BuiltinType::LongDouble:
791   case BuiltinType::Float16:
792   case BuiltinType::BFloat16:
793   case BuiltinType::Float128:
794   case BuiltinType::Double:
795     // FIXME: For targets where long double and __float128 have the same size,
796     // they are currently indistinguishable in the debugger without some
797     // special treatment. However, there is currently no consensus on encoding
798     // and this should be updated once a DWARF encoding exists for distinct
799     // floating point types of the same size.
800     Encoding = llvm::dwarf::DW_ATE_float;
801     break;
802   case BuiltinType::ShortAccum:
803   case BuiltinType::Accum:
804   case BuiltinType::LongAccum:
805   case BuiltinType::ShortFract:
806   case BuiltinType::Fract:
807   case BuiltinType::LongFract:
808   case BuiltinType::SatShortFract:
809   case BuiltinType::SatFract:
810   case BuiltinType::SatLongFract:
811   case BuiltinType::SatShortAccum:
812   case BuiltinType::SatAccum:
813   case BuiltinType::SatLongAccum:
814     Encoding = llvm::dwarf::DW_ATE_signed_fixed;
815     break;
816   case BuiltinType::UShortAccum:
817   case BuiltinType::UAccum:
818   case BuiltinType::ULongAccum:
819   case BuiltinType::UShortFract:
820   case BuiltinType::UFract:
821   case BuiltinType::ULongFract:
822   case BuiltinType::SatUShortAccum:
823   case BuiltinType::SatUAccum:
824   case BuiltinType::SatULongAccum:
825   case BuiltinType::SatUShortFract:
826   case BuiltinType::SatUFract:
827   case BuiltinType::SatULongFract:
828     Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
829     break;
830   }
831 
832   switch (BT->getKind()) {
833   case BuiltinType::Long:
834     BTName = "long int";
835     break;
836   case BuiltinType::LongLong:
837     BTName = "long long int";
838     break;
839   case BuiltinType::ULong:
840     BTName = "long unsigned int";
841     break;
842   case BuiltinType::ULongLong:
843     BTName = "long long unsigned int";
844     break;
845   default:
846     BTName = BT->getName(CGM.getLangOpts());
847     break;
848   }
849   // Bit size and offset of the type.
850   uint64_t Size = CGM.getContext().getTypeSize(BT);
851   return DBuilder.createBasicType(BTName, Size, Encoding);
852 }
853 
854 llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
855   return DBuilder.createUnspecifiedType("auto");
856 }
857 
858 llvm::DIType *CGDebugInfo::CreateType(const ExtIntType *Ty) {
859 
860   StringRef Name = Ty->isUnsigned() ? "unsigned _ExtInt" : "_ExtInt";
861   llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
862                                        ? llvm::dwarf::DW_ATE_unsigned
863                                        : llvm::dwarf::DW_ATE_signed;
864 
865   return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
866                                   Encoding);
867 }
868 
869 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
870   // Bit size and offset of the type.
871   llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
872   if (Ty->isComplexIntegerType())
873     Encoding = llvm::dwarf::DW_ATE_lo_user;
874 
875   uint64_t Size = CGM.getContext().getTypeSize(Ty);
876   return DBuilder.createBasicType("complex", Size, Encoding);
877 }
878 
879 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
880                                                llvm::DIFile *Unit) {
881   QualifierCollector Qc;
882   const Type *T = Qc.strip(Ty);
883 
884   // Ignore these qualifiers for now.
885   Qc.removeObjCGCAttr();
886   Qc.removeAddressSpace();
887   Qc.removeObjCLifetime();
888 
889   // We will create one Derived type for one qualifier and recurse to handle any
890   // additional ones.
891   llvm::dwarf::Tag Tag;
892   if (Qc.hasConst()) {
893     Tag = llvm::dwarf::DW_TAG_const_type;
894     Qc.removeConst();
895   } else if (Qc.hasVolatile()) {
896     Tag = llvm::dwarf::DW_TAG_volatile_type;
897     Qc.removeVolatile();
898   } else if (Qc.hasRestrict()) {
899     Tag = llvm::dwarf::DW_TAG_restrict_type;
900     Qc.removeRestrict();
901   } else {
902     assert(Qc.empty() && "Unknown type qualifier for debug info");
903     return getOrCreateType(QualType(T, 0), Unit);
904   }
905 
906   auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
907 
908   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
909   // CVR derived types.
910   return DBuilder.createQualifiedType(Tag, FromTy);
911 }
912 
913 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
914                                       llvm::DIFile *Unit) {
915 
916   // The frontend treats 'id' as a typedef to an ObjCObjectType,
917   // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
918   // debug info, we want to emit 'id' in both cases.
919   if (Ty->isObjCQualifiedIdType())
920     return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
921 
922   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
923                                Ty->getPointeeType(), Unit);
924 }
925 
926 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
927                                       llvm::DIFile *Unit) {
928   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
929                                Ty->getPointeeType(), Unit);
930 }
931 
932 /// \return whether a C++ mangling exists for the type defined by TD.
933 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
934   switch (TheCU->getSourceLanguage()) {
935   case llvm::dwarf::DW_LANG_C_plus_plus:
936   case llvm::dwarf::DW_LANG_C_plus_plus_11:
937   case llvm::dwarf::DW_LANG_C_plus_plus_14:
938     return true;
939   case llvm::dwarf::DW_LANG_ObjC_plus_plus:
940     return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
941   default:
942     return false;
943   }
944 }
945 
946 // Determines if the debug info for this tag declaration needs a type
947 // identifier. The purpose of the unique identifier is to deduplicate type
948 // information for identical types across TUs. Because of the C++ one definition
949 // rule (ODR), it is valid to assume that the type is defined the same way in
950 // every TU and its debug info is equivalent.
951 //
952 // C does not have the ODR, and it is common for codebases to contain multiple
953 // different definitions of a struct with the same name in different TUs.
954 // Therefore, if the type doesn't have a C++ mangling, don't give it an
955 // identifer. Type information in C is smaller and simpler than C++ type
956 // information, so the increase in debug info size is negligible.
957 //
958 // If the type is not externally visible, it should be unique to the current TU,
959 // and should not need an identifier to participate in type deduplication.
960 // However, when emitting CodeView, the format internally uses these
961 // unique type name identifers for references between debug info. For example,
962 // the method of a class in an anonymous namespace uses the identifer to refer
963 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
964 // for such types, so when emitting CodeView, always use identifiers for C++
965 // types. This may create problems when attempting to emit CodeView when the MS
966 // C++ ABI is not in use.
967 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
968                                 llvm::DICompileUnit *TheCU) {
969   // We only add a type identifier for types with C++ name mangling.
970   if (!hasCXXMangling(TD, TheCU))
971     return false;
972 
973   // Externally visible types with C++ mangling need a type identifier.
974   if (TD->isExternallyVisible())
975     return true;
976 
977   // CodeView types with C++ mangling need a type identifier.
978   if (CGM.getCodeGenOpts().EmitCodeView)
979     return true;
980 
981   return false;
982 }
983 
984 // Returns a unique type identifier string if one exists, or an empty string.
985 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
986                                           llvm::DICompileUnit *TheCU) {
987   SmallString<256> Identifier;
988   const TagDecl *TD = Ty->getDecl();
989 
990   if (!needsTypeIdentifier(TD, CGM, TheCU))
991     return Identifier;
992   if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
993     if (RD->getDefinition())
994       if (RD->isDynamicClass() &&
995           CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
996         return Identifier;
997 
998   // TODO: This is using the RTTI name. Is there a better way to get
999   // a unique string for a type?
1000   llvm::raw_svector_ostream Out(Identifier);
1001   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1002   return Identifier;
1003 }
1004 
1005 /// \return the appropriate DWARF tag for a composite type.
1006 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1007   llvm::dwarf::Tag Tag;
1008   if (RD->isStruct() || RD->isInterface())
1009     Tag = llvm::dwarf::DW_TAG_structure_type;
1010   else if (RD->isUnion())
1011     Tag = llvm::dwarf::DW_TAG_union_type;
1012   else {
1013     // FIXME: This could be a struct type giving a default visibility different
1014     // than C++ class type, but needs llvm metadata changes first.
1015     assert(RD->isClass());
1016     Tag = llvm::dwarf::DW_TAG_class_type;
1017   }
1018   return Tag;
1019 }
1020 
1021 llvm::DICompositeType *
1022 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1023                                       llvm::DIScope *Ctx) {
1024   const RecordDecl *RD = Ty->getDecl();
1025   if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1026     return cast<llvm::DICompositeType>(T);
1027   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1028   unsigned Line = getLineNumber(RD->getLocation());
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   unsigned line = getLineNumber(loc);
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   if (DebugKind == codegenoptions::DebugLineTablesOnly)
2321     return true;
2322 
2323   if (DebugKind > codegenoptions::LimitedDebugInfo)
2324     return false;
2325 
2326   if (!LangOpts.CPlusPlus)
2327     return false;
2328 
2329   if (!RD->isCompleteDefinitionRequired())
2330     return true;
2331 
2332   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2333 
2334   if (!CXXDecl)
2335     return false;
2336 
2337   // Only emit complete debug info for a dynamic class when its vtable is
2338   // emitted.  However, Microsoft debuggers don't resolve type information
2339   // across DLL boundaries, so skip this optimization if the class or any of its
2340   // methods are marked dllimport. This isn't a complete solution, since objects
2341   // without any dllimport methods can be used in one DLL and constructed in
2342   // another, but it is the current behavior of LimitedDebugInfo.
2343   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2344       !isClassOrMethodDLLImport(CXXDecl))
2345     return true;
2346 
2347   TemplateSpecializationKind Spec = TSK_Undeclared;
2348   if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2349     Spec = SD->getSpecializationKind();
2350 
2351   if (Spec == TSK_ExplicitInstantiationDeclaration &&
2352       hasExplicitMemberDefinition(CXXDecl->method_begin(),
2353                                   CXXDecl->method_end()))
2354     return true;
2355 
2356   // In constructor homing mode, only emit complete debug info for a class
2357   // when its constructor is emitted.
2358   if ((DebugKind == codegenoptions::DebugInfoConstructor) &&
2359       canUseCtorHoming(CXXDecl))
2360     return true;
2361 
2362   return false;
2363 }
2364 
2365 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2366   if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2367     return;
2368 
2369   QualType Ty = CGM.getContext().getRecordType(RD);
2370   llvm::DIType *T = getTypeOrNull(Ty);
2371   if (T && T->isForwardDecl())
2372     completeClassData(RD);
2373 }
2374 
2375 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2376   RecordDecl *RD = Ty->getDecl();
2377   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2378   if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2379                                 CGM.getLangOpts())) {
2380     if (!T)
2381       T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2382     return T;
2383   }
2384 
2385   return CreateTypeDefinition(Ty);
2386 }
2387 
2388 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2389   RecordDecl *RD = Ty->getDecl();
2390 
2391   // Get overall information about the record type for the debug info.
2392   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2393 
2394   // Records and classes and unions can all be recursive.  To handle them, we
2395   // first generate a debug descriptor for the struct as a forward declaration.
2396   // Then (if it is a definition) we go through and get debug info for all of
2397   // its members.  Finally, we create a descriptor for the complete type (which
2398   // may refer to the forward decl if the struct is recursive) and replace all
2399   // uses of the forward declaration with the final definition.
2400   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2401 
2402   const RecordDecl *D = RD->getDefinition();
2403   if (!D || !D->isCompleteDefinition())
2404     return FwdDecl;
2405 
2406   if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2407     CollectContainingType(CXXDecl, FwdDecl);
2408 
2409   // Push the struct on region stack.
2410   LexicalBlockStack.emplace_back(&*FwdDecl);
2411   RegionMap[Ty->getDecl()].reset(FwdDecl);
2412 
2413   // Convert all the elements.
2414   SmallVector<llvm::Metadata *, 16> EltTys;
2415   // what about nested types?
2416 
2417   // Note: The split of CXXDecl information here is intentional, the
2418   // gdb tests will depend on a certain ordering at printout. The debug
2419   // information offsets are still correct if we merge them all together
2420   // though.
2421   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2422   if (CXXDecl) {
2423     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2424     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2425   }
2426 
2427   // Collect data fields (including static variables and any initializers).
2428   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2429   if (CXXDecl)
2430     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2431 
2432   LexicalBlockStack.pop_back();
2433   RegionMap.erase(Ty->getDecl());
2434 
2435   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2436   DBuilder.replaceArrays(FwdDecl, Elements);
2437 
2438   if (FwdDecl->isTemporary())
2439     FwdDecl =
2440         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2441 
2442   RegionMap[Ty->getDecl()].reset(FwdDecl);
2443   return FwdDecl;
2444 }
2445 
2446 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2447                                       llvm::DIFile *Unit) {
2448   // Ignore protocols.
2449   return getOrCreateType(Ty->getBaseType(), Unit);
2450 }
2451 
2452 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2453                                       llvm::DIFile *Unit) {
2454   // Ignore protocols.
2455   SourceLocation Loc = Ty->getDecl()->getLocation();
2456 
2457   // Use Typedefs to represent ObjCTypeParamType.
2458   return DBuilder.createTypedef(
2459       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2460       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2461       getDeclContextDescriptor(Ty->getDecl()));
2462 }
2463 
2464 /// \return true if Getter has the default name for the property PD.
2465 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2466                                  const ObjCMethodDecl *Getter) {
2467   assert(PD);
2468   if (!Getter)
2469     return true;
2470 
2471   assert(Getter->getDeclName().isObjCZeroArgSelector());
2472   return PD->getName() ==
2473          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2474 }
2475 
2476 /// \return true if Setter has the default name for the property PD.
2477 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2478                                  const ObjCMethodDecl *Setter) {
2479   assert(PD);
2480   if (!Setter)
2481     return true;
2482 
2483   assert(Setter->getDeclName().isObjCOneArgSelector());
2484   return SelectorTable::constructSetterName(PD->getName()) ==
2485          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2486 }
2487 
2488 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2489                                       llvm::DIFile *Unit) {
2490   ObjCInterfaceDecl *ID = Ty->getDecl();
2491   if (!ID)
2492     return nullptr;
2493 
2494   // Return a forward declaration if this type was imported from a clang module,
2495   // and this is not the compile unit with the implementation of the type (which
2496   // may contain hidden ivars).
2497   if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2498       !ID->getImplementation())
2499     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2500                                       ID->getName(),
2501                                       getDeclContextDescriptor(ID), Unit, 0);
2502 
2503   // Get overall information about the record type for the debug info.
2504   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2505   unsigned Line = getLineNumber(ID->getLocation());
2506   auto RuntimeLang =
2507       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2508 
2509   // If this is just a forward declaration return a special forward-declaration
2510   // debug type since we won't be able to lay out the entire type.
2511   ObjCInterfaceDecl *Def = ID->getDefinition();
2512   if (!Def || !Def->getImplementation()) {
2513     llvm::DIScope *Mod = getParentModuleOrNull(ID);
2514     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2515         llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2516         DefUnit, Line, RuntimeLang);
2517     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2518     return FwdDecl;
2519   }
2520 
2521   return CreateTypeDefinition(Ty, Unit);
2522 }
2523 
2524 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2525                                                   bool CreateSkeletonCU) {
2526   // Use the Module pointer as the key into the cache. This is a
2527   // nullptr if the "Module" is a PCH, which is safe because we don't
2528   // support chained PCH debug info, so there can only be a single PCH.
2529   const Module *M = Mod.getModuleOrNull();
2530   auto ModRef = ModuleCache.find(M);
2531   if (ModRef != ModuleCache.end())
2532     return cast<llvm::DIModule>(ModRef->second);
2533 
2534   // Macro definitions that were defined with "-D" on the command line.
2535   SmallString<128> ConfigMacros;
2536   {
2537     llvm::raw_svector_ostream OS(ConfigMacros);
2538     const auto &PPOpts = CGM.getPreprocessorOpts();
2539     unsigned I = 0;
2540     // Translate the macro definitions back into a command line.
2541     for (auto &M : PPOpts.Macros) {
2542       if (++I > 1)
2543         OS << " ";
2544       const std::string &Macro = M.first;
2545       bool Undef = M.second;
2546       OS << "\"-" << (Undef ? 'U' : 'D');
2547       for (char c : Macro)
2548         switch (c) {
2549         case '\\':
2550           OS << "\\\\";
2551           break;
2552         case '"':
2553           OS << "\\\"";
2554           break;
2555         default:
2556           OS << c;
2557         }
2558       OS << '\"';
2559     }
2560   }
2561 
2562   bool IsRootModule = M ? !M->Parent : true;
2563   // When a module name is specified as -fmodule-name, that module gets a
2564   // clang::Module object, but it won't actually be built or imported; it will
2565   // be textual.
2566   if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2567     assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2568            "clang module without ASTFile must be specified by -fmodule-name");
2569 
2570   // Return a StringRef to the remapped Path.
2571   auto RemapPath = [this](StringRef Path) -> std::string {
2572     std::string Remapped = remapDIPath(Path);
2573     StringRef Relative(Remapped);
2574     StringRef CompDir = TheCU->getDirectory();
2575     if (Relative.consume_front(CompDir))
2576       Relative.consume_front(llvm::sys::path::get_separator());
2577 
2578     return Relative.str();
2579   };
2580 
2581   if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2582     // PCH files don't have a signature field in the control block,
2583     // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2584     // We use the lower 64 bits for debug info.
2585 
2586     uint64_t Signature = 0;
2587     if (const auto &ModSig = Mod.getSignature())
2588       Signature = ModSig.truncatedValue();
2589     else
2590       Signature = ~1ULL;
2591 
2592     llvm::DIBuilder DIB(CGM.getModule());
2593     SmallString<0> PCM;
2594     if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2595       PCM = Mod.getPath();
2596     llvm::sys::path::append(PCM, Mod.getASTFile());
2597     DIB.createCompileUnit(
2598         TheCU->getSourceLanguage(),
2599         // TODO: Support "Source" from external AST providers?
2600         DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2601         TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2602         llvm::DICompileUnit::FullDebug, Signature);
2603     DIB.finalize();
2604   }
2605 
2606   llvm::DIModule *Parent =
2607       IsRootModule ? nullptr
2608                    : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2609                                           CreateSkeletonCU);
2610   std::string IncludePath = Mod.getPath().str();
2611   llvm::DIModule *DIMod =
2612       DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2613                             RemapPath(IncludePath));
2614   ModuleCache[M].reset(DIMod);
2615   return DIMod;
2616 }
2617 
2618 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2619                                                 llvm::DIFile *Unit) {
2620   ObjCInterfaceDecl *ID = Ty->getDecl();
2621   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2622   unsigned Line = getLineNumber(ID->getLocation());
2623   unsigned RuntimeLang = TheCU->getSourceLanguage();
2624 
2625   // Bit size, align and offset of the type.
2626   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2627   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2628 
2629   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2630   if (ID->getImplementation())
2631     Flags |= llvm::DINode::FlagObjcClassComplete;
2632 
2633   llvm::DIScope *Mod = getParentModuleOrNull(ID);
2634   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2635       Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2636       nullptr, llvm::DINodeArray(), RuntimeLang);
2637 
2638   QualType QTy(Ty, 0);
2639   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2640 
2641   // Push the struct on region stack.
2642   LexicalBlockStack.emplace_back(RealDecl);
2643   RegionMap[Ty->getDecl()].reset(RealDecl);
2644 
2645   // Convert all the elements.
2646   SmallVector<llvm::Metadata *, 16> EltTys;
2647 
2648   ObjCInterfaceDecl *SClass = ID->getSuperClass();
2649   if (SClass) {
2650     llvm::DIType *SClassTy =
2651         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2652     if (!SClassTy)
2653       return nullptr;
2654 
2655     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2656                                                       llvm::DINode::FlagZero);
2657     EltTys.push_back(InhTag);
2658   }
2659 
2660   // Create entries for all of the properties.
2661   auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2662     SourceLocation Loc = PD->getLocation();
2663     llvm::DIFile *PUnit = getOrCreateFile(Loc);
2664     unsigned PLine = getLineNumber(Loc);
2665     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2666     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2667     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2668         PD->getName(), PUnit, PLine,
2669         hasDefaultGetterName(PD, Getter) ? ""
2670                                          : getSelectorName(PD->getGetterName()),
2671         hasDefaultSetterName(PD, Setter) ? ""
2672                                          : getSelectorName(PD->getSetterName()),
2673         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2674     EltTys.push_back(PropertyNode);
2675   };
2676   {
2677     llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2678     for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2679       for (auto *PD : ClassExt->properties()) {
2680         PropertySet.insert(PD->getIdentifier());
2681         AddProperty(PD);
2682       }
2683     for (const auto *PD : ID->properties()) {
2684       // Don't emit duplicate metadata for properties that were already in a
2685       // class extension.
2686       if (!PropertySet.insert(PD->getIdentifier()).second)
2687         continue;
2688       AddProperty(PD);
2689     }
2690   }
2691 
2692   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2693   unsigned FieldNo = 0;
2694   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2695        Field = Field->getNextIvar(), ++FieldNo) {
2696     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2697     if (!FieldTy)
2698       return nullptr;
2699 
2700     StringRef FieldName = Field->getName();
2701 
2702     // Ignore unnamed fields.
2703     if (FieldName.empty())
2704       continue;
2705 
2706     // Get the location for the field.
2707     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2708     unsigned FieldLine = getLineNumber(Field->getLocation());
2709     QualType FType = Field->getType();
2710     uint64_t FieldSize = 0;
2711     uint32_t FieldAlign = 0;
2712 
2713     if (!FType->isIncompleteArrayType()) {
2714 
2715       // Bit size, align and offset of the type.
2716       FieldSize = Field->isBitField()
2717                       ? Field->getBitWidthValue(CGM.getContext())
2718                       : CGM.getContext().getTypeSize(FType);
2719       FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2720     }
2721 
2722     uint64_t FieldOffset;
2723     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2724       // We don't know the runtime offset of an ivar if we're using the
2725       // non-fragile ABI.  For bitfields, use the bit offset into the first
2726       // byte of storage of the bitfield.  For other fields, use zero.
2727       if (Field->isBitField()) {
2728         FieldOffset =
2729             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2730         FieldOffset %= CGM.getContext().getCharWidth();
2731       } else {
2732         FieldOffset = 0;
2733       }
2734     } else {
2735       FieldOffset = RL.getFieldOffset(FieldNo);
2736     }
2737 
2738     llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2739     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2740       Flags = llvm::DINode::FlagProtected;
2741     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2742       Flags = llvm::DINode::FlagPrivate;
2743     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2744       Flags = llvm::DINode::FlagPublic;
2745 
2746     llvm::MDNode *PropertyNode = nullptr;
2747     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2748       if (ObjCPropertyImplDecl *PImpD =
2749               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2750         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2751           SourceLocation Loc = PD->getLocation();
2752           llvm::DIFile *PUnit = getOrCreateFile(Loc);
2753           unsigned PLine = getLineNumber(Loc);
2754           ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2755           ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2756           PropertyNode = DBuilder.createObjCProperty(
2757               PD->getName(), PUnit, PLine,
2758               hasDefaultGetterName(PD, Getter)
2759                   ? ""
2760                   : getSelectorName(PD->getGetterName()),
2761               hasDefaultSetterName(PD, Setter)
2762                   ? ""
2763                   : getSelectorName(PD->getSetterName()),
2764               PD->getPropertyAttributes(),
2765               getOrCreateType(PD->getType(), PUnit));
2766         }
2767       }
2768     }
2769     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2770                                       FieldSize, FieldAlign, FieldOffset, Flags,
2771                                       FieldTy, PropertyNode);
2772     EltTys.push_back(FieldTy);
2773   }
2774 
2775   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2776   DBuilder.replaceArrays(RealDecl, Elements);
2777 
2778   LexicalBlockStack.pop_back();
2779   return RealDecl;
2780 }
2781 
2782 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2783                                       llvm::DIFile *Unit) {
2784   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2785   int64_t Count = Ty->getNumElements();
2786 
2787   llvm::Metadata *Subscript;
2788   QualType QTy(Ty, 0);
2789   auto SizeExpr = SizeExprCache.find(QTy);
2790   if (SizeExpr != SizeExprCache.end())
2791     Subscript = DBuilder.getOrCreateSubrange(
2792         SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2793         nullptr /*upperBound*/, nullptr /*stride*/);
2794   else {
2795     auto *CountNode =
2796         llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2797             llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
2798     Subscript = DBuilder.getOrCreateSubrange(
2799         CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2800         nullptr /*stride*/);
2801   }
2802   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2803 
2804   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2805   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2806 
2807   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2808 }
2809 
2810 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
2811                                       llvm::DIFile *Unit) {
2812   // FIXME: Create another debug type for matrices
2813   // For the time being, it treats it like a nested ArrayType.
2814 
2815   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2816   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2817   uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2818 
2819   // Create ranges for both dimensions.
2820   llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
2821   auto *ColumnCountNode =
2822       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2823           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
2824   auto *RowCountNode =
2825       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2826           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
2827   Subscripts.push_back(DBuilder.getOrCreateSubrange(
2828       ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2829       nullptr /*stride*/));
2830   Subscripts.push_back(DBuilder.getOrCreateSubrange(
2831       RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2832       nullptr /*stride*/));
2833   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2834   return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
2835 }
2836 
2837 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2838   uint64_t Size;
2839   uint32_t Align;
2840 
2841   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2842   if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2843     Size = 0;
2844     Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2845                                    CGM.getContext());
2846   } else if (Ty->isIncompleteArrayType()) {
2847     Size = 0;
2848     if (Ty->getElementType()->isIncompleteType())
2849       Align = 0;
2850     else
2851       Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2852   } else if (Ty->isIncompleteType()) {
2853     Size = 0;
2854     Align = 0;
2855   } else {
2856     // Size and align of the whole array, not the element type.
2857     Size = CGM.getContext().getTypeSize(Ty);
2858     Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2859   }
2860 
2861   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
2862   // interior arrays, do we care?  Why aren't nested arrays represented the
2863   // obvious/recursive way?
2864   SmallVector<llvm::Metadata *, 8> Subscripts;
2865   QualType EltTy(Ty, 0);
2866   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2867     // If the number of elements is known, then count is that number. Otherwise,
2868     // it's -1. This allows us to represent a subrange with an array of 0
2869     // elements, like this:
2870     //
2871     //   struct foo {
2872     //     int x[0];
2873     //   };
2874     int64_t Count = -1; // Count == -1 is an unbounded array.
2875     if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2876       Count = CAT->getSize().getZExtValue();
2877     else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2878       if (Expr *Size = VAT->getSizeExpr()) {
2879         Expr::EvalResult Result;
2880         if (Size->EvaluateAsInt(Result, CGM.getContext()))
2881           Count = Result.Val.getInt().getExtValue();
2882       }
2883     }
2884 
2885     auto SizeNode = SizeExprCache.find(EltTy);
2886     if (SizeNode != SizeExprCache.end())
2887       Subscripts.push_back(DBuilder.getOrCreateSubrange(
2888           SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
2889           nullptr /*upperBound*/, nullptr /*stride*/));
2890     else {
2891       auto *CountNode =
2892           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2893               llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
2894       Subscripts.push_back(DBuilder.getOrCreateSubrange(
2895           CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2896           nullptr /*stride*/));
2897     }
2898     EltTy = Ty->getElementType();
2899   }
2900 
2901   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2902 
2903   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2904                                   SubscriptArray);
2905 }
2906 
2907 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2908                                       llvm::DIFile *Unit) {
2909   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2910                                Ty->getPointeeType(), Unit);
2911 }
2912 
2913 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2914                                       llvm::DIFile *Unit) {
2915   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2916                                Ty->getPointeeType(), Unit);
2917 }
2918 
2919 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2920                                       llvm::DIFile *U) {
2921   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2922   uint64_t Size = 0;
2923 
2924   if (!Ty->isIncompleteType()) {
2925     Size = CGM.getContext().getTypeSize(Ty);
2926 
2927     // Set the MS inheritance model. There is no flag for the unspecified model.
2928     if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2929       switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2930       case MSInheritanceModel::Single:
2931         Flags |= llvm::DINode::FlagSingleInheritance;
2932         break;
2933       case MSInheritanceModel::Multiple:
2934         Flags |= llvm::DINode::FlagMultipleInheritance;
2935         break;
2936       case MSInheritanceModel::Virtual:
2937         Flags |= llvm::DINode::FlagVirtualInheritance;
2938         break;
2939       case MSInheritanceModel::Unspecified:
2940         break;
2941       }
2942     }
2943   }
2944 
2945   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2946   if (Ty->isMemberDataPointerType())
2947     return DBuilder.createMemberPointerType(
2948         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2949         Flags);
2950 
2951   const FunctionProtoType *FPT =
2952       Ty->getPointeeType()->getAs<FunctionProtoType>();
2953   return DBuilder.createMemberPointerType(
2954       getOrCreateInstanceMethodType(
2955           CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
2956           FPT, U, false),
2957       ClassType, Size, /*Align=*/0, Flags);
2958 }
2959 
2960 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2961   auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2962   return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2963 }
2964 
2965 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2966   return getOrCreateType(Ty->getElementType(), U);
2967 }
2968 
2969 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2970   const EnumDecl *ED = Ty->getDecl();
2971 
2972   uint64_t Size = 0;
2973   uint32_t Align = 0;
2974   if (!ED->getTypeForDecl()->isIncompleteType()) {
2975     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2976     Align = getDeclAlignIfRequired(ED, CGM.getContext());
2977   }
2978 
2979   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2980 
2981   bool isImportedFromModule =
2982       DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2983 
2984   // If this is just a forward declaration, construct an appropriately
2985   // marked node and just return it.
2986   if (isImportedFromModule || !ED->getDefinition()) {
2987     // Note that it is possible for enums to be created as part of
2988     // their own declcontext. In this case a FwdDecl will be created
2989     // twice. This doesn't cause a problem because both FwdDecls are
2990     // entered into the ReplaceMap: finalize() will replace the first
2991     // FwdDecl with the second and then replace the second with
2992     // complete type.
2993     llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2994     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2995     llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2996         llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2997 
2998     unsigned Line = getLineNumber(ED->getLocation());
2999     StringRef EDName = ED->getName();
3000     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3001         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3002         0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3003 
3004     ReplaceMap.emplace_back(
3005         std::piecewise_construct, std::make_tuple(Ty),
3006         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3007     return RetTy;
3008   }
3009 
3010   return CreateTypeDefinition(Ty);
3011 }
3012 
3013 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3014   const EnumDecl *ED = Ty->getDecl();
3015   uint64_t Size = 0;
3016   uint32_t Align = 0;
3017   if (!ED->getTypeForDecl()->isIncompleteType()) {
3018     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3019     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3020   }
3021 
3022   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3023 
3024   // Create elements for each enumerator.
3025   SmallVector<llvm::Metadata *, 16> Enumerators;
3026   ED = ED->getDefinition();
3027   bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
3028   for (const auto *Enum : ED->enumerators()) {
3029     const auto &InitVal = Enum->getInitVal();
3030     auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
3031     Enumerators.push_back(
3032         DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
3033   }
3034 
3035   // Return a CompositeType for the enum itself.
3036   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3037 
3038   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3039   unsigned Line = getLineNumber(ED->getLocation());
3040   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3041   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3042   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3043                                         Line, Size, Align, EltArray, ClassTy,
3044                                         Identifier, ED->isScoped());
3045 }
3046 
3047 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3048                                         unsigned MType, SourceLocation LineLoc,
3049                                         StringRef Name, StringRef Value) {
3050   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3051   return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3052 }
3053 
3054 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3055                                                     SourceLocation LineLoc,
3056                                                     SourceLocation FileLoc) {
3057   llvm::DIFile *FName = getOrCreateFile(FileLoc);
3058   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3059   return DBuilder.createTempMacroFile(Parent, Line, FName);
3060 }
3061 
3062 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3063   Qualifiers Quals;
3064   do {
3065     Qualifiers InnerQuals = T.getLocalQualifiers();
3066     // Qualifiers::operator+() doesn't like it if you add a Qualifier
3067     // that is already there.
3068     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3069     Quals += InnerQuals;
3070     QualType LastT = T;
3071     switch (T->getTypeClass()) {
3072     default:
3073       return C.getQualifiedType(T.getTypePtr(), Quals);
3074     case Type::TemplateSpecialization: {
3075       const auto *Spec = cast<TemplateSpecializationType>(T);
3076       if (Spec->isTypeAlias())
3077         return C.getQualifiedType(T.getTypePtr(), Quals);
3078       T = Spec->desugar();
3079       break;
3080     }
3081     case Type::TypeOfExpr:
3082       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3083       break;
3084     case Type::TypeOf:
3085       T = cast<TypeOfType>(T)->getUnderlyingType();
3086       break;
3087     case Type::Decltype:
3088       T = cast<DecltypeType>(T)->getUnderlyingType();
3089       break;
3090     case Type::UnaryTransform:
3091       T = cast<UnaryTransformType>(T)->getUnderlyingType();
3092       break;
3093     case Type::Attributed:
3094       T = cast<AttributedType>(T)->getEquivalentType();
3095       break;
3096     case Type::Elaborated:
3097       T = cast<ElaboratedType>(T)->getNamedType();
3098       break;
3099     case Type::Paren:
3100       T = cast<ParenType>(T)->getInnerType();
3101       break;
3102     case Type::MacroQualified:
3103       T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3104       break;
3105     case Type::SubstTemplateTypeParm:
3106       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3107       break;
3108     case Type::Auto:
3109     case Type::DeducedTemplateSpecialization: {
3110       QualType DT = cast<DeducedType>(T)->getDeducedType();
3111       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3112       T = DT;
3113       break;
3114     }
3115     case Type::Adjusted:
3116     case Type::Decayed:
3117       // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3118       T = cast<AdjustedType>(T)->getAdjustedType();
3119       break;
3120     }
3121 
3122     assert(T != LastT && "Type unwrapping failed to unwrap!");
3123     (void)LastT;
3124   } while (true);
3125 }
3126 
3127 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3128   assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3129   auto It = TypeCache.find(Ty.getAsOpaquePtr());
3130   if (It != TypeCache.end()) {
3131     // Verify that the debug info still exists.
3132     if (llvm::Metadata *V = It->second)
3133       return cast<llvm::DIType>(V);
3134   }
3135 
3136   return nullptr;
3137 }
3138 
3139 void CGDebugInfo::completeTemplateDefinition(
3140     const ClassTemplateSpecializationDecl &SD) {
3141   completeUnusedClass(SD);
3142 }
3143 
3144 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3145   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3146     return;
3147 
3148   completeClassData(&D);
3149   // In case this type has no member function definitions being emitted, ensure
3150   // it is retained
3151   RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3152 }
3153 
3154 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3155   if (Ty.isNull())
3156     return nullptr;
3157 
3158   llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3159     std::string Name;
3160     llvm::raw_string_ostream OS(Name);
3161     Ty.print(OS, getPrintingPolicy());
3162     return Name;
3163   });
3164 
3165   // Unwrap the type as needed for debug information.
3166   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3167 
3168   if (auto *T = getTypeOrNull(Ty))
3169     return T;
3170 
3171   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3172   void *TyPtr = Ty.getAsOpaquePtr();
3173 
3174   // And update the type cache.
3175   TypeCache[TyPtr].reset(Res);
3176 
3177   return Res;
3178 }
3179 
3180 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3181   // A forward declaration inside a module header does not belong to the module.
3182   if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3183     return nullptr;
3184   if (DebugTypeExtRefs && D->isFromASTFile()) {
3185     // Record a reference to an imported clang module or precompiled header.
3186     auto *Reader = CGM.getContext().getExternalSource();
3187     auto Idx = D->getOwningModuleID();
3188     auto Info = Reader->getSourceDescriptor(Idx);
3189     if (Info)
3190       return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3191   } else if (ClangModuleMap) {
3192     // We are building a clang module or a precompiled header.
3193     //
3194     // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3195     // and it wouldn't be necessary to specify the parent scope
3196     // because the type is already unique by definition (it would look
3197     // like the output of -fno-standalone-debug). On the other hand,
3198     // the parent scope helps a consumer to quickly locate the object
3199     // file where the type's definition is located, so it might be
3200     // best to make this behavior a command line or debugger tuning
3201     // option.
3202     if (Module *M = D->getOwningModule()) {
3203       // This is a (sub-)module.
3204       auto Info = ASTSourceDescriptor(*M);
3205       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3206     } else {
3207       // This the precompiled header being built.
3208       return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3209     }
3210   }
3211 
3212   return nullptr;
3213 }
3214 
3215 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3216   // Handle qualifiers, which recursively handles what they refer to.
3217   if (Ty.hasLocalQualifiers())
3218     return CreateQualifiedType(Ty, Unit);
3219 
3220   // Work out details of type.
3221   switch (Ty->getTypeClass()) {
3222 #define TYPE(Class, Base)
3223 #define ABSTRACT_TYPE(Class, Base)
3224 #define NON_CANONICAL_TYPE(Class, Base)
3225 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3226 #include "clang/AST/TypeNodes.inc"
3227     llvm_unreachable("Dependent types cannot show up in debug information");
3228 
3229   case Type::ExtVector:
3230   case Type::Vector:
3231     return CreateType(cast<VectorType>(Ty), Unit);
3232   case Type::ConstantMatrix:
3233     return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3234   case Type::ObjCObjectPointer:
3235     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3236   case Type::ObjCObject:
3237     return CreateType(cast<ObjCObjectType>(Ty), Unit);
3238   case Type::ObjCTypeParam:
3239     return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3240   case Type::ObjCInterface:
3241     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3242   case Type::Builtin:
3243     return CreateType(cast<BuiltinType>(Ty));
3244   case Type::Complex:
3245     return CreateType(cast<ComplexType>(Ty));
3246   case Type::Pointer:
3247     return CreateType(cast<PointerType>(Ty), Unit);
3248   case Type::BlockPointer:
3249     return CreateType(cast<BlockPointerType>(Ty), Unit);
3250   case Type::Typedef:
3251     return CreateType(cast<TypedefType>(Ty), Unit);
3252   case Type::Record:
3253     return CreateType(cast<RecordType>(Ty));
3254   case Type::Enum:
3255     return CreateEnumType(cast<EnumType>(Ty));
3256   case Type::FunctionProto:
3257   case Type::FunctionNoProto:
3258     return CreateType(cast<FunctionType>(Ty), Unit);
3259   case Type::ConstantArray:
3260   case Type::VariableArray:
3261   case Type::IncompleteArray:
3262     return CreateType(cast<ArrayType>(Ty), Unit);
3263 
3264   case Type::LValueReference:
3265     return CreateType(cast<LValueReferenceType>(Ty), Unit);
3266   case Type::RValueReference:
3267     return CreateType(cast<RValueReferenceType>(Ty), Unit);
3268 
3269   case Type::MemberPointer:
3270     return CreateType(cast<MemberPointerType>(Ty), Unit);
3271 
3272   case Type::Atomic:
3273     return CreateType(cast<AtomicType>(Ty), Unit);
3274 
3275   case Type::ExtInt:
3276     return CreateType(cast<ExtIntType>(Ty));
3277   case Type::Pipe:
3278     return CreateType(cast<PipeType>(Ty), Unit);
3279 
3280   case Type::TemplateSpecialization:
3281     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3282 
3283   case Type::Auto:
3284   case Type::Attributed:
3285   case Type::Adjusted:
3286   case Type::Decayed:
3287   case Type::DeducedTemplateSpecialization:
3288   case Type::Elaborated:
3289   case Type::Paren:
3290   case Type::MacroQualified:
3291   case Type::SubstTemplateTypeParm:
3292   case Type::TypeOfExpr:
3293   case Type::TypeOf:
3294   case Type::Decltype:
3295   case Type::UnaryTransform:
3296     break;
3297   }
3298 
3299   llvm_unreachable("type should have been unwrapped!");
3300 }
3301 
3302 llvm::DICompositeType *
3303 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3304   QualType QTy(Ty, 0);
3305 
3306   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3307 
3308   // We may have cached a forward decl when we could have created
3309   // a non-forward decl. Go ahead and create a non-forward decl
3310   // now.
3311   if (T && !T->isForwardDecl())
3312     return T;
3313 
3314   // Otherwise create the type.
3315   llvm::DICompositeType *Res = CreateLimitedType(Ty);
3316 
3317   // Propagate members from the declaration to the definition
3318   // CreateType(const RecordType*) will overwrite this with the members in the
3319   // correct order if the full type is needed.
3320   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3321 
3322   // And update the type cache.
3323   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3324   return Res;
3325 }
3326 
3327 // TODO: Currently used for context chains when limiting debug info.
3328 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3329   RecordDecl *RD = Ty->getDecl();
3330 
3331   // Get overall information about the record type for the debug info.
3332   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3333   unsigned Line = getLineNumber(RD->getLocation());
3334   StringRef RDName = getClassName(RD);
3335 
3336   llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3337 
3338   // If we ended up creating the type during the context chain construction,
3339   // just return that.
3340   auto *T = cast_or_null<llvm::DICompositeType>(
3341       getTypeOrNull(CGM.getContext().getRecordType(RD)));
3342   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3343     return T;
3344 
3345   // If this is just a forward or incomplete declaration, construct an
3346   // appropriately marked node and just return it.
3347   const RecordDecl *D = RD->getDefinition();
3348   if (!D || !D->isCompleteDefinition())
3349     return getOrCreateRecordFwdDecl(Ty, RDContext);
3350 
3351   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3352   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3353 
3354   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3355 
3356   // Explicitly record the calling convention and export symbols for C++
3357   // records.
3358   auto Flags = llvm::DINode::FlagZero;
3359   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3360     if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3361       Flags |= llvm::DINode::FlagTypePassByReference;
3362     else
3363       Flags |= llvm::DINode::FlagTypePassByValue;
3364 
3365     // Record if a C++ record is non-trivial type.
3366     if (!CXXRD->isTrivial())
3367       Flags |= llvm::DINode::FlagNonTrivial;
3368 
3369     // Record exports it symbols to the containing structure.
3370     if (CXXRD->isAnonymousStructOrUnion())
3371         Flags |= llvm::DINode::FlagExportSymbols;
3372   }
3373 
3374   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3375       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3376       Flags, Identifier);
3377 
3378   // Elements of composite types usually have back to the type, creating
3379   // uniquing cycles.  Distinct nodes are more efficient.
3380   switch (RealDecl->getTag()) {
3381   default:
3382     llvm_unreachable("invalid composite type tag");
3383 
3384   case llvm::dwarf::DW_TAG_array_type:
3385   case llvm::dwarf::DW_TAG_enumeration_type:
3386     // Array elements and most enumeration elements don't have back references,
3387     // so they don't tend to be involved in uniquing cycles and there is some
3388     // chance of merging them when linking together two modules.  Only make
3389     // them distinct if they are ODR-uniqued.
3390     if (Identifier.empty())
3391       break;
3392     LLVM_FALLTHROUGH;
3393 
3394   case llvm::dwarf::DW_TAG_structure_type:
3395   case llvm::dwarf::DW_TAG_union_type:
3396   case llvm::dwarf::DW_TAG_class_type:
3397     // Immediately resolve to a distinct node.
3398     RealDecl =
3399         llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3400     break;
3401   }
3402 
3403   RegionMap[Ty->getDecl()].reset(RealDecl);
3404   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3405 
3406   if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3407     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3408                            CollectCXXTemplateParams(TSpecial, DefUnit));
3409   return RealDecl;
3410 }
3411 
3412 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3413                                         llvm::DICompositeType *RealDecl) {
3414   // A class's primary base or the class itself contains the vtable.
3415   llvm::DICompositeType *ContainingType = nullptr;
3416   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3417   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3418     // Seek non-virtual primary base root.
3419     while (1) {
3420       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3421       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3422       if (PBT && !BRL.isPrimaryBaseVirtual())
3423         PBase = PBT;
3424       else
3425         break;
3426     }
3427     ContainingType = cast<llvm::DICompositeType>(
3428         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3429                         getOrCreateFile(RD->getLocation())));
3430   } else if (RD->isDynamicClass())
3431     ContainingType = RealDecl;
3432 
3433   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3434 }
3435 
3436 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3437                                             StringRef Name, uint64_t *Offset) {
3438   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3439   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3440   auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3441   llvm::DIType *Ty =
3442       DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3443                                 *Offset, llvm::DINode::FlagZero, FieldTy);
3444   *Offset += FieldSize;
3445   return Ty;
3446 }
3447 
3448 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3449                                            StringRef &Name,
3450                                            StringRef &LinkageName,
3451                                            llvm::DIScope *&FDContext,
3452                                            llvm::DINodeArray &TParamsArray,
3453                                            llvm::DINode::DIFlags &Flags) {
3454   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3455   Name = getFunctionName(FD);
3456   // Use mangled name as linkage name for C/C++ functions.
3457   if (FD->hasPrototype()) {
3458     LinkageName = CGM.getMangledName(GD);
3459     Flags |= llvm::DINode::FlagPrototyped;
3460   }
3461   // No need to replicate the linkage name if it isn't different from the
3462   // subprogram name, no need to have it at all unless coverage is enabled or
3463   // debug is set to more than just line tables or extra debug info is needed.
3464   if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3465                               !CGM.getCodeGenOpts().EmitGcovNotes &&
3466                               !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3467                               DebugKind <= codegenoptions::DebugLineTablesOnly))
3468     LinkageName = StringRef();
3469 
3470   // Emit the function scope in line tables only mode (if CodeView) to
3471   // differentiate between function names.
3472   if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3473       (DebugKind == codegenoptions::DebugLineTablesOnly &&
3474        CGM.getCodeGenOpts().EmitCodeView)) {
3475     if (const NamespaceDecl *NSDecl =
3476             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3477       FDContext = getOrCreateNamespace(NSDecl);
3478     else if (const RecordDecl *RDecl =
3479                  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3480       llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3481       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3482     }
3483   }
3484   if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3485     // Check if it is a noreturn-marked function
3486     if (FD->isNoReturn())
3487       Flags |= llvm::DINode::FlagNoReturn;
3488     // Collect template parameters.
3489     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3490   }
3491 }
3492 
3493 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3494                                       unsigned &LineNo, QualType &T,
3495                                       StringRef &Name, StringRef &LinkageName,
3496                                       llvm::MDTuple *&TemplateParameters,
3497                                       llvm::DIScope *&VDContext) {
3498   Unit = getOrCreateFile(VD->getLocation());
3499   LineNo = getLineNumber(VD->getLocation());
3500 
3501   setLocation(VD->getLocation());
3502 
3503   T = VD->getType();
3504   if (T->isIncompleteArrayType()) {
3505     // CodeGen turns int[] into int[1] so we'll do the same here.
3506     llvm::APInt ConstVal(32, 1);
3507     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3508 
3509     T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3510                                               ArrayType::Normal, 0);
3511   }
3512 
3513   Name = VD->getName();
3514   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3515       !isa<ObjCMethodDecl>(VD->getDeclContext()))
3516     LinkageName = CGM.getMangledName(VD);
3517   if (LinkageName == Name)
3518     LinkageName = StringRef();
3519 
3520   if (isa<VarTemplateSpecializationDecl>(VD)) {
3521     llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3522     TemplateParameters = parameterNodes.get();
3523   } else {
3524     TemplateParameters = nullptr;
3525   }
3526 
3527   // Since we emit declarations (DW_AT_members) for static members, place the
3528   // definition of those static members in the namespace they were declared in
3529   // in the source code (the lexical decl context).
3530   // FIXME: Generalize this for even non-member global variables where the
3531   // declaration and definition may have different lexical decl contexts, once
3532   // we have support for emitting declarations of (non-member) global variables.
3533   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3534                                                    : VD->getDeclContext();
3535   // When a record type contains an in-line initialization of a static data
3536   // member, and the record type is marked as __declspec(dllexport), an implicit
3537   // definition of the member will be created in the record context.  DWARF
3538   // doesn't seem to have a nice way to describe this in a form that consumers
3539   // are likely to understand, so fake the "normal" situation of a definition
3540   // outside the class by putting it in the global scope.
3541   if (DC->isRecord())
3542     DC = CGM.getContext().getTranslationUnitDecl();
3543 
3544   llvm::DIScope *Mod = getParentModuleOrNull(VD);
3545   VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3546 }
3547 
3548 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3549                                                           bool Stub) {
3550   llvm::DINodeArray TParamsArray;
3551   StringRef Name, LinkageName;
3552   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3553   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3554   SourceLocation Loc = GD.getDecl()->getLocation();
3555   llvm::DIFile *Unit = getOrCreateFile(Loc);
3556   llvm::DIScope *DContext = Unit;
3557   unsigned Line = getLineNumber(Loc);
3558   collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3559                            Flags);
3560   auto *FD = cast<FunctionDecl>(GD.getDecl());
3561 
3562   // Build function type.
3563   SmallVector<QualType, 16> ArgTypes;
3564   for (const ParmVarDecl *Parm : FD->parameters())
3565     ArgTypes.push_back(Parm->getType());
3566 
3567   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3568   QualType FnType = CGM.getContext().getFunctionType(
3569       FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3570   if (!FD->isExternallyVisible())
3571     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3572   if (CGM.getLangOpts().Optimize)
3573     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3574 
3575   if (Stub) {
3576     Flags |= getCallSiteRelatedAttrs();
3577     SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3578     return DBuilder.createFunction(
3579         DContext, Name, LinkageName, Unit, Line,
3580         getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3581         TParamsArray.get(), getFunctionDeclaration(FD));
3582   }
3583 
3584   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3585       DContext, Name, LinkageName, Unit, Line,
3586       getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3587       TParamsArray.get(), getFunctionDeclaration(FD));
3588   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3589   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3590                                  std::make_tuple(CanonDecl),
3591                                  std::make_tuple(SP));
3592   return SP;
3593 }
3594 
3595 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3596   return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3597 }
3598 
3599 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3600   return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3601 }
3602 
3603 llvm::DIGlobalVariable *
3604 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3605   QualType T;
3606   StringRef Name, LinkageName;
3607   SourceLocation Loc = VD->getLocation();
3608   llvm::DIFile *Unit = getOrCreateFile(Loc);
3609   llvm::DIScope *DContext = Unit;
3610   unsigned Line = getLineNumber(Loc);
3611   llvm::MDTuple *TemplateParameters = nullptr;
3612 
3613   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3614                       DContext);
3615   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3616   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3617       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3618       !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3619   FwdDeclReplaceMap.emplace_back(
3620       std::piecewise_construct,
3621       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3622       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3623   return GV;
3624 }
3625 
3626 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3627   // We only need a declaration (not a definition) of the type - so use whatever
3628   // we would otherwise do to get a type for a pointee. (forward declarations in
3629   // limited debug info, full definitions (if the type definition is available)
3630   // in unlimited debug info)
3631   if (const auto *TD = dyn_cast<TypeDecl>(D))
3632     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3633                            getOrCreateFile(TD->getLocation()));
3634   auto I = DeclCache.find(D->getCanonicalDecl());
3635 
3636   if (I != DeclCache.end()) {
3637     auto N = I->second;
3638     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3639       return GVE->getVariable();
3640     return dyn_cast_or_null<llvm::DINode>(N);
3641   }
3642 
3643   // No definition for now. Emit a forward definition that might be
3644   // merged with a potential upcoming definition.
3645   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3646     return getFunctionForwardDeclaration(FD);
3647   else if (const auto *VD = dyn_cast<VarDecl>(D))
3648     return getGlobalVariableForwardDeclaration(VD);
3649 
3650   return nullptr;
3651 }
3652 
3653 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3654   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3655     return nullptr;
3656 
3657   const auto *FD = dyn_cast<FunctionDecl>(D);
3658   if (!FD)
3659     return nullptr;
3660 
3661   // Setup context.
3662   auto *S = getDeclContextDescriptor(D);
3663 
3664   auto MI = SPCache.find(FD->getCanonicalDecl());
3665   if (MI == SPCache.end()) {
3666     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3667       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3668                                      cast<llvm::DICompositeType>(S));
3669     }
3670   }
3671   if (MI != SPCache.end()) {
3672     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3673     if (SP && !SP->isDefinition())
3674       return SP;
3675   }
3676 
3677   for (auto NextFD : FD->redecls()) {
3678     auto MI = SPCache.find(NextFD->getCanonicalDecl());
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   return nullptr;
3686 }
3687 
3688 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3689     const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3690     llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3691   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3692     return nullptr;
3693 
3694   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3695   if (!OMD)
3696     return nullptr;
3697 
3698   if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3699     return nullptr;
3700 
3701   if (OMD->isDirectMethod())
3702     SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3703 
3704   // Starting with DWARF V5 method declarations are emitted as children of
3705   // the interface type.
3706   auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3707   if (!ID)
3708     ID = OMD->getClassInterface();
3709   if (!ID)
3710     return nullptr;
3711   QualType QTy(ID->getTypeForDecl(), 0);
3712   auto It = TypeCache.find(QTy.getAsOpaquePtr());
3713   if (It == TypeCache.end())
3714     return nullptr;
3715   auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3716   llvm::DISubprogram *FD = DBuilder.createFunction(
3717       InterfaceType, getObjCMethodName(OMD), StringRef(),
3718       InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3719   DBuilder.finalizeSubprogram(FD);
3720   ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3721   return FD;
3722 }
3723 
3724 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3725 // implicit parameter "this".
3726 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3727                                                              QualType FnType,
3728                                                              llvm::DIFile *F) {
3729   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3730     // Create fake but valid subroutine type. Otherwise -verify would fail, and
3731     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3732     return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3733 
3734   if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3735     return getOrCreateMethodType(Method, F, false);
3736 
3737   const auto *FTy = FnType->getAs<FunctionType>();
3738   CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3739 
3740   if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3741     // Add "self" and "_cmd"
3742     SmallVector<llvm::Metadata *, 16> Elts;
3743 
3744     // First element is always return type. For 'void' functions it is NULL.
3745     QualType ResultTy = OMethod->getReturnType();
3746 
3747     // Replace the instancetype keyword with the actual type.
3748     if (ResultTy == CGM.getContext().getObjCInstanceType())
3749       ResultTy = CGM.getContext().getPointerType(
3750           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3751 
3752     Elts.push_back(getOrCreateType(ResultTy, F));
3753     // "self" pointer is always first argument.
3754     QualType SelfDeclTy;
3755     if (auto *SelfDecl = OMethod->getSelfDecl())
3756       SelfDeclTy = SelfDecl->getType();
3757     else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3758       if (FPT->getNumParams() > 1)
3759         SelfDeclTy = FPT->getParamType(0);
3760     if (!SelfDeclTy.isNull())
3761       Elts.push_back(
3762           CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3763     // "_cmd" pointer is always second argument.
3764     Elts.push_back(DBuilder.createArtificialType(
3765         getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3766     // Get rest of the arguments.
3767     for (const auto *PI : OMethod->parameters())
3768       Elts.push_back(getOrCreateType(PI->getType(), F));
3769     // Variadic methods need a special marker at the end of the type list.
3770     if (OMethod->isVariadic())
3771       Elts.push_back(DBuilder.createUnspecifiedParameter());
3772 
3773     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3774     return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3775                                          getDwarfCC(CC));
3776   }
3777 
3778   // Handle variadic function types; they need an additional
3779   // unspecified parameter.
3780   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3781     if (FD->isVariadic()) {
3782       SmallVector<llvm::Metadata *, 16> EltTys;
3783       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3784       if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3785         for (QualType ParamType : FPT->param_types())
3786           EltTys.push_back(getOrCreateType(ParamType, F));
3787       EltTys.push_back(DBuilder.createUnspecifiedParameter());
3788       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3789       return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3790                                            getDwarfCC(CC));
3791     }
3792 
3793   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3794 }
3795 
3796 void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3797                                     SourceLocation ScopeLoc, QualType FnType,
3798                                     llvm::Function *Fn, bool CurFuncIsThunk) {
3799   StringRef Name;
3800   StringRef LinkageName;
3801 
3802   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3803 
3804   const Decl *D = GD.getDecl();
3805   bool HasDecl = (D != nullptr);
3806 
3807   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3808   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3809   llvm::DIFile *Unit = getOrCreateFile(Loc);
3810   llvm::DIScope *FDContext = Unit;
3811   llvm::DINodeArray TParamsArray;
3812   if (!HasDecl) {
3813     // Use llvm function name.
3814     LinkageName = Fn->getName();
3815   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3816     // If there is a subprogram for this function available then use it.
3817     auto FI = SPCache.find(FD->getCanonicalDecl());
3818     if (FI != SPCache.end()) {
3819       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3820       if (SP && SP->isDefinition()) {
3821         LexicalBlockStack.emplace_back(SP);
3822         RegionMap[D].reset(SP);
3823         return;
3824       }
3825     }
3826     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3827                              TParamsArray, Flags);
3828   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3829     Name = getObjCMethodName(OMD);
3830     Flags |= llvm::DINode::FlagPrototyped;
3831   } else if (isa<VarDecl>(D) &&
3832              GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3833     // This is a global initializer or atexit destructor for a global variable.
3834     Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3835                                      Fn);
3836   } else {
3837     Name = Fn->getName();
3838 
3839     if (isa<BlockDecl>(D))
3840       LinkageName = Name;
3841 
3842     Flags |= llvm::DINode::FlagPrototyped;
3843   }
3844   if (Name.startswith("\01"))
3845     Name = Name.substr(1);
3846 
3847   if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
3848       (isa<VarDecl>(D) && GD.getDynamicInitKind() != DynamicInitKind::NoStub)) {
3849     Flags |= llvm::DINode::FlagArtificial;
3850     // Artificial functions should not silently reuse CurLoc.
3851     CurLoc = SourceLocation();
3852   }
3853 
3854   if (CurFuncIsThunk)
3855     Flags |= llvm::DINode::FlagThunk;
3856 
3857   if (Fn->hasLocalLinkage())
3858     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3859   if (CGM.getLangOpts().Optimize)
3860     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3861 
3862   llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3863   llvm::DISubprogram::DISPFlags SPFlagsForDef =
3864       SPFlags | llvm::DISubprogram::SPFlagDefinition;
3865 
3866   unsigned LineNo = getLineNumber(Loc);
3867   unsigned ScopeLine = getLineNumber(ScopeLoc);
3868   llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3869   llvm::DISubprogram *Decl = nullptr;
3870   if (D)
3871     Decl = isa<ObjCMethodDecl>(D)
3872                ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3873                : getFunctionDeclaration(D);
3874 
3875   // FIXME: The function declaration we're constructing here is mostly reusing
3876   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3877   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3878   // all subprograms instead of the actual context since subprogram definitions
3879   // are emitted as CU level entities by the backend.
3880   llvm::DISubprogram *SP = DBuilder.createFunction(
3881       FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3882       FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3883   Fn->setSubprogram(SP);
3884   // We might get here with a VarDecl in the case we're generating
3885   // code for the initialization of globals. Do not record these decls
3886   // as they will overwrite the actual VarDecl Decl in the cache.
3887   if (HasDecl && isa<FunctionDecl>(D))
3888     DeclCache[D->getCanonicalDecl()].reset(SP);
3889 
3890   // Push the function onto the lexical block stack.
3891   LexicalBlockStack.emplace_back(SP);
3892 
3893   if (HasDecl)
3894     RegionMap[D].reset(SP);
3895 }
3896 
3897 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3898                                    QualType FnType, llvm::Function *Fn) {
3899   StringRef Name;
3900   StringRef LinkageName;
3901 
3902   const Decl *D = GD.getDecl();
3903   if (!D)
3904     return;
3905 
3906   llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3907     std::string Name;
3908     llvm::raw_string_ostream OS(Name);
3909     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3910       ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3911                                /*Qualified=*/true);
3912     return Name;
3913   });
3914 
3915   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3916   llvm::DIFile *Unit = getOrCreateFile(Loc);
3917   bool IsDeclForCallSite = Fn ? true : false;
3918   llvm::DIScope *FDContext =
3919       IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
3920   llvm::DINodeArray TParamsArray;
3921   if (isa<FunctionDecl>(D)) {
3922     // If there is a DISubprogram for this function available then use it.
3923     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3924                              TParamsArray, Flags);
3925   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3926     Name = getObjCMethodName(OMD);
3927     Flags |= llvm::DINode::FlagPrototyped;
3928   } else {
3929     llvm_unreachable("not a function or ObjC method");
3930   }
3931   if (!Name.empty() && Name[0] == '\01')
3932     Name = Name.substr(1);
3933 
3934   if (D->isImplicit()) {
3935     Flags |= llvm::DINode::FlagArtificial;
3936     // Artificial functions without a location should not silently reuse CurLoc.
3937     if (Loc.isInvalid())
3938       CurLoc = SourceLocation();
3939   }
3940   unsigned LineNo = getLineNumber(Loc);
3941   unsigned ScopeLine = 0;
3942   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3943   if (CGM.getLangOpts().Optimize)
3944     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3945 
3946   llvm::DISubprogram *SP = DBuilder.createFunction(
3947       FDContext, Name, LinkageName, Unit, LineNo,
3948       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3949       TParamsArray.get(), getFunctionDeclaration(D));
3950 
3951   if (IsDeclForCallSite)
3952     Fn->setSubprogram(SP);
3953 
3954   DBuilder.finalizeSubprogram(SP);
3955 }
3956 
3957 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3958                                           QualType CalleeType,
3959                                           const FunctionDecl *CalleeDecl) {
3960   if (!CallOrInvoke)
3961     return;
3962   auto *Func = CallOrInvoke->getCalledFunction();
3963   if (!Func)
3964     return;
3965   if (Func->getSubprogram())
3966     return;
3967 
3968   // Do not emit a declaration subprogram for a builtin, a function with nodebug
3969   // attribute, or if call site info isn't required. Also, elide declarations
3970   // for functions with reserved names, as call site-related features aren't
3971   // interesting in this case (& also, the compiler may emit calls to these
3972   // functions without debug locations, which makes the verifier complain).
3973   if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() ||
3974       getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3975     return;
3976   if (const auto *Id = CalleeDecl->getIdentifier())
3977     if (Id->isReservedName())
3978       return;
3979 
3980   // If there is no DISubprogram attached to the function being called,
3981   // create the one describing the function in order to have complete
3982   // call site debug info.
3983   if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
3984     EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
3985 }
3986 
3987 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3988   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3989   // If there is a subprogram for this function available then use it.
3990   auto FI = SPCache.find(FD->getCanonicalDecl());
3991   llvm::DISubprogram *SP = nullptr;
3992   if (FI != SPCache.end())
3993     SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3994   if (!SP || !SP->isDefinition())
3995     SP = getFunctionStub(GD);
3996   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3997   LexicalBlockStack.emplace_back(SP);
3998   setInlinedAt(Builder.getCurrentDebugLocation());
3999   EmitLocation(Builder, FD->getLocation());
4000 }
4001 
4002 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
4003   assert(CurInlinedAt && "unbalanced inline scope stack");
4004   EmitFunctionEnd(Builder, nullptr);
4005   setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4006 }
4007 
4008 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
4009   // Update our current location
4010   setLocation(Loc);
4011 
4012   if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4013     return;
4014 
4015   llvm::MDNode *Scope = LexicalBlockStack.back();
4016   Builder.SetCurrentDebugLocation(
4017       llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4018                             getColumnNumber(CurLoc), Scope, CurInlinedAt));
4019 }
4020 
4021 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4022   llvm::MDNode *Back = nullptr;
4023   if (!LexicalBlockStack.empty())
4024     Back = LexicalBlockStack.back().get();
4025   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4026       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4027       getColumnNumber(CurLoc)));
4028 }
4029 
4030 void CGDebugInfo::AppendAddressSpaceXDeref(
4031     unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
4032   Optional<unsigned> DWARFAddressSpace =
4033       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4034   if (!DWARFAddressSpace)
4035     return;
4036 
4037   Expr.push_back(llvm::dwarf::DW_OP_constu);
4038   Expr.push_back(DWARFAddressSpace.getValue());
4039   Expr.push_back(llvm::dwarf::DW_OP_swap);
4040   Expr.push_back(llvm::dwarf::DW_OP_xderef);
4041 }
4042 
4043 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4044                                         SourceLocation Loc) {
4045   // Set our current location.
4046   setLocation(Loc);
4047 
4048   // Emit a line table change for the current location inside the new scope.
4049   Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4050       CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4051       LexicalBlockStack.back(), CurInlinedAt));
4052 
4053   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4054     return;
4055 
4056   // Create a new lexical block and push it on the stack.
4057   CreateLexicalBlock(Loc);
4058 }
4059 
4060 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4061                                       SourceLocation Loc) {
4062   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4063 
4064   // Provide an entry in the line table for the end of the block.
4065   EmitLocation(Builder, Loc);
4066 
4067   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4068     return;
4069 
4070   LexicalBlockStack.pop_back();
4071 }
4072 
4073 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4074   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4075   unsigned RCount = FnBeginRegionCount.back();
4076   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4077 
4078   // Pop all regions for this function.
4079   while (LexicalBlockStack.size() != RCount) {
4080     // Provide an entry in the line table for the end of the block.
4081     EmitLocation(Builder, CurLoc);
4082     LexicalBlockStack.pop_back();
4083   }
4084   FnBeginRegionCount.pop_back();
4085 
4086   if (Fn && Fn->getSubprogram())
4087     DBuilder.finalizeSubprogram(Fn->getSubprogram());
4088 }
4089 
4090 CGDebugInfo::BlockByRefType
4091 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4092                                           uint64_t *XOffset) {
4093   SmallVector<llvm::Metadata *, 5> EltTys;
4094   QualType FType;
4095   uint64_t FieldSize, FieldOffset;
4096   uint32_t FieldAlign;
4097 
4098   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4099   QualType Type = VD->getType();
4100 
4101   FieldOffset = 0;
4102   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4103   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4104   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4105   FType = CGM.getContext().IntTy;
4106   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4107   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4108 
4109   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4110   if (HasCopyAndDispose) {
4111     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4112     EltTys.push_back(
4113         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4114     EltTys.push_back(
4115         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4116   }
4117   bool HasByrefExtendedLayout;
4118   Qualifiers::ObjCLifetime Lifetime;
4119   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4120                                         HasByrefExtendedLayout) &&
4121       HasByrefExtendedLayout) {
4122     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4123     EltTys.push_back(
4124         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4125   }
4126 
4127   CharUnits Align = CGM.getContext().getDeclAlign(VD);
4128   if (Align > CGM.getContext().toCharUnitsFromBits(
4129                   CGM.getTarget().getPointerAlign(0))) {
4130     CharUnits FieldOffsetInBytes =
4131         CGM.getContext().toCharUnitsFromBits(FieldOffset);
4132     CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4133     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4134 
4135     if (NumPaddingBytes.isPositive()) {
4136       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4137       FType = CGM.getContext().getConstantArrayType(
4138           CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4139       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4140     }
4141   }
4142 
4143   FType = Type;
4144   llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4145   FieldSize = CGM.getContext().getTypeSize(FType);
4146   FieldAlign = CGM.getContext().toBits(Align);
4147 
4148   *XOffset = FieldOffset;
4149   llvm::DIType *FieldTy = DBuilder.createMemberType(
4150       Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4151       llvm::DINode::FlagZero, WrappedTy);
4152   EltTys.push_back(FieldTy);
4153   FieldOffset += FieldSize;
4154 
4155   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4156   return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4157                                     llvm::DINode::FlagZero, nullptr, Elements),
4158           WrappedTy};
4159 }
4160 
4161 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4162                                                 llvm::Value *Storage,
4163                                                 llvm::Optional<unsigned> ArgNo,
4164                                                 CGBuilderTy &Builder,
4165                                                 const bool UsePointerValue) {
4166   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4167   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4168   if (VD->hasAttr<NoDebugAttr>())
4169     return nullptr;
4170 
4171   bool Unwritten =
4172       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4173                            cast<Decl>(VD->getDeclContext())->isImplicit());
4174   llvm::DIFile *Unit = nullptr;
4175   if (!Unwritten)
4176     Unit = getOrCreateFile(VD->getLocation());
4177   llvm::DIType *Ty;
4178   uint64_t XOffset = 0;
4179   if (VD->hasAttr<BlocksAttr>())
4180     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4181   else
4182     Ty = getOrCreateType(VD->getType(), Unit);
4183 
4184   // If there is no debug info for this type then do not emit debug info
4185   // for this variable.
4186   if (!Ty)
4187     return nullptr;
4188 
4189   // Get location information.
4190   unsigned Line = 0;
4191   unsigned Column = 0;
4192   if (!Unwritten) {
4193     Line = getLineNumber(VD->getLocation());
4194     Column = getColumnNumber(VD->getLocation());
4195   }
4196   SmallVector<int64_t, 13> Expr;
4197   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4198   if (VD->isImplicit())
4199     Flags |= llvm::DINode::FlagArtificial;
4200 
4201   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4202 
4203   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4204   AppendAddressSpaceXDeref(AddressSpace, Expr);
4205 
4206   // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4207   // object pointer flag.
4208   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4209     if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4210         IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4211       Flags |= llvm::DINode::FlagObjectPointer;
4212   }
4213 
4214   // Note: Older versions of clang used to emit byval references with an extra
4215   // DW_OP_deref, because they referenced the IR arg directly instead of
4216   // referencing an alloca. Newer versions of LLVM don't treat allocas
4217   // differently from other function arguments when used in a dbg.declare.
4218   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4219   StringRef Name = VD->getName();
4220   if (!Name.empty()) {
4221     if (VD->hasAttr<BlocksAttr>()) {
4222       // Here, we need an offset *into* the alloca.
4223       CharUnits offset = CharUnits::fromQuantity(32);
4224       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4225       // offset of __forwarding field
4226       offset = CGM.getContext().toCharUnitsFromBits(
4227           CGM.getTarget().getPointerWidth(0));
4228       Expr.push_back(offset.getQuantity());
4229       Expr.push_back(llvm::dwarf::DW_OP_deref);
4230       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4231       // offset of x field
4232       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4233       Expr.push_back(offset.getQuantity());
4234     }
4235   } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4236     // If VD is an anonymous union then Storage represents value for
4237     // all union fields.
4238     const RecordDecl *RD = RT->getDecl();
4239     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4240       // GDB has trouble finding local variables in anonymous unions, so we emit
4241       // artificial local variables for each of the members.
4242       //
4243       // FIXME: Remove this code as soon as GDB supports this.
4244       // The debug info verifier in LLVM operates based on the assumption that a
4245       // variable has the same size as its storage and we had to disable the
4246       // check for artificial variables.
4247       for (const auto *Field : RD->fields()) {
4248         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4249         StringRef FieldName = Field->getName();
4250 
4251         // Ignore unnamed fields. Do not ignore unnamed records.
4252         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4253           continue;
4254 
4255         // Use VarDecl's Tag, Scope and Line number.
4256         auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4257         auto *D = DBuilder.createAutoVariable(
4258             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4259             Flags | llvm::DINode::FlagArtificial, FieldAlign);
4260 
4261         // Insert an llvm.dbg.declare into the current block.
4262         DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4263                                llvm::DILocation::get(CGM.getLLVMContext(), Line,
4264                                                      Column, Scope,
4265                                                      CurInlinedAt),
4266                                Builder.GetInsertBlock());
4267       }
4268     }
4269   }
4270 
4271   // Clang stores the sret pointer provided by the caller in a static alloca.
4272   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4273   // the address of the variable.
4274   if (UsePointerValue) {
4275     assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4276                Expr.end() &&
4277            "Debug info already contains DW_OP_deref.");
4278     Expr.push_back(llvm::dwarf::DW_OP_deref);
4279   }
4280 
4281   // Create the descriptor for the variable.
4282   auto *D = ArgNo ? DBuilder.createParameterVariable(
4283                         Scope, Name, *ArgNo, Unit, Line, Ty,
4284                         CGM.getLangOpts().Optimize, Flags)
4285                   : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4286                                                 CGM.getLangOpts().Optimize,
4287                                                 Flags, Align);
4288 
4289   // Insert an llvm.dbg.declare into the current block.
4290   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4291                          llvm::DILocation::get(CGM.getLLVMContext(), Line,
4292                                                Column, Scope, CurInlinedAt),
4293                          Builder.GetInsertBlock());
4294 
4295   return D;
4296 }
4297 
4298 llvm::DILocalVariable *
4299 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4300                                        CGBuilderTy &Builder,
4301                                        const bool UsePointerValue) {
4302   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4303   return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4304 }
4305 
4306 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4307   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4308   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4309 
4310   if (D->hasAttr<NoDebugAttr>())
4311     return;
4312 
4313   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4314   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4315 
4316   // Get location information.
4317   unsigned Line = getLineNumber(D->getLocation());
4318   unsigned Column = getColumnNumber(D->getLocation());
4319 
4320   StringRef Name = D->getName();
4321 
4322   // Create the descriptor for the label.
4323   auto *L =
4324       DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4325 
4326   // Insert an llvm.dbg.label into the current block.
4327   DBuilder.insertLabel(L,
4328                        llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4329                                              Scope, CurInlinedAt),
4330                        Builder.GetInsertBlock());
4331 }
4332 
4333 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4334                                           llvm::DIType *Ty) {
4335   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4336   if (CachedTy)
4337     Ty = CachedTy;
4338   return DBuilder.createObjectPointerType(Ty);
4339 }
4340 
4341 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4342     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4343     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4344   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4345   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4346 
4347   if (Builder.GetInsertBlock() == nullptr)
4348     return;
4349   if (VD->hasAttr<NoDebugAttr>())
4350     return;
4351 
4352   bool isByRef = VD->hasAttr<BlocksAttr>();
4353 
4354   uint64_t XOffset = 0;
4355   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4356   llvm::DIType *Ty;
4357   if (isByRef)
4358     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4359   else
4360     Ty = getOrCreateType(VD->getType(), Unit);
4361 
4362   // Self is passed along as an implicit non-arg variable in a
4363   // block. Mark it as the object pointer.
4364   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4365     if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4366       Ty = CreateSelfType(VD->getType(), Ty);
4367 
4368   // Get location information.
4369   unsigned Line = getLineNumber(VD->getLocation());
4370   unsigned Column = getColumnNumber(VD->getLocation());
4371 
4372   const llvm::DataLayout &target = CGM.getDataLayout();
4373 
4374   CharUnits offset = CharUnits::fromQuantity(
4375       target.getStructLayout(blockInfo.StructureType)
4376           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4377 
4378   SmallVector<int64_t, 9> addr;
4379   addr.push_back(llvm::dwarf::DW_OP_deref);
4380   addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4381   addr.push_back(offset.getQuantity());
4382   if (isByRef) {
4383     addr.push_back(llvm::dwarf::DW_OP_deref);
4384     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4385     // offset of __forwarding field
4386     offset =
4387         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4388     addr.push_back(offset.getQuantity());
4389     addr.push_back(llvm::dwarf::DW_OP_deref);
4390     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4391     // offset of x field
4392     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4393     addr.push_back(offset.getQuantity());
4394   }
4395 
4396   // Create the descriptor for the variable.
4397   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4398   auto *D = DBuilder.createAutoVariable(
4399       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4400       Line, Ty, false, llvm::DINode::FlagZero, Align);
4401 
4402   // Insert an llvm.dbg.declare into the current block.
4403   auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4404                                   LexicalBlockStack.back(), CurInlinedAt);
4405   auto *Expr = DBuilder.createExpression(addr);
4406   if (InsertPoint)
4407     DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4408   else
4409     DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4410 }
4411 
4412 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4413                                            unsigned ArgNo,
4414                                            CGBuilderTy &Builder) {
4415   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4416   EmitDeclare(VD, AI, ArgNo, Builder);
4417 }
4418 
4419 namespace {
4420 struct BlockLayoutChunk {
4421   uint64_t OffsetInBits;
4422   const BlockDecl::Capture *Capture;
4423 };
4424 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4425   return l.OffsetInBits < r.OffsetInBits;
4426 }
4427 } // namespace
4428 
4429 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4430     const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4431     const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4432     SmallVectorImpl<llvm::Metadata *> &Fields) {
4433   // Blocks in OpenCL have unique constraints which make the standard fields
4434   // redundant while requiring size and align fields for enqueue_kernel. See
4435   // initializeForBlockHeader in CGBlocks.cpp
4436   if (CGM.getLangOpts().OpenCL) {
4437     Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4438                                      BlockLayout.getElementOffsetInBits(0),
4439                                      Unit, Unit));
4440     Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4441                                      BlockLayout.getElementOffsetInBits(1),
4442                                      Unit, Unit));
4443   } else {
4444     Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4445                                      BlockLayout.getElementOffsetInBits(0),
4446                                      Unit, Unit));
4447     Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4448                                      BlockLayout.getElementOffsetInBits(1),
4449                                      Unit, Unit));
4450     Fields.push_back(
4451         createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4452                         BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4453     auto *FnTy = Block.getBlockExpr()->getFunctionType();
4454     auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4455     Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4456                                      BlockLayout.getElementOffsetInBits(3),
4457                                      Unit, Unit));
4458     Fields.push_back(createFieldType(
4459         "__descriptor",
4460         Context.getPointerType(Block.NeedsCopyDispose
4461                                    ? Context.getBlockDescriptorExtendedType()
4462                                    : Context.getBlockDescriptorType()),
4463         Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4464   }
4465 }
4466 
4467 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4468                                                        StringRef Name,
4469                                                        unsigned ArgNo,
4470                                                        llvm::AllocaInst *Alloca,
4471                                                        CGBuilderTy &Builder) {
4472   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4473   ASTContext &C = CGM.getContext();
4474   const BlockDecl *blockDecl = block.getBlockDecl();
4475 
4476   // Collect some general information about the block's location.
4477   SourceLocation loc = blockDecl->getCaretLocation();
4478   llvm::DIFile *tunit = getOrCreateFile(loc);
4479   unsigned line = getLineNumber(loc);
4480   unsigned column = getColumnNumber(loc);
4481 
4482   // Build the debug-info type for the block literal.
4483   getDeclContextDescriptor(blockDecl);
4484 
4485   const llvm::StructLayout *blockLayout =
4486       CGM.getDataLayout().getStructLayout(block.StructureType);
4487 
4488   SmallVector<llvm::Metadata *, 16> fields;
4489   collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4490                                              fields);
4491 
4492   // We want to sort the captures by offset, not because DWARF
4493   // requires this, but because we're paranoid about debuggers.
4494   SmallVector<BlockLayoutChunk, 8> chunks;
4495 
4496   // 'this' capture.
4497   if (blockDecl->capturesCXXThis()) {
4498     BlockLayoutChunk chunk;
4499     chunk.OffsetInBits =
4500         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4501     chunk.Capture = nullptr;
4502     chunks.push_back(chunk);
4503   }
4504 
4505   // Variable captures.
4506   for (const auto &capture : blockDecl->captures()) {
4507     const VarDecl *variable = capture.getVariable();
4508     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4509 
4510     // Ignore constant captures.
4511     if (captureInfo.isConstant())
4512       continue;
4513 
4514     BlockLayoutChunk chunk;
4515     chunk.OffsetInBits =
4516         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4517     chunk.Capture = &capture;
4518     chunks.push_back(chunk);
4519   }
4520 
4521   // Sort by offset.
4522   llvm::array_pod_sort(chunks.begin(), chunks.end());
4523 
4524   for (const BlockLayoutChunk &Chunk : chunks) {
4525     uint64_t offsetInBits = Chunk.OffsetInBits;
4526     const BlockDecl::Capture *capture = Chunk.Capture;
4527 
4528     // If we have a null capture, this must be the C++ 'this' capture.
4529     if (!capture) {
4530       QualType type;
4531       if (auto *Method =
4532               cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4533         type = Method->getThisType();
4534       else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4535         type = QualType(RDecl->getTypeForDecl(), 0);
4536       else
4537         llvm_unreachable("unexpected block declcontext");
4538 
4539       fields.push_back(createFieldType("this", type, loc, AS_public,
4540                                        offsetInBits, tunit, tunit));
4541       continue;
4542     }
4543 
4544     const VarDecl *variable = capture->getVariable();
4545     StringRef name = variable->getName();
4546 
4547     llvm::DIType *fieldType;
4548     if (capture->isByRef()) {
4549       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4550       auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4551       // FIXME: This recomputes the layout of the BlockByRefWrapper.
4552       uint64_t xoffset;
4553       fieldType =
4554           EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4555       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4556       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4557                                             PtrInfo.Width, Align, offsetInBits,
4558                                             llvm::DINode::FlagZero, fieldType);
4559     } else {
4560       auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4561       fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4562                                   offsetInBits, Align, tunit, tunit);
4563     }
4564     fields.push_back(fieldType);
4565   }
4566 
4567   SmallString<36> typeName;
4568   llvm::raw_svector_ostream(typeName)
4569       << "__block_literal_" << CGM.getUniqueBlockCount();
4570 
4571   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4572 
4573   llvm::DIType *type =
4574       DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4575                                 CGM.getContext().toBits(block.BlockSize), 0,
4576                                 llvm::DINode::FlagZero, nullptr, fieldsArray);
4577   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4578 
4579   // Get overall information about the block.
4580   llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4581   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4582 
4583   // Create the descriptor for the parameter.
4584   auto *debugVar = DBuilder.createParameterVariable(
4585       scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4586 
4587   // Insert an llvm.dbg.declare into the current block.
4588   DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4589                          llvm::DILocation::get(CGM.getLLVMContext(), line,
4590                                                column, scope, CurInlinedAt),
4591                          Builder.GetInsertBlock());
4592 }
4593 
4594 llvm::DIDerivedType *
4595 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4596   if (!D || !D->isStaticDataMember())
4597     return nullptr;
4598 
4599   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4600   if (MI != StaticDataMemberCache.end()) {
4601     assert(MI->second && "Static data member declaration should still exist");
4602     return MI->second;
4603   }
4604 
4605   // If the member wasn't found in the cache, lazily construct and add it to the
4606   // type (used when a limited form of the type is emitted).
4607   auto DC = D->getDeclContext();
4608   auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4609   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4610 }
4611 
4612 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4613     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4614     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4615   llvm::DIGlobalVariableExpression *GVE = nullptr;
4616 
4617   for (const auto *Field : RD->fields()) {
4618     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4619     StringRef FieldName = Field->getName();
4620 
4621     // Ignore unnamed fields, but recurse into anonymous records.
4622     if (FieldName.empty()) {
4623       if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4624         GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4625                                      Var, DContext);
4626       continue;
4627     }
4628     // Use VarDecl's Tag, Scope and Line number.
4629     GVE = DBuilder.createGlobalVariableExpression(
4630         DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4631         Var->hasLocalLinkage());
4632     Var->addDebugInfo(GVE);
4633   }
4634   return GVE;
4635 }
4636 
4637 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4638                                      const VarDecl *D) {
4639   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4640   if (D->hasAttr<NoDebugAttr>())
4641     return;
4642 
4643   llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4644     std::string Name;
4645     llvm::raw_string_ostream OS(Name);
4646     D->getNameForDiagnostic(OS, getPrintingPolicy(),
4647                             /*Qualified=*/true);
4648     return Name;
4649   });
4650 
4651   // If we already created a DIGlobalVariable for this declaration, just attach
4652   // it to the llvm::GlobalVariable.
4653   auto Cached = DeclCache.find(D->getCanonicalDecl());
4654   if (Cached != DeclCache.end())
4655     return Var->addDebugInfo(
4656         cast<llvm::DIGlobalVariableExpression>(Cached->second));
4657 
4658   // Create global variable debug descriptor.
4659   llvm::DIFile *Unit = nullptr;
4660   llvm::DIScope *DContext = nullptr;
4661   unsigned LineNo;
4662   StringRef DeclName, LinkageName;
4663   QualType T;
4664   llvm::MDTuple *TemplateParameters = nullptr;
4665   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4666                       TemplateParameters, DContext);
4667 
4668   // Attempt to store one global variable for the declaration - even if we
4669   // emit a lot of fields.
4670   llvm::DIGlobalVariableExpression *GVE = nullptr;
4671 
4672   // If this is an anonymous union then we'll want to emit a global
4673   // variable for each member of the anonymous union so that it's possible
4674   // to find the name of any field in the union.
4675   if (T->isUnionType() && DeclName.empty()) {
4676     const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4677     assert(RD->isAnonymousStructOrUnion() &&
4678            "unnamed non-anonymous struct or union?");
4679     GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4680   } else {
4681     auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4682 
4683     SmallVector<int64_t, 4> Expr;
4684     unsigned AddressSpace =
4685         CGM.getContext().getTargetAddressSpace(D->getType());
4686     if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4687       if (D->hasAttr<CUDASharedAttr>())
4688         AddressSpace =
4689             CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4690       else if (D->hasAttr<CUDAConstantAttr>())
4691         AddressSpace =
4692             CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4693     }
4694     AppendAddressSpaceXDeref(AddressSpace, Expr);
4695 
4696     GVE = DBuilder.createGlobalVariableExpression(
4697         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4698         Var->hasLocalLinkage(), true,
4699         Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4700         getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4701         Align);
4702     Var->addDebugInfo(GVE);
4703   }
4704   DeclCache[D->getCanonicalDecl()].reset(GVE);
4705 }
4706 
4707 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4708   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4709   if (VD->hasAttr<NoDebugAttr>())
4710     return;
4711   llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4712     std::string Name;
4713     llvm::raw_string_ostream OS(Name);
4714     VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4715                              /*Qualified=*/true);
4716     return Name;
4717   });
4718 
4719   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4720   // Create the descriptor for the variable.
4721   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4722   StringRef Name = VD->getName();
4723   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4724 
4725   if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4726     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4727     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4728 
4729     if (CGM.getCodeGenOpts().EmitCodeView) {
4730       // If CodeView, emit enums as global variables, unless they are defined
4731       // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4732       // enums in classes, and because it is difficult to attach this scope
4733       // information to the global variable.
4734       if (isa<RecordDecl>(ED->getDeclContext()))
4735         return;
4736     } else {
4737       // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4738       // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4739       // first time `ZERO` is referenced in a function.
4740       llvm::DIType *EDTy =
4741           getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4742       assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4743       (void)EDTy;
4744       return;
4745     }
4746   }
4747 
4748   // Do not emit separate definitions for function local consts.
4749   if (isa<FunctionDecl>(VD->getDeclContext()))
4750     return;
4751 
4752   VD = cast<ValueDecl>(VD->getCanonicalDecl());
4753   auto *VarD = dyn_cast<VarDecl>(VD);
4754   if (VarD && VarD->isStaticDataMember()) {
4755     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4756     getDeclContextDescriptor(VarD);
4757     // Ensure that the type is retained even though it's otherwise unreferenced.
4758     //
4759     // FIXME: This is probably unnecessary, since Ty should reference RD
4760     // through its scope.
4761     RetainedTypes.push_back(
4762         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4763 
4764     return;
4765   }
4766   llvm::DIScope *DContext = getDeclContextDescriptor(VD);
4767 
4768   auto &GV = DeclCache[VD];
4769   if (GV)
4770     return;
4771   llvm::DIExpression *InitExpr = nullptr;
4772   if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4773     // FIXME: Add a representation for integer constants wider than 64 bits.
4774     if (Init.isInt())
4775       InitExpr =
4776           DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4777     else if (Init.isFloat())
4778       InitExpr = DBuilder.createConstantValueExpression(
4779           Init.getFloat().bitcastToAPInt().getZExtValue());
4780   }
4781 
4782   llvm::MDTuple *TemplateParameters = nullptr;
4783 
4784   if (isa<VarTemplateSpecializationDecl>(VD))
4785     if (VarD) {
4786       llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4787       TemplateParameters = parameterNodes.get();
4788     }
4789 
4790   GV.reset(DBuilder.createGlobalVariableExpression(
4791       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4792       true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4793       TemplateParameters, Align));
4794 }
4795 
4796 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4797                                        const VarDecl *D) {
4798   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4799   if (D->hasAttr<NoDebugAttr>())
4800     return;
4801 
4802   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4803   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4804   StringRef Name = D->getName();
4805   llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4806 
4807   llvm::DIScope *DContext = getDeclContextDescriptor(D);
4808   llvm::DIGlobalVariableExpression *GVE =
4809       DBuilder.createGlobalVariableExpression(
4810           DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4811           Ty, false, false, nullptr, nullptr, nullptr, Align);
4812   Var->addDebugInfo(GVE);
4813 }
4814 
4815 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4816   if (!LexicalBlockStack.empty())
4817     return LexicalBlockStack.back();
4818   llvm::DIScope *Mod = getParentModuleOrNull(D);
4819   return getContextDescriptor(D, Mod ? Mod : TheCU);
4820 }
4821 
4822 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4823   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4824     return;
4825   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4826   if (!NSDecl->isAnonymousNamespace() ||
4827       CGM.getCodeGenOpts().DebugExplicitImport) {
4828     auto Loc = UD.getLocation();
4829     DBuilder.createImportedModule(
4830         getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4831         getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4832   }
4833 }
4834 
4835 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4836   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4837     return;
4838   assert(UD.shadow_size() &&
4839          "We shouldn't be codegening an invalid UsingDecl containing no decls");
4840   // Emitting one decl is sufficient - debuggers can detect that this is an
4841   // overloaded name & provide lookup for all the overloads.
4842   const UsingShadowDecl &USD = **UD.shadow_begin();
4843 
4844   // FIXME: Skip functions with undeduced auto return type for now since we
4845   // don't currently have the plumbing for separate declarations & definitions
4846   // of free functions and mismatched types (auto in the declaration, concrete
4847   // return type in the definition)
4848   if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4849     if (const auto *AT =
4850             FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
4851       if (AT->getDeducedType().isNull())
4852         return;
4853   if (llvm::DINode *Target =
4854           getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4855     auto Loc = USD.getLocation();
4856     DBuilder.createImportedDeclaration(
4857         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4858         getOrCreateFile(Loc), getLineNumber(Loc));
4859   }
4860 }
4861 
4862 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4863   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4864     return;
4865   if (Module *M = ID.getImportedModule()) {
4866     auto Info = ASTSourceDescriptor(*M);
4867     auto Loc = ID.getLocation();
4868     DBuilder.createImportedDeclaration(
4869         getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4870         getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4871         getLineNumber(Loc));
4872   }
4873 }
4874 
4875 llvm::DIImportedEntity *
4876 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4877   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4878     return nullptr;
4879   auto &VH = NamespaceAliasCache[&NA];
4880   if (VH)
4881     return cast<llvm::DIImportedEntity>(VH);
4882   llvm::DIImportedEntity *R;
4883   auto Loc = NA.getLocation();
4884   if (const auto *Underlying =
4885           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4886     // This could cache & dedup here rather than relying on metadata deduping.
4887     R = DBuilder.createImportedDeclaration(
4888         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4889         EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4890         getLineNumber(Loc), NA.getName());
4891   else
4892     R = DBuilder.createImportedDeclaration(
4893         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4894         getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4895         getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4896   VH.reset(R);
4897   return R;
4898 }
4899 
4900 llvm::DINamespace *
4901 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4902   // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4903   // if necessary, and this way multiple declarations of the same namespace in
4904   // different parent modules stay distinct.
4905   auto I = NamespaceCache.find(NSDecl);
4906   if (I != NamespaceCache.end())
4907     return cast<llvm::DINamespace>(I->second);
4908 
4909   llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4910   // Don't trust the context if it is a DIModule (see comment above).
4911   llvm::DINamespace *NS =
4912       DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4913   NamespaceCache[NSDecl].reset(NS);
4914   return NS;
4915 }
4916 
4917 void CGDebugInfo::setDwoId(uint64_t Signature) {
4918   assert(TheCU && "no main compile unit");
4919   TheCU->setDWOId(Signature);
4920 }
4921 
4922 void CGDebugInfo::finalize() {
4923   // Creating types might create further types - invalidating the current
4924   // element and the size(), so don't cache/reference them.
4925   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4926     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4927     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4928                            ? CreateTypeDefinition(E.Type, E.Unit)
4929                            : E.Decl;
4930     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4931   }
4932 
4933   // Add methods to interface.
4934   for (const auto &P : ObjCMethodCache) {
4935     if (P.second.empty())
4936       continue;
4937 
4938     QualType QTy(P.first->getTypeForDecl(), 0);
4939     auto It = TypeCache.find(QTy.getAsOpaquePtr());
4940     assert(It != TypeCache.end());
4941 
4942     llvm::DICompositeType *InterfaceDecl =
4943         cast<llvm::DICompositeType>(It->second);
4944 
4945     auto CurElts = InterfaceDecl->getElements();
4946     SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4947 
4948     // For DWARF v4 or earlier, only add objc_direct methods.
4949     for (auto &SubprogramDirect : P.second)
4950       if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4951         EltTys.push_back(SubprogramDirect.getPointer());
4952 
4953     llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4954     DBuilder.replaceArrays(InterfaceDecl, Elements);
4955   }
4956 
4957   for (const auto &P : ReplaceMap) {
4958     assert(P.second);
4959     auto *Ty = cast<llvm::DIType>(P.second);
4960     assert(Ty->isForwardDecl());
4961 
4962     auto It = TypeCache.find(P.first);
4963     assert(It != TypeCache.end());
4964     assert(It->second);
4965 
4966     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4967                               cast<llvm::DIType>(It->second));
4968   }
4969 
4970   for (const auto &P : FwdDeclReplaceMap) {
4971     assert(P.second);
4972     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4973     llvm::Metadata *Repl;
4974 
4975     auto It = DeclCache.find(P.first);
4976     // If there has been no definition for the declaration, call RAUW
4977     // with ourselves, that will destroy the temporary MDNode and
4978     // replace it with a standard one, avoiding leaking memory.
4979     if (It == DeclCache.end())
4980       Repl = P.second;
4981     else
4982       Repl = It->second;
4983 
4984     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4985       Repl = GVE->getVariable();
4986     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4987   }
4988 
4989   // We keep our own list of retained types, because we need to look
4990   // up the final type in the type cache.
4991   for (auto &RT : RetainedTypes)
4992     if (auto MD = TypeCache[RT])
4993       DBuilder.retainType(cast<llvm::DIType>(MD));
4994 
4995   DBuilder.finalize();
4996 }
4997 
4998 // Don't ignore in case of explicit cast where it is referenced indirectly.
4999 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
5000   if (CGM.getCodeGenOpts().hasReducedDebugInfo())
5001     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5002       DBuilder.retainType(DieTy);
5003 }
5004 
5005 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
5006   if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
5007     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5008       DBuilder.retainType(DieTy);
5009 }
5010 
5011 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
5012   if (LexicalBlockStack.empty())
5013     return llvm::DebugLoc();
5014 
5015   llvm::MDNode *Scope = LexicalBlockStack.back();
5016   return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
5017                                getColumnNumber(Loc), Scope);
5018 }
5019 
5020 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
5021   // Call site-related attributes are only useful in optimized programs, and
5022   // when there's a possibility of debugging backtraces.
5023   if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
5024       DebugKind == codegenoptions::LocTrackingOnly)
5025     return llvm::DINode::FlagZero;
5026 
5027   // Call site-related attributes are available in DWARF v5. Some debuggers,
5028   // while not fully DWARF v5-compliant, may accept these attributes as if they
5029   // were part of DWARF v4.
5030   bool SupportsDWARFv4Ext =
5031       CGM.getCodeGenOpts().DwarfVersion == 4 &&
5032       (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
5033        CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
5034 
5035   if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
5036     return llvm::DINode::FlagZero;
5037 
5038   return llvm::DINode::FlagAllCallsDescribed;
5039 }
5040