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