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