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