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