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