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