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