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