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