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