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