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