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