]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp
Upgrade our copies of clang, llvm, lld, lldb, compiler-rt, libc++,
[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   // Always get the full list of parameters, not just the ones from the
1822   // specialization. A partial specialization may have fewer parameters than
1823   // there are arguments.
1824   auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1825   if (!TS)
1826     return llvm::DINodeArray();
1827   VarTemplateDecl *T = TS->getSpecializedTemplate();
1828   const TemplateParameterList *TList = T->getTemplateParameters();
1829   auto TA = TS->getTemplateArgs().asArray();
1830   return CollectTemplateParams(TList, TA, Unit);
1831 }
1832
1833 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1834     const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1835   // Always get the full list of parameters, not just the ones from the
1836   // specialization. A partial specialization may have fewer parameters than
1837   // there are arguments.
1838   TemplateParameterList *TPList =
1839       TSpecial->getSpecializedTemplate()->getTemplateParameters();
1840   const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1841   return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1842 }
1843
1844 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1845   if (VTablePtrType)
1846     return VTablePtrType;
1847
1848   ASTContext &Context = CGM.getContext();
1849
1850   /* Function type */
1851   llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1852   llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1853   llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1854   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1855   unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1856   Optional<unsigned> DWARFAddressSpace =
1857       CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1858
1859   llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1860       SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1861   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1862   return VTablePtrType;
1863 }
1864
1865 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1866   // Copy the gdb compatible name on the side and use its reference.
1867   return internString("_vptr$", RD->getNameAsString());
1868 }
1869
1870 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1871                                     SmallVectorImpl<llvm::Metadata *> &EltTys,
1872                                     llvm::DICompositeType *RecordTy) {
1873   // If this class is not dynamic then there is not any vtable info to collect.
1874   if (!RD->isDynamicClass())
1875     return;
1876
1877   // Don't emit any vtable shape or vptr info if this class doesn't have an
1878   // extendable vfptr. This can happen if the class doesn't have virtual
1879   // methods, or in the MS ABI if those virtual methods only come from virtually
1880   // inherited bases.
1881   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1882   if (!RL.hasExtendableVFPtr())
1883     return;
1884
1885   // CodeView needs to know how large the vtable of every dynamic class is, so
1886   // emit a special named pointer type into the element list. The vptr type
1887   // points to this type as well.
1888   llvm::DIType *VPtrTy = nullptr;
1889   bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
1890                          CGM.getTarget().getCXXABI().isMicrosoft();
1891   if (NeedVTableShape) {
1892     uint64_t PtrWidth =
1893         CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1894     const VTableLayout &VFTLayout =
1895         CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
1896     unsigned VSlotCount =
1897         VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
1898     unsigned VTableWidth = PtrWidth * VSlotCount;
1899     unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1900     Optional<unsigned> DWARFAddressSpace =
1901         CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1902
1903     // Create a very wide void* type and insert it directly in the element list.
1904     llvm::DIType *VTableType = DBuilder.createPointerType(
1905         nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1906     EltTys.push_back(VTableType);
1907
1908     // The vptr is a pointer to this special vtable type.
1909     VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
1910   }
1911
1912   // If there is a primary base then the artificial vptr member lives there.
1913   if (RL.getPrimaryBase())
1914     return;
1915
1916   if (!VPtrTy)
1917     VPtrTy = getOrCreateVTablePtrType(Unit);
1918
1919   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1920   llvm::DIType *VPtrMember =
1921       DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1922                                 llvm::DINode::FlagArtificial, VPtrTy);
1923   EltTys.push_back(VPtrMember);
1924 }
1925
1926 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1927                                                  SourceLocation Loc) {
1928   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1929   llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1930   return T;
1931 }
1932
1933 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1934                                                     SourceLocation Loc) {
1935   return getOrCreateStandaloneType(D, Loc);
1936 }
1937
1938 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1939                                                      SourceLocation Loc) {
1940   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1941   assert(!D.isNull() && "null type");
1942   llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1943   assert(T && "could not create debug info for type");
1944
1945   RetainedTypes.push_back(D.getAsOpaquePtr());
1946   return T;
1947 }
1948
1949 void CGDebugInfo::completeType(const EnumDecl *ED) {
1950   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1951     return;
1952   QualType Ty = CGM.getContext().getEnumType(ED);
1953   void *TyPtr = Ty.getAsOpaquePtr();
1954   auto I = TypeCache.find(TyPtr);
1955   if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1956     return;
1957   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1958   assert(!Res->isForwardDecl());
1959   TypeCache[TyPtr].reset(Res);
1960 }
1961
1962 void CGDebugInfo::completeType(const RecordDecl *RD) {
1963   if (DebugKind > codegenoptions::LimitedDebugInfo ||
1964       !CGM.getLangOpts().CPlusPlus)
1965     completeRequiredType(RD);
1966 }
1967
1968 /// Return true if the class or any of its methods are marked dllimport.
1969 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
1970   if (RD->hasAttr<DLLImportAttr>())
1971     return true;
1972   for (const CXXMethodDecl *MD : RD->methods())
1973     if (MD->hasAttr<DLLImportAttr>())
1974       return true;
1975   return false;
1976 }
1977
1978 /// Does a type definition exist in an imported clang module?
1979 static bool isDefinedInClangModule(const RecordDecl *RD) {
1980   // Only definitions that where imported from an AST file come from a module.
1981   if (!RD || !RD->isFromASTFile())
1982     return false;
1983   // Anonymous entities cannot be addressed. Treat them as not from module.
1984   if (!RD->isExternallyVisible() && RD->getName().empty())
1985     return false;
1986   if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
1987     if (!CXXDecl->isCompleteDefinition())
1988       return false;
1989     // Check wether RD is a template.
1990     auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
1991     if (TemplateKind != TSK_Undeclared) {
1992       // Unfortunately getOwningModule() isn't accurate enough to find the
1993       // owning module of a ClassTemplateSpecializationDecl that is inside a
1994       // namespace spanning multiple modules.
1995       bool Explicit = false;
1996       if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
1997         Explicit = TD->isExplicitInstantiationOrSpecialization();
1998       if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
1999         return false;
2000       // This is a template, check the origin of the first member.
2001       if (CXXDecl->field_begin() == CXXDecl->field_end())
2002         return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2003       if (!CXXDecl->field_begin()->isFromASTFile())
2004         return false;
2005     }
2006   }
2007   return true;
2008 }
2009
2010 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2011   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2012     if (CXXRD->isDynamicClass() &&
2013         CGM.getVTableLinkage(CXXRD) ==
2014             llvm::GlobalValue::AvailableExternallyLinkage &&
2015         !isClassOrMethodDLLImport(CXXRD))
2016       return;
2017
2018   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2019     return;
2020
2021   completeClass(RD);
2022 }
2023
2024 void CGDebugInfo::completeClass(const RecordDecl *RD) {
2025   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2026     return;
2027   QualType Ty = CGM.getContext().getRecordType(RD);
2028   void *TyPtr = Ty.getAsOpaquePtr();
2029   auto I = TypeCache.find(TyPtr);
2030   if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2031     return;
2032   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2033   assert(!Res->isForwardDecl());
2034   TypeCache[TyPtr].reset(Res);
2035 }
2036
2037 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2038                                         CXXRecordDecl::method_iterator End) {
2039   for (CXXMethodDecl *MD : llvm::make_range(I, End))
2040     if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2041       if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2042           !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2043         return true;
2044   return false;
2045 }
2046
2047 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2048                                  bool DebugTypeExtRefs, const RecordDecl *RD,
2049                                  const LangOptions &LangOpts) {
2050   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2051     return true;
2052
2053   if (auto *ES = RD->getASTContext().getExternalSource())
2054     if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2055       return true;
2056
2057   if (DebugKind > codegenoptions::LimitedDebugInfo)
2058     return false;
2059
2060   if (!LangOpts.CPlusPlus)
2061     return false;
2062
2063   if (!RD->isCompleteDefinitionRequired())
2064     return true;
2065
2066   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2067
2068   if (!CXXDecl)
2069     return false;
2070
2071   // Only emit complete debug info for a dynamic class when its vtable is
2072   // emitted.  However, Microsoft debuggers don't resolve type information
2073   // across DLL boundaries, so skip this optimization if the class or any of its
2074   // methods are marked dllimport. This isn't a complete solution, since objects
2075   // without any dllimport methods can be used in one DLL and constructed in
2076   // another, but it is the current behavior of LimitedDebugInfo.
2077   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2078       !isClassOrMethodDLLImport(CXXDecl))
2079     return true;
2080
2081   TemplateSpecializationKind Spec = TSK_Undeclared;
2082   if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2083     Spec = SD->getSpecializationKind();
2084
2085   if (Spec == TSK_ExplicitInstantiationDeclaration &&
2086       hasExplicitMemberDefinition(CXXDecl->method_begin(),
2087                                   CXXDecl->method_end()))
2088     return true;
2089
2090   return false;
2091 }
2092
2093 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2094   if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2095     return;
2096
2097   QualType Ty = CGM.getContext().getRecordType(RD);
2098   llvm::DIType *T = getTypeOrNull(Ty);
2099   if (T && T->isForwardDecl())
2100     completeClassData(RD);
2101 }
2102
2103 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2104   RecordDecl *RD = Ty->getDecl();
2105   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2106   if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2107                                 CGM.getLangOpts())) {
2108     if (!T)
2109       T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2110     return T;
2111   }
2112
2113   return CreateTypeDefinition(Ty);
2114 }
2115
2116 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2117   RecordDecl *RD = Ty->getDecl();
2118
2119   // Get overall information about the record type for the debug info.
2120   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2121
2122   // Records and classes and unions can all be recursive.  To handle them, we
2123   // first generate a debug descriptor for the struct as a forward declaration.
2124   // Then (if it is a definition) we go through and get debug info for all of
2125   // its members.  Finally, we create a descriptor for the complete type (which
2126   // may refer to the forward decl if the struct is recursive) and replace all
2127   // uses of the forward declaration with the final definition.
2128   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
2129
2130   const RecordDecl *D = RD->getDefinition();
2131   if (!D || !D->isCompleteDefinition())
2132     return FwdDecl;
2133
2134   if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2135     CollectContainingType(CXXDecl, FwdDecl);
2136
2137   // Push the struct on region stack.
2138   LexicalBlockStack.emplace_back(&*FwdDecl);
2139   RegionMap[Ty->getDecl()].reset(FwdDecl);
2140
2141   // Convert all the elements.
2142   SmallVector<llvm::Metadata *, 16> EltTys;
2143   // what about nested types?
2144
2145   // Note: The split of CXXDecl information here is intentional, the
2146   // gdb tests will depend on a certain ordering at printout. The debug
2147   // information offsets are still correct if we merge them all together
2148   // though.
2149   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2150   if (CXXDecl) {
2151     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2152     CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
2153   }
2154
2155   // Collect data fields (including static variables and any initializers).
2156   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2157   if (CXXDecl)
2158     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2159
2160   LexicalBlockStack.pop_back();
2161   RegionMap.erase(Ty->getDecl());
2162
2163   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2164   DBuilder.replaceArrays(FwdDecl, Elements);
2165
2166   if (FwdDecl->isTemporary())
2167     FwdDecl =
2168         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2169
2170   RegionMap[Ty->getDecl()].reset(FwdDecl);
2171   return FwdDecl;
2172 }
2173
2174 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2175                                       llvm::DIFile *Unit) {
2176   // Ignore protocols.
2177   return getOrCreateType(Ty->getBaseType(), Unit);
2178 }
2179
2180 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2181                                       llvm::DIFile *Unit) {
2182   // Ignore protocols.
2183   SourceLocation Loc = Ty->getDecl()->getLocation();
2184
2185   // Use Typedefs to represent ObjCTypeParamType.
2186   return DBuilder.createTypedef(
2187       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2188       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2189       getDeclContextDescriptor(Ty->getDecl()));
2190 }
2191
2192 /// \return true if Getter has the default name for the property PD.
2193 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2194                                  const ObjCMethodDecl *Getter) {
2195   assert(PD);
2196   if (!Getter)
2197     return true;
2198
2199   assert(Getter->getDeclName().isObjCZeroArgSelector());
2200   return PD->getName() ==
2201          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2202 }
2203
2204 /// \return true if Setter has the default name for the property PD.
2205 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2206                                  const ObjCMethodDecl *Setter) {
2207   assert(PD);
2208   if (!Setter)
2209     return true;
2210
2211   assert(Setter->getDeclName().isObjCOneArgSelector());
2212   return SelectorTable::constructSetterName(PD->getName()) ==
2213          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2214 }
2215
2216 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2217                                       llvm::DIFile *Unit) {
2218   ObjCInterfaceDecl *ID = Ty->getDecl();
2219   if (!ID)
2220     return nullptr;
2221
2222   // Return a forward declaration if this type was imported from a clang module,
2223   // and this is not the compile unit with the implementation of the type (which
2224   // may contain hidden ivars).
2225   if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2226       !ID->getImplementation())
2227     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2228                                       ID->getName(),
2229                                       getDeclContextDescriptor(ID), Unit, 0);
2230
2231   // Get overall information about the record type for the debug info.
2232   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2233   unsigned Line = getLineNumber(ID->getLocation());
2234   auto RuntimeLang =
2235       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2236
2237   // If this is just a forward declaration return a special forward-declaration
2238   // debug type since we won't be able to lay out the entire type.
2239   ObjCInterfaceDecl *Def = ID->getDefinition();
2240   if (!Def || !Def->getImplementation()) {
2241     llvm::DIScope *Mod = getParentModuleOrNull(ID);
2242     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2243         llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2244         DefUnit, Line, RuntimeLang);
2245     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2246     return FwdDecl;
2247   }
2248
2249   return CreateTypeDefinition(Ty, Unit);
2250 }
2251
2252 llvm::DIModule *
2253 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2254                                   bool CreateSkeletonCU) {
2255   // Use the Module pointer as the key into the cache. This is a
2256   // nullptr if the "Module" is a PCH, which is safe because we don't
2257   // support chained PCH debug info, so there can only be a single PCH.
2258   const Module *M = Mod.getModuleOrNull();
2259   auto ModRef = ModuleCache.find(M);
2260   if (ModRef != ModuleCache.end())
2261     return cast<llvm::DIModule>(ModRef->second);
2262
2263   // Macro definitions that were defined with "-D" on the command line.
2264   SmallString<128> ConfigMacros;
2265   {
2266     llvm::raw_svector_ostream OS(ConfigMacros);
2267     const auto &PPOpts = CGM.getPreprocessorOpts();
2268     unsigned I = 0;
2269     // Translate the macro definitions back into a command line.
2270     for (auto &M : PPOpts.Macros) {
2271       if (++I > 1)
2272         OS << " ";
2273       const std::string &Macro = M.first;
2274       bool Undef = M.second;
2275       OS << "\"-" << (Undef ? 'U' : 'D');
2276       for (char c : Macro)
2277         switch (c) {
2278         case '\\':
2279           OS << "\\\\";
2280           break;
2281         case '"':
2282           OS << "\\\"";
2283           break;
2284         default:
2285           OS << c;
2286         }
2287       OS << '\"';
2288     }
2289   }
2290
2291   bool IsRootModule = M ? !M->Parent : true;
2292   if (CreateSkeletonCU && IsRootModule) {
2293     // PCH files don't have a signature field in the control block,
2294     // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2295     // We use the lower 64 bits for debug info.
2296     uint64_t Signature =
2297         Mod.getSignature()
2298             ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2299             : ~1ULL;
2300     llvm::DIBuilder DIB(CGM.getModule());
2301     DIB.createCompileUnit(TheCU->getSourceLanguage(),
2302                           // TODO: Support "Source" from external AST providers?
2303                           DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2304                           TheCU->getProducer(), true, StringRef(), 0,
2305                           Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2306                           Signature);
2307     DIB.finalize();
2308   }
2309   llvm::DIModule *Parent =
2310       IsRootModule ? nullptr
2311                    : getOrCreateModuleRef(
2312                          ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2313                          CreateSkeletonCU);
2314   llvm::DIModule *DIMod =
2315       DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2316                             Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2317   ModuleCache[M].reset(DIMod);
2318   return DIMod;
2319 }
2320
2321 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2322                                                 llvm::DIFile *Unit) {
2323   ObjCInterfaceDecl *ID = Ty->getDecl();
2324   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2325   unsigned Line = getLineNumber(ID->getLocation());
2326   unsigned RuntimeLang = TheCU->getSourceLanguage();
2327
2328   // Bit size, align and offset of the type.
2329   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2330   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2331
2332   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2333   if (ID->getImplementation())
2334     Flags |= llvm::DINode::FlagObjcClassComplete;
2335
2336   llvm::DIScope *Mod = getParentModuleOrNull(ID);
2337   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2338       Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2339       nullptr, llvm::DINodeArray(), RuntimeLang);
2340
2341   QualType QTy(Ty, 0);
2342   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2343
2344   // Push the struct on region stack.
2345   LexicalBlockStack.emplace_back(RealDecl);
2346   RegionMap[Ty->getDecl()].reset(RealDecl);
2347
2348   // Convert all the elements.
2349   SmallVector<llvm::Metadata *, 16> EltTys;
2350
2351   ObjCInterfaceDecl *SClass = ID->getSuperClass();
2352   if (SClass) {
2353     llvm::DIType *SClassTy =
2354         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2355     if (!SClassTy)
2356       return nullptr;
2357
2358     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2359                                                       llvm::DINode::FlagZero);
2360     EltTys.push_back(InhTag);
2361   }
2362
2363   // Create entries for all of the properties.
2364   auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2365     SourceLocation Loc = PD->getLocation();
2366     llvm::DIFile *PUnit = getOrCreateFile(Loc);
2367     unsigned PLine = getLineNumber(Loc);
2368     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2369     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2370     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2371         PD->getName(), PUnit, PLine,
2372         hasDefaultGetterName(PD, Getter) ? ""
2373                                          : getSelectorName(PD->getGetterName()),
2374         hasDefaultSetterName(PD, Setter) ? ""
2375                                          : getSelectorName(PD->getSetterName()),
2376         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2377     EltTys.push_back(PropertyNode);
2378   };
2379   {
2380     llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2381     for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2382       for (auto *PD : ClassExt->properties()) {
2383         PropertySet.insert(PD->getIdentifier());
2384         AddProperty(PD);
2385       }
2386     for (const auto *PD : ID->properties()) {
2387       // Don't emit duplicate metadata for properties that were already in a
2388       // class extension.
2389       if (!PropertySet.insert(PD->getIdentifier()).second)
2390         continue;
2391       AddProperty(PD);
2392     }
2393   }
2394
2395   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2396   unsigned FieldNo = 0;
2397   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2398        Field = Field->getNextIvar(), ++FieldNo) {
2399     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2400     if (!FieldTy)
2401       return nullptr;
2402
2403     StringRef FieldName = Field->getName();
2404
2405     // Ignore unnamed fields.
2406     if (FieldName.empty())
2407       continue;
2408
2409     // Get the location for the field.
2410     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2411     unsigned FieldLine = getLineNumber(Field->getLocation());
2412     QualType FType = Field->getType();
2413     uint64_t FieldSize = 0;
2414     uint32_t FieldAlign = 0;
2415
2416     if (!FType->isIncompleteArrayType()) {
2417
2418       // Bit size, align and offset of the type.
2419       FieldSize = Field->isBitField()
2420                       ? Field->getBitWidthValue(CGM.getContext())
2421                       : CGM.getContext().getTypeSize(FType);
2422       FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2423     }
2424
2425     uint64_t FieldOffset;
2426     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2427       // We don't know the runtime offset of an ivar if we're using the
2428       // non-fragile ABI.  For bitfields, use the bit offset into the first
2429       // byte of storage of the bitfield.  For other fields, use zero.
2430       if (Field->isBitField()) {
2431         FieldOffset =
2432             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2433         FieldOffset %= CGM.getContext().getCharWidth();
2434       } else {
2435         FieldOffset = 0;
2436       }
2437     } else {
2438       FieldOffset = RL.getFieldOffset(FieldNo);
2439     }
2440
2441     llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2442     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2443       Flags = llvm::DINode::FlagProtected;
2444     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2445       Flags = llvm::DINode::FlagPrivate;
2446     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2447       Flags = llvm::DINode::FlagPublic;
2448
2449     llvm::MDNode *PropertyNode = nullptr;
2450     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2451       if (ObjCPropertyImplDecl *PImpD =
2452               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2453         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2454           SourceLocation Loc = PD->getLocation();
2455           llvm::DIFile *PUnit = getOrCreateFile(Loc);
2456           unsigned PLine = getLineNumber(Loc);
2457           ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2458           ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2459           PropertyNode = DBuilder.createObjCProperty(
2460               PD->getName(), PUnit, PLine,
2461               hasDefaultGetterName(PD, Getter)
2462                   ? ""
2463                   : getSelectorName(PD->getGetterName()),
2464               hasDefaultSetterName(PD, Setter)
2465                   ? ""
2466                   : getSelectorName(PD->getSetterName()),
2467               PD->getPropertyAttributes(),
2468               getOrCreateType(PD->getType(), PUnit));
2469         }
2470       }
2471     }
2472     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2473                                       FieldSize, FieldAlign, FieldOffset, Flags,
2474                                       FieldTy, PropertyNode);
2475     EltTys.push_back(FieldTy);
2476   }
2477
2478   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2479   DBuilder.replaceArrays(RealDecl, Elements);
2480
2481   LexicalBlockStack.pop_back();
2482   return RealDecl;
2483 }
2484
2485 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2486                                       llvm::DIFile *Unit) {
2487   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2488   int64_t Count = Ty->getNumElements();
2489
2490   llvm::Metadata *Subscript;
2491   QualType QTy(Ty, 0);
2492   auto SizeExpr = SizeExprCache.find(QTy);
2493   if (SizeExpr != SizeExprCache.end())
2494     Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2495   else
2496     Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
2497   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2498
2499   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2500   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2501
2502   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2503 }
2504
2505 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2506   uint64_t Size;
2507   uint32_t Align;
2508
2509   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2510   if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2511     Size = 0;
2512     Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2513                                    CGM.getContext());
2514   } else if (Ty->isIncompleteArrayType()) {
2515     Size = 0;
2516     if (Ty->getElementType()->isIncompleteType())
2517       Align = 0;
2518     else
2519       Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2520   } else if (Ty->isIncompleteType()) {
2521     Size = 0;
2522     Align = 0;
2523   } else {
2524     // Size and align of the whole array, not the element type.
2525     Size = CGM.getContext().getTypeSize(Ty);
2526     Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2527   }
2528
2529   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
2530   // interior arrays, do we care?  Why aren't nested arrays represented the
2531   // obvious/recursive way?
2532   SmallVector<llvm::Metadata *, 8> Subscripts;
2533   QualType EltTy(Ty, 0);
2534   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2535     // If the number of elements is known, then count is that number. Otherwise,
2536     // it's -1. This allows us to represent a subrange with an array of 0
2537     // elements, like this:
2538     //
2539     //   struct foo {
2540     //     int x[0];
2541     //   };
2542     int64_t Count = -1; // Count == -1 is an unbounded array.
2543     if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2544       Count = CAT->getSize().getZExtValue();
2545     else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2546       if (Expr *Size = VAT->getSizeExpr()) {
2547         Expr::EvalResult Result;
2548         if (Size->EvaluateAsInt(Result, CGM.getContext()))
2549           Count = Result.Val.getInt().getExtValue();
2550       }
2551     }
2552
2553     auto SizeNode = SizeExprCache.find(EltTy);
2554     if (SizeNode != SizeExprCache.end())
2555       Subscripts.push_back(
2556           DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2557     else
2558       Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2559     EltTy = Ty->getElementType();
2560   }
2561
2562   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2563
2564   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2565                                   SubscriptArray);
2566 }
2567
2568 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2569                                       llvm::DIFile *Unit) {
2570   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2571                                Ty->getPointeeType(), Unit);
2572 }
2573
2574 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2575                                       llvm::DIFile *Unit) {
2576   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2577                                Ty->getPointeeType(), Unit);
2578 }
2579
2580 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2581                                       llvm::DIFile *U) {
2582   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2583   uint64_t Size = 0;
2584
2585   if (!Ty->isIncompleteType()) {
2586     Size = CGM.getContext().getTypeSize(Ty);
2587
2588     // Set the MS inheritance model. There is no flag for the unspecified model.
2589     if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2590       switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2591       case MSInheritanceAttr::Keyword_single_inheritance:
2592         Flags |= llvm::DINode::FlagSingleInheritance;
2593         break;
2594       case MSInheritanceAttr::Keyword_multiple_inheritance:
2595         Flags |= llvm::DINode::FlagMultipleInheritance;
2596         break;
2597       case MSInheritanceAttr::Keyword_virtual_inheritance:
2598         Flags |= llvm::DINode::FlagVirtualInheritance;
2599         break;
2600       case MSInheritanceAttr::Keyword_unspecified_inheritance:
2601         break;
2602       }
2603     }
2604   }
2605
2606   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2607   if (Ty->isMemberDataPointerType())
2608     return DBuilder.createMemberPointerType(
2609         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2610         Flags);
2611
2612   const FunctionProtoType *FPT =
2613       Ty->getPointeeType()->getAs<FunctionProtoType>();
2614   return DBuilder.createMemberPointerType(
2615       getOrCreateInstanceMethodType(
2616           CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
2617           FPT, U),
2618       ClassType, Size, /*Align=*/0, Flags);
2619 }
2620
2621 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2622   auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2623   return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2624 }
2625
2626 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2627   return getOrCreateType(Ty->getElementType(), U);
2628 }
2629
2630 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2631   const EnumDecl *ED = Ty->getDecl();
2632
2633   uint64_t Size = 0;
2634   uint32_t Align = 0;
2635   if (!ED->getTypeForDecl()->isIncompleteType()) {
2636     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2637     Align = getDeclAlignIfRequired(ED, CGM.getContext());
2638   }
2639
2640   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2641
2642   bool isImportedFromModule =
2643       DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2644
2645   // If this is just a forward declaration, construct an appropriately
2646   // marked node and just return it.
2647   if (isImportedFromModule || !ED->getDefinition()) {
2648     // Note that it is possible for enums to be created as part of
2649     // their own declcontext. In this case a FwdDecl will be created
2650     // twice. This doesn't cause a problem because both FwdDecls are
2651     // entered into the ReplaceMap: finalize() will replace the first
2652     // FwdDecl with the second and then replace the second with
2653     // complete type.
2654     llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2655     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2656     llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2657         llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2658
2659     unsigned Line = getLineNumber(ED->getLocation());
2660     StringRef EDName = ED->getName();
2661     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2662         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2663         0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
2664
2665     ReplaceMap.emplace_back(
2666         std::piecewise_construct, std::make_tuple(Ty),
2667         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2668     return RetTy;
2669   }
2670
2671   return CreateTypeDefinition(Ty);
2672 }
2673
2674 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2675   const EnumDecl *ED = Ty->getDecl();
2676   uint64_t Size = 0;
2677   uint32_t Align = 0;
2678   if (!ED->getTypeForDecl()->isIncompleteType()) {
2679     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2680     Align = getDeclAlignIfRequired(ED, CGM.getContext());
2681   }
2682
2683   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2684
2685   // Create elements for each enumerator.
2686   SmallVector<llvm::Metadata *, 16> Enumerators;
2687   ED = ED->getDefinition();
2688   bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
2689   for (const auto *Enum : ED->enumerators()) {
2690     const auto &InitVal = Enum->getInitVal();
2691     auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2692     Enumerators.push_back(
2693         DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
2694   }
2695
2696   // Return a CompositeType for the enum itself.
2697   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2698
2699   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2700   unsigned Line = getLineNumber(ED->getLocation());
2701   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2702   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
2703   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2704                                         Line, Size, Align, EltArray, ClassTy,
2705                                         Identifier, ED->isScoped());
2706 }
2707
2708 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2709                                         unsigned MType, SourceLocation LineLoc,
2710                                         StringRef Name, StringRef Value) {
2711   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2712   return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2713 }
2714
2715 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2716                                                     SourceLocation LineLoc,
2717                                                     SourceLocation FileLoc) {
2718   llvm::DIFile *FName = getOrCreateFile(FileLoc);
2719   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2720   return DBuilder.createTempMacroFile(Parent, Line, FName);
2721 }
2722
2723 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2724   Qualifiers Quals;
2725   do {
2726     Qualifiers InnerQuals = T.getLocalQualifiers();
2727     // Qualifiers::operator+() doesn't like it if you add a Qualifier
2728     // that is already there.
2729     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2730     Quals += InnerQuals;
2731     QualType LastT = T;
2732     switch (T->getTypeClass()) {
2733     default:
2734       return C.getQualifiedType(T.getTypePtr(), Quals);
2735     case Type::TemplateSpecialization: {
2736       const auto *Spec = cast<TemplateSpecializationType>(T);
2737       if (Spec->isTypeAlias())
2738         return C.getQualifiedType(T.getTypePtr(), Quals);
2739       T = Spec->desugar();
2740       break;
2741     }
2742     case Type::TypeOfExpr:
2743       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2744       break;
2745     case Type::TypeOf:
2746       T = cast<TypeOfType>(T)->getUnderlyingType();
2747       break;
2748     case Type::Decltype:
2749       T = cast<DecltypeType>(T)->getUnderlyingType();
2750       break;
2751     case Type::UnaryTransform:
2752       T = cast<UnaryTransformType>(T)->getUnderlyingType();
2753       break;
2754     case Type::Attributed:
2755       T = cast<AttributedType>(T)->getEquivalentType();
2756       break;
2757     case Type::Elaborated:
2758       T = cast<ElaboratedType>(T)->getNamedType();
2759       break;
2760     case Type::Paren:
2761       T = cast<ParenType>(T)->getInnerType();
2762       break;
2763     case Type::SubstTemplateTypeParm:
2764       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2765       break;
2766     case Type::Auto:
2767     case Type::DeducedTemplateSpecialization: {
2768       QualType DT = cast<DeducedType>(T)->getDeducedType();
2769       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2770       T = DT;
2771       break;
2772     }
2773     case Type::Adjusted:
2774     case Type::Decayed:
2775       // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2776       T = cast<AdjustedType>(T)->getAdjustedType();
2777       break;
2778     }
2779
2780     assert(T != LastT && "Type unwrapping failed to unwrap!");
2781     (void)LastT;
2782   } while (true);
2783 }
2784
2785 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2786
2787   // Unwrap the type as needed for debug information.
2788   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2789
2790   auto It = TypeCache.find(Ty.getAsOpaquePtr());
2791   if (It != TypeCache.end()) {
2792     // Verify that the debug info still exists.
2793     if (llvm::Metadata *V = It->second)
2794       return cast<llvm::DIType>(V);
2795   }
2796
2797   return nullptr;
2798 }
2799
2800 void CGDebugInfo::completeTemplateDefinition(
2801     const ClassTemplateSpecializationDecl &SD) {
2802   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2803     return;
2804   completeUnusedClass(SD);
2805 }
2806
2807 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2808   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2809     return;
2810
2811   completeClassData(&D);
2812   // In case this type has no member function definitions being emitted, ensure
2813   // it is retained
2814   RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
2815 }
2816
2817 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2818   if (Ty.isNull())
2819     return nullptr;
2820
2821   // Unwrap the type as needed for debug information.
2822   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2823
2824   if (auto *T = getTypeOrNull(Ty))
2825     return T;
2826
2827   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2828   void *TyPtr = Ty.getAsOpaquePtr();
2829
2830   // And update the type cache.
2831   TypeCache[TyPtr].reset(Res);
2832
2833   return Res;
2834 }
2835
2836 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2837   // A forward declaration inside a module header does not belong to the module.
2838   if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2839     return nullptr;
2840   if (DebugTypeExtRefs && D->isFromASTFile()) {
2841     // Record a reference to an imported clang module or precompiled header.
2842     auto *Reader = CGM.getContext().getExternalSource();
2843     auto Idx = D->getOwningModuleID();
2844     auto Info = Reader->getSourceDescriptor(Idx);
2845     if (Info)
2846       return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2847   } else if (ClangModuleMap) {
2848     // We are building a clang module or a precompiled header.
2849     //
2850     // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2851     // and it wouldn't be necessary to specify the parent scope
2852     // because the type is already unique by definition (it would look
2853     // like the output of -fno-standalone-debug). On the other hand,
2854     // the parent scope helps a consumer to quickly locate the object
2855     // file where the type's definition is located, so it might be
2856     // best to make this behavior a command line or debugger tuning
2857     // option.
2858     if (Module *M = D->getOwningModule()) {
2859       // This is a (sub-)module.
2860       auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2861       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2862     } else {
2863       // This the precompiled header being built.
2864       return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
2865     }
2866   }
2867
2868   return nullptr;
2869 }
2870
2871 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2872   // Handle qualifiers, which recursively handles what they refer to.
2873   if (Ty.hasLocalQualifiers())
2874     return CreateQualifiedType(Ty, Unit);
2875
2876   // Work out details of type.
2877   switch (Ty->getTypeClass()) {
2878 #define TYPE(Class, Base)
2879 #define ABSTRACT_TYPE(Class, Base)
2880 #define NON_CANONICAL_TYPE(Class, Base)
2881 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2882 #include "clang/AST/TypeNodes.def"
2883     llvm_unreachable("Dependent types cannot show up in debug information");
2884
2885   case Type::ExtVector:
2886   case Type::Vector:
2887     return CreateType(cast<VectorType>(Ty), Unit);
2888   case Type::ObjCObjectPointer:
2889     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2890   case Type::ObjCObject:
2891     return CreateType(cast<ObjCObjectType>(Ty), Unit);
2892   case Type::ObjCTypeParam:
2893     return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
2894   case Type::ObjCInterface:
2895     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2896   case Type::Builtin:
2897     return CreateType(cast<BuiltinType>(Ty));
2898   case Type::Complex:
2899     return CreateType(cast<ComplexType>(Ty));
2900   case Type::Pointer:
2901     return CreateType(cast<PointerType>(Ty), Unit);
2902   case Type::BlockPointer:
2903     return CreateType(cast<BlockPointerType>(Ty), Unit);
2904   case Type::Typedef:
2905     return CreateType(cast<TypedefType>(Ty), Unit);
2906   case Type::Record:
2907     return CreateType(cast<RecordType>(Ty));
2908   case Type::Enum:
2909     return CreateEnumType(cast<EnumType>(Ty));
2910   case Type::FunctionProto:
2911   case Type::FunctionNoProto:
2912     return CreateType(cast<FunctionType>(Ty), Unit);
2913   case Type::ConstantArray:
2914   case Type::VariableArray:
2915   case Type::IncompleteArray:
2916     return CreateType(cast<ArrayType>(Ty), Unit);
2917
2918   case Type::LValueReference:
2919     return CreateType(cast<LValueReferenceType>(Ty), Unit);
2920   case Type::RValueReference:
2921     return CreateType(cast<RValueReferenceType>(Ty), Unit);
2922
2923   case Type::MemberPointer:
2924     return CreateType(cast<MemberPointerType>(Ty), Unit);
2925
2926   case Type::Atomic:
2927     return CreateType(cast<AtomicType>(Ty), Unit);
2928
2929   case Type::Pipe:
2930     return CreateType(cast<PipeType>(Ty), Unit);
2931
2932   case Type::TemplateSpecialization:
2933     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2934
2935   case Type::Auto:
2936   case Type::Attributed:
2937   case Type::Adjusted:
2938   case Type::Decayed:
2939   case Type::DeducedTemplateSpecialization:
2940   case Type::Elaborated:
2941   case Type::Paren:
2942   case Type::SubstTemplateTypeParm:
2943   case Type::TypeOfExpr:
2944   case Type::TypeOf:
2945   case Type::Decltype:
2946   case Type::UnaryTransform:
2947   case Type::PackExpansion:
2948     break;
2949   }
2950
2951   llvm_unreachable("type should have been unwrapped!");
2952 }
2953
2954 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2955                                                            llvm::DIFile *Unit) {
2956   QualType QTy(Ty, 0);
2957
2958   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2959
2960   // We may have cached a forward decl when we could have created
2961   // a non-forward decl. Go ahead and create a non-forward decl
2962   // now.
2963   if (T && !T->isForwardDecl())
2964     return T;
2965
2966   // Otherwise create the type.
2967   llvm::DICompositeType *Res = CreateLimitedType(Ty);
2968
2969   // Propagate members from the declaration to the definition
2970   // CreateType(const RecordType*) will overwrite this with the members in the
2971   // correct order if the full type is needed.
2972   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2973
2974   // And update the type cache.
2975   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2976   return Res;
2977 }
2978
2979 // TODO: Currently used for context chains when limiting debug info.
2980 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2981   RecordDecl *RD = Ty->getDecl();
2982
2983   // Get overall information about the record type for the debug info.
2984   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2985   unsigned Line = getLineNumber(RD->getLocation());
2986   StringRef RDName = getClassName(RD);
2987
2988   llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2989
2990   // If we ended up creating the type during the context chain construction,
2991   // just return that.
2992   auto *T = cast_or_null<llvm::DICompositeType>(
2993       getTypeOrNull(CGM.getContext().getRecordType(RD)));
2994   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2995     return T;
2996
2997   // If this is just a forward or incomplete declaration, construct an
2998   // appropriately marked node and just return it.
2999   const RecordDecl *D = RD->getDefinition();
3000   if (!D || !D->isCompleteDefinition())
3001     return getOrCreateRecordFwdDecl(Ty, RDContext);
3002
3003   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3004   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3005
3006   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3007
3008   // Explicitly record the calling convention for C++ records.
3009   auto Flags = llvm::DINode::FlagZero;
3010   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3011     if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3012       Flags |= llvm::DINode::FlagTypePassByReference;
3013     else
3014       Flags |= llvm::DINode::FlagTypePassByValue;
3015
3016     // Record if a C++ record is trivial type.
3017     if (CXXRD->isTrivial())
3018       Flags |= llvm::DINode::FlagTrivial;
3019   }
3020
3021   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3022       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3023       Flags, Identifier);
3024
3025   // Elements of composite types usually have back to the type, creating
3026   // uniquing cycles.  Distinct nodes are more efficient.
3027   switch (RealDecl->getTag()) {
3028   default:
3029     llvm_unreachable("invalid composite type tag");
3030
3031   case llvm::dwarf::DW_TAG_array_type:
3032   case llvm::dwarf::DW_TAG_enumeration_type:
3033     // Array elements and most enumeration elements don't have back references,
3034     // so they don't tend to be involved in uniquing cycles and there is some
3035     // chance of merging them when linking together two modules.  Only make
3036     // them distinct if they are ODR-uniqued.
3037     if (Identifier.empty())
3038       break;
3039     LLVM_FALLTHROUGH;
3040
3041   case llvm::dwarf::DW_TAG_structure_type:
3042   case llvm::dwarf::DW_TAG_union_type:
3043   case llvm::dwarf::DW_TAG_class_type:
3044     // Immediately resolve to a distinct node.
3045     RealDecl =
3046         llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3047     break;
3048   }
3049
3050   RegionMap[Ty->getDecl()].reset(RealDecl);
3051   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3052
3053   if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3054     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3055                            CollectCXXTemplateParams(TSpecial, DefUnit));
3056   return RealDecl;
3057 }
3058
3059 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3060                                         llvm::DICompositeType *RealDecl) {
3061   // A class's primary base or the class itself contains the vtable.
3062   llvm::DICompositeType *ContainingType = nullptr;
3063   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3064   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3065     // Seek non-virtual primary base root.
3066     while (1) {
3067       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3068       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3069       if (PBT && !BRL.isPrimaryBaseVirtual())
3070         PBase = PBT;
3071       else
3072         break;
3073     }
3074     ContainingType = cast<llvm::DICompositeType>(
3075         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3076                         getOrCreateFile(RD->getLocation())));
3077   } else if (RD->isDynamicClass())
3078     ContainingType = RealDecl;
3079
3080   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3081 }
3082
3083 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3084                                             StringRef Name, uint64_t *Offset) {
3085   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3086   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3087   auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3088   llvm::DIType *Ty =
3089       DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3090                                 *Offset, llvm::DINode::FlagZero, FieldTy);
3091   *Offset += FieldSize;
3092   return Ty;
3093 }
3094
3095 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3096                                            StringRef &Name,
3097                                            StringRef &LinkageName,
3098                                            llvm::DIScope *&FDContext,
3099                                            llvm::DINodeArray &TParamsArray,
3100                                            llvm::DINode::DIFlags &Flags) {
3101   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3102   Name = getFunctionName(FD);
3103   // Use mangled name as linkage name for C/C++ functions.
3104   if (FD->hasPrototype()) {
3105     LinkageName = CGM.getMangledName(GD);
3106     Flags |= llvm::DINode::FlagPrototyped;
3107   }
3108   // No need to replicate the linkage name if it isn't different from the
3109   // subprogram name, no need to have it at all unless coverage is enabled or
3110   // debug is set to more than just line tables or extra debug info is needed.
3111   if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3112                               !CGM.getCodeGenOpts().EmitGcovNotes &&
3113                               !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3114                               DebugKind <= codegenoptions::DebugLineTablesOnly))
3115     LinkageName = StringRef();
3116
3117   if (DebugKind >= codegenoptions::LimitedDebugInfo) {
3118     if (const NamespaceDecl *NSDecl =
3119             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3120       FDContext = getOrCreateNamespace(NSDecl);
3121     else if (const RecordDecl *RDecl =
3122                  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3123       llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3124       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3125     }
3126     // Check if it is a noreturn-marked function
3127     if (FD->isNoReturn())
3128       Flags |= llvm::DINode::FlagNoReturn;
3129     // Collect template parameters.
3130     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3131   }
3132 }
3133
3134 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3135                                       unsigned &LineNo, QualType &T,
3136                                       StringRef &Name, StringRef &LinkageName,
3137                                       llvm::MDTuple *&TemplateParameters,
3138                                       llvm::DIScope *&VDContext) {
3139   Unit = getOrCreateFile(VD->getLocation());
3140   LineNo = getLineNumber(VD->getLocation());
3141
3142   setLocation(VD->getLocation());
3143
3144   T = VD->getType();
3145   if (T->isIncompleteArrayType()) {
3146     // CodeGen turns int[] into int[1] so we'll do the same here.
3147     llvm::APInt ConstVal(32, 1);
3148     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3149
3150     T = CGM.getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal,
3151                                               0);
3152   }
3153
3154   Name = VD->getName();
3155   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3156       !isa<ObjCMethodDecl>(VD->getDeclContext()))
3157     LinkageName = CGM.getMangledName(VD);
3158   if (LinkageName == Name)
3159     LinkageName = StringRef();
3160
3161   if (isa<VarTemplateSpecializationDecl>(VD)) {
3162     llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3163     TemplateParameters = parameterNodes.get();
3164   } else {
3165     TemplateParameters = nullptr;
3166   }
3167
3168   // Since we emit declarations (DW_AT_members) for static members, place the
3169   // definition of those static members in the namespace they were declared in
3170   // in the source code (the lexical decl context).
3171   // FIXME: Generalize this for even non-member global variables where the
3172   // declaration and definition may have different lexical decl contexts, once
3173   // we have support for emitting declarations of (non-member) global variables.
3174   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3175                                                    : VD->getDeclContext();
3176   // When a record type contains an in-line initialization of a static data
3177   // member, and the record type is marked as __declspec(dllexport), an implicit
3178   // definition of the member will be created in the record context.  DWARF
3179   // doesn't seem to have a nice way to describe this in a form that consumers
3180   // are likely to understand, so fake the "normal" situation of a definition
3181   // outside the class by putting it in the global scope.
3182   if (DC->isRecord())
3183     DC = CGM.getContext().getTranslationUnitDecl();
3184
3185   llvm::DIScope *Mod = getParentModuleOrNull(VD);
3186   VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3187 }
3188
3189 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3190                                                           bool Stub) {
3191   llvm::DINodeArray TParamsArray;
3192   StringRef Name, LinkageName;
3193   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3194   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3195   SourceLocation Loc = GD.getDecl()->getLocation();
3196   llvm::DIFile *Unit = getOrCreateFile(Loc);
3197   llvm::DIScope *DContext = Unit;
3198   unsigned Line = getLineNumber(Loc);
3199   collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3200                            Flags);
3201   auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
3202
3203   // Build function type.
3204   SmallVector<QualType, 16> ArgTypes;
3205   if (FD)
3206     for (const ParmVarDecl *Parm : FD->parameters())
3207       ArgTypes.push_back(Parm->getType());
3208   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3209   QualType FnType = CGM.getContext().getFunctionType(
3210       FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3211   if (!FD->isExternallyVisible())
3212     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3213   if (CGM.getLangOpts().Optimize)
3214     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3215
3216   if (Stub) {
3217     Flags |= getCallSiteRelatedAttrs();
3218     SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3219     return DBuilder.createFunction(
3220         DContext, Name, LinkageName, Unit, Line,
3221         getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3222         TParamsArray.get(), getFunctionDeclaration(FD));
3223   }
3224
3225   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3226       DContext, Name, LinkageName, Unit, Line,
3227       getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3228       TParamsArray.get(), getFunctionDeclaration(FD));
3229   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3230   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3231                                  std::make_tuple(CanonDecl),
3232                                  std::make_tuple(SP));
3233   return SP;
3234 }
3235
3236 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3237   return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3238 }
3239
3240 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3241   return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3242 }
3243
3244 llvm::DIGlobalVariable *
3245 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3246   QualType T;
3247   StringRef Name, LinkageName;
3248   SourceLocation Loc = VD->getLocation();
3249   llvm::DIFile *Unit = getOrCreateFile(Loc);
3250   llvm::DIScope *DContext = Unit;
3251   unsigned Line = getLineNumber(Loc);
3252   llvm::MDTuple *TemplateParameters = nullptr;
3253
3254   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3255                       DContext);
3256   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3257   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3258       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3259       !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3260   FwdDeclReplaceMap.emplace_back(
3261       std::piecewise_construct,
3262       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3263       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3264   return GV;
3265 }
3266
3267 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3268   // We only need a declaration (not a definition) of the type - so use whatever
3269   // we would otherwise do to get a type for a pointee. (forward declarations in
3270   // limited debug info, full definitions (if the type definition is available)
3271   // in unlimited debug info)
3272   if (const auto *TD = dyn_cast<TypeDecl>(D))
3273     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3274                            getOrCreateFile(TD->getLocation()));
3275   auto I = DeclCache.find(D->getCanonicalDecl());
3276
3277   if (I != DeclCache.end()) {
3278     auto N = I->second;
3279     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3280       return GVE->getVariable();
3281     return dyn_cast_or_null<llvm::DINode>(N);
3282   }
3283
3284   // No definition for now. Emit a forward definition that might be
3285   // merged with a potential upcoming definition.
3286   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3287     return getFunctionForwardDeclaration(FD);
3288   else if (const auto *VD = dyn_cast<VarDecl>(D))
3289     return getGlobalVariableForwardDeclaration(VD);
3290
3291   return nullptr;
3292 }
3293
3294 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3295   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3296     return nullptr;
3297
3298   const auto *FD = dyn_cast<FunctionDecl>(D);
3299   if (!FD)
3300     return nullptr;
3301
3302   // Setup context.
3303   auto *S = getDeclContextDescriptor(D);
3304
3305   auto MI = SPCache.find(FD->getCanonicalDecl());
3306   if (MI == SPCache.end()) {
3307     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3308       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3309                                      cast<llvm::DICompositeType>(S));
3310     }
3311   }
3312   if (MI != SPCache.end()) {
3313     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3314     if (SP && !SP->isDefinition())
3315       return SP;
3316   }
3317
3318   for (auto NextFD : FD->redecls()) {
3319     auto MI = SPCache.find(NextFD->getCanonicalDecl());
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   return nullptr;
3327 }
3328
3329 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3330 // implicit parameter "this".
3331 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3332                                                              QualType FnType,
3333                                                              llvm::DIFile *F) {
3334   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3335     // Create fake but valid subroutine type. Otherwise -verify would fail, and
3336     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3337     return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3338
3339   if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3340     return getOrCreateMethodType(Method, F);
3341
3342   const auto *FTy = FnType->getAs<FunctionType>();
3343   CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3344
3345   if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3346     // Add "self" and "_cmd"
3347     SmallVector<llvm::Metadata *, 16> Elts;
3348
3349     // First element is always return type. For 'void' functions it is NULL.
3350     QualType ResultTy = OMethod->getReturnType();
3351
3352     // Replace the instancetype keyword with the actual type.
3353     if (ResultTy == CGM.getContext().getObjCInstanceType())
3354       ResultTy = CGM.getContext().getPointerType(
3355           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3356
3357     Elts.push_back(getOrCreateType(ResultTy, F));
3358     // "self" pointer is always first argument.
3359     QualType SelfDeclTy;
3360     if (auto *SelfDecl = OMethod->getSelfDecl())
3361       SelfDeclTy = SelfDecl->getType();
3362     else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3363       if (FPT->getNumParams() > 1)
3364         SelfDeclTy = FPT->getParamType(0);
3365     if (!SelfDeclTy.isNull())
3366       Elts.push_back(
3367           CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3368     // "_cmd" pointer is always second argument.
3369     Elts.push_back(DBuilder.createArtificialType(
3370         getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3371     // Get rest of the arguments.
3372     for (const auto *PI : OMethod->parameters())
3373       Elts.push_back(getOrCreateType(PI->getType(), F));
3374     // Variadic methods need a special marker at the end of the type list.
3375     if (OMethod->isVariadic())
3376       Elts.push_back(DBuilder.createUnspecifiedParameter());
3377
3378     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3379     return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3380                                          getDwarfCC(CC));
3381   }
3382
3383   // Handle variadic function types; they need an additional
3384   // unspecified parameter.
3385   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3386     if (FD->isVariadic()) {
3387       SmallVector<llvm::Metadata *, 16> EltTys;
3388       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3389       if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3390         for (QualType ParamType : FPT->param_types())
3391           EltTys.push_back(getOrCreateType(ParamType, F));
3392       EltTys.push_back(DBuilder.createUnspecifiedParameter());
3393       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3394       return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3395                                            getDwarfCC(CC));
3396     }
3397
3398   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3399 }
3400
3401 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3402                                     SourceLocation ScopeLoc, QualType FnType,
3403                                     llvm::Function *Fn, bool CurFuncIsThunk,
3404                                     CGBuilderTy &Builder) {
3405
3406   StringRef Name;
3407   StringRef LinkageName;
3408
3409   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3410
3411   const Decl *D = GD.getDecl();
3412   bool HasDecl = (D != nullptr);
3413
3414   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3415   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3416   llvm::DIFile *Unit = getOrCreateFile(Loc);
3417   llvm::DIScope *FDContext = Unit;
3418   llvm::DINodeArray TParamsArray;
3419   if (!HasDecl) {
3420     // Use llvm function name.
3421     LinkageName = Fn->getName();
3422   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3423     // If there is a subprogram for this function available then use it.
3424     auto FI = SPCache.find(FD->getCanonicalDecl());
3425     if (FI != SPCache.end()) {
3426       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3427       if (SP && SP->isDefinition()) {
3428         LexicalBlockStack.emplace_back(SP);
3429         RegionMap[D].reset(SP);
3430         return;
3431       }
3432     }
3433     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3434                              TParamsArray, Flags);
3435   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3436     Name = getObjCMethodName(OMD);
3437     Flags |= llvm::DINode::FlagPrototyped;
3438   } else {
3439     // Use llvm function name.
3440     Name = Fn->getName();
3441     Flags |= llvm::DINode::FlagPrototyped;
3442   }
3443   if (Name.startswith("\01"))
3444     Name = Name.substr(1);
3445
3446   if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
3447     Flags |= llvm::DINode::FlagArtificial;
3448     // Artificial functions should not silently reuse CurLoc.
3449     CurLoc = SourceLocation();
3450   }
3451
3452   if (CurFuncIsThunk)
3453     Flags |= llvm::DINode::FlagThunk;
3454
3455   if (Fn->hasLocalLinkage())
3456     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3457   if (CGM.getLangOpts().Optimize)
3458     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3459
3460   llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3461   llvm::DISubprogram::DISPFlags SPFlagsForDef =
3462       SPFlags | llvm::DISubprogram::SPFlagDefinition;
3463
3464   unsigned LineNo = getLineNumber(Loc);
3465   unsigned ScopeLine = getLineNumber(ScopeLoc);
3466
3467   // FIXME: The function declaration we're constructing here is mostly reusing
3468   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3469   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3470   // all subprograms instead of the actual context since subprogram definitions
3471   // are emitted as CU level entities by the backend.
3472   llvm::DISubprogram *SP = DBuilder.createFunction(
3473       FDContext, Name, LinkageName, Unit, LineNo,
3474       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, FlagsForDef,
3475       SPFlagsForDef, TParamsArray.get(), getFunctionDeclaration(D));
3476   Fn->setSubprogram(SP);
3477   // We might get here with a VarDecl in the case we're generating
3478   // code for the initialization of globals. Do not record these decls
3479   // as they will overwrite the actual VarDecl Decl in the cache.
3480   if (HasDecl && isa<FunctionDecl>(D))
3481     DeclCache[D->getCanonicalDecl()].reset(SP);
3482
3483   if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
3484     // Starting with DWARF V5 method declarations are emitted as children of
3485     // the interface type.
3486     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
3487       const ObjCInterfaceDecl *ID = OMD->getClassInterface();
3488       QualType QTy(ID->getTypeForDecl(), 0);
3489       auto It = TypeCache.find(QTy.getAsOpaquePtr());
3490       if (It != TypeCache.end()) {
3491         llvm::DICompositeType *InterfaceDecl =
3492             cast<llvm::DICompositeType>(It->second);
3493         llvm::DISubprogram *FD = DBuilder.createFunction(
3494             InterfaceDecl, Name, LinkageName, Unit, LineNo,
3495             getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3496             TParamsArray.get());
3497         DBuilder.finalizeSubprogram(FD);
3498         ObjCMethodCache[ID].push_back(FD);
3499       }
3500     }
3501   }
3502
3503   // Push the function onto the lexical block stack.
3504   LexicalBlockStack.emplace_back(SP);
3505
3506   if (HasDecl)
3507     RegionMap[D].reset(SP);
3508 }
3509
3510 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3511                                    QualType FnType) {
3512   StringRef Name;
3513   StringRef LinkageName;
3514
3515   const Decl *D = GD.getDecl();
3516   if (!D)
3517     return;
3518
3519   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3520   llvm::DIFile *Unit = getOrCreateFile(Loc);
3521   llvm::DIScope *FDContext = getDeclContextDescriptor(D);
3522   llvm::DINodeArray TParamsArray;
3523   if (isa<FunctionDecl>(D)) {
3524     // If there is a DISubprogram for this function available then use it.
3525     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3526                              TParamsArray, Flags);
3527   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3528     Name = getObjCMethodName(OMD);
3529     Flags |= llvm::DINode::FlagPrototyped;
3530   } else {
3531     llvm_unreachable("not a function or ObjC method");
3532   }
3533   if (!Name.empty() && Name[0] == '\01')
3534     Name = Name.substr(1);
3535
3536   if (D->isImplicit()) {
3537     Flags |= llvm::DINode::FlagArtificial;
3538     // Artificial functions without a location should not silently reuse CurLoc.
3539     if (Loc.isInvalid())
3540       CurLoc = SourceLocation();
3541   }
3542   unsigned LineNo = getLineNumber(Loc);
3543   unsigned ScopeLine = 0;
3544   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3545   if (CGM.getLangOpts().Optimize)
3546     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3547
3548   DBuilder.retainType(DBuilder.createFunction(
3549       FDContext, Name, LinkageName, Unit, LineNo,
3550       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3551       TParamsArray.get(), getFunctionDeclaration(D)));
3552 }
3553
3554 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3555   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3556   // If there is a subprogram for this function available then use it.
3557   auto FI = SPCache.find(FD->getCanonicalDecl());
3558   llvm::DISubprogram *SP = nullptr;
3559   if (FI != SPCache.end())
3560     SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3561   if (!SP || !SP->isDefinition())
3562     SP = getFunctionStub(GD);
3563   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3564   LexicalBlockStack.emplace_back(SP);
3565   setInlinedAt(Builder.getCurrentDebugLocation());
3566   EmitLocation(Builder, FD->getLocation());
3567 }
3568
3569 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3570   assert(CurInlinedAt && "unbalanced inline scope stack");
3571   EmitFunctionEnd(Builder, nullptr);
3572   setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3573 }
3574
3575 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3576   // Update our current location
3577   setLocation(Loc);
3578
3579   if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
3580     return;
3581
3582   llvm::MDNode *Scope = LexicalBlockStack.back();
3583   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3584       getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3585 }
3586
3587 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3588   llvm::MDNode *Back = nullptr;
3589   if (!LexicalBlockStack.empty())
3590     Back = LexicalBlockStack.back().get();
3591   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3592       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3593       getColumnNumber(CurLoc)));
3594 }
3595
3596 void CGDebugInfo::AppendAddressSpaceXDeref(
3597     unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
3598   Optional<unsigned> DWARFAddressSpace =
3599       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3600   if (!DWARFAddressSpace)
3601     return;
3602
3603   Expr.push_back(llvm::dwarf::DW_OP_constu);
3604   Expr.push_back(DWARFAddressSpace.getValue());
3605   Expr.push_back(llvm::dwarf::DW_OP_swap);
3606   Expr.push_back(llvm::dwarf::DW_OP_xderef);
3607 }
3608
3609 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3610                                         SourceLocation Loc) {
3611   // Set our current location.
3612   setLocation(Loc);
3613
3614   // Emit a line table change for the current location inside the new scope.
3615   Builder.SetCurrentDebugLocation(
3616       llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3617                           LexicalBlockStack.back(), CurInlinedAt));
3618
3619   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3620     return;
3621
3622   // Create a new lexical block and push it on the stack.
3623   CreateLexicalBlock(Loc);
3624 }
3625
3626 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3627                                       SourceLocation Loc) {
3628   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3629
3630   // Provide an entry in the line table for the end of the block.
3631   EmitLocation(Builder, Loc);
3632
3633   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3634     return;
3635
3636   LexicalBlockStack.pop_back();
3637 }
3638
3639 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3640   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3641   unsigned RCount = FnBeginRegionCount.back();
3642   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3643
3644   // Pop all regions for this function.
3645   while (LexicalBlockStack.size() != RCount) {
3646     // Provide an entry in the line table for the end of the block.
3647     EmitLocation(Builder, CurLoc);
3648     LexicalBlockStack.pop_back();
3649   }
3650   FnBeginRegionCount.pop_back();
3651
3652   if (Fn && Fn->getSubprogram())
3653     DBuilder.finalizeSubprogram(Fn->getSubprogram());
3654 }
3655
3656 CGDebugInfo::BlockByRefType
3657 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3658                                           uint64_t *XOffset) {
3659   SmallVector<llvm::Metadata *, 5> EltTys;
3660   QualType FType;
3661   uint64_t FieldSize, FieldOffset;
3662   uint32_t FieldAlign;
3663
3664   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3665   QualType Type = VD->getType();
3666
3667   FieldOffset = 0;
3668   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3669   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3670   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3671   FType = CGM.getContext().IntTy;
3672   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3673   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3674
3675   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3676   if (HasCopyAndDispose) {
3677     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3678     EltTys.push_back(
3679         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3680     EltTys.push_back(
3681         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3682   }
3683   bool HasByrefExtendedLayout;
3684   Qualifiers::ObjCLifetime Lifetime;
3685   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3686                                         HasByrefExtendedLayout) &&
3687       HasByrefExtendedLayout) {
3688     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3689     EltTys.push_back(
3690         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3691   }
3692
3693   CharUnits Align = CGM.getContext().getDeclAlign(VD);
3694   if (Align > CGM.getContext().toCharUnitsFromBits(
3695                   CGM.getTarget().getPointerAlign(0))) {
3696     CharUnits FieldOffsetInBytes =
3697         CGM.getContext().toCharUnitsFromBits(FieldOffset);
3698     CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3699     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3700
3701     if (NumPaddingBytes.isPositive()) {
3702       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3703       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3704                                                     pad, ArrayType::Normal, 0);
3705       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3706     }
3707   }
3708
3709   FType = Type;
3710   llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
3711   FieldSize = CGM.getContext().getTypeSize(FType);
3712   FieldAlign = CGM.getContext().toBits(Align);
3713
3714   *XOffset = FieldOffset;
3715   llvm::DIType *FieldTy = DBuilder.createMemberType(
3716       Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
3717       llvm::DINode::FlagZero, WrappedTy);
3718   EltTys.push_back(FieldTy);
3719   FieldOffset += FieldSize;
3720
3721   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3722   return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
3723                                     llvm::DINode::FlagZero, nullptr, Elements),
3724           WrappedTy};
3725 }
3726
3727 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
3728                                                 llvm::Value *Storage,
3729                                                 llvm::Optional<unsigned> ArgNo,
3730                                                 CGBuilderTy &Builder) {
3731   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3732   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3733   if (VD->hasAttr<NoDebugAttr>())
3734     return nullptr;
3735
3736   bool Unwritten =
3737       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3738                            cast<Decl>(VD->getDeclContext())->isImplicit());
3739   llvm::DIFile *Unit = nullptr;
3740   if (!Unwritten)
3741     Unit = getOrCreateFile(VD->getLocation());
3742   llvm::DIType *Ty;
3743   uint64_t XOffset = 0;
3744   if (VD->hasAttr<BlocksAttr>())
3745     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
3746   else
3747     Ty = getOrCreateType(VD->getType(), Unit);
3748
3749   // If there is no debug info for this type then do not emit debug info
3750   // for this variable.
3751   if (!Ty)
3752     return nullptr;
3753
3754   // Get location information.
3755   unsigned Line = 0;
3756   unsigned Column = 0;
3757   if (!Unwritten) {
3758     Line = getLineNumber(VD->getLocation());
3759     Column = getColumnNumber(VD->getLocation());
3760   }
3761   SmallVector<int64_t, 13> Expr;
3762   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3763   if (VD->isImplicit())
3764     Flags |= llvm::DINode::FlagArtificial;
3765
3766   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3767
3768   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
3769   AppendAddressSpaceXDeref(AddressSpace, Expr);
3770
3771   // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
3772   // object pointer flag.
3773   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
3774     if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
3775         IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3776       Flags |= llvm::DINode::FlagObjectPointer;
3777   }
3778
3779   // Note: Older versions of clang used to emit byval references with an extra
3780   // DW_OP_deref, because they referenced the IR arg directly instead of
3781   // referencing an alloca. Newer versions of LLVM don't treat allocas
3782   // differently from other function arguments when used in a dbg.declare.
3783   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
3784   StringRef Name = VD->getName();
3785   if (!Name.empty()) {
3786     if (VD->hasAttr<BlocksAttr>()) {
3787       // Here, we need an offset *into* the alloca.
3788       CharUnits offset = CharUnits::fromQuantity(32);
3789       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3790       // offset of __forwarding field
3791       offset = CGM.getContext().toCharUnitsFromBits(
3792           CGM.getTarget().getPointerWidth(0));
3793       Expr.push_back(offset.getQuantity());
3794       Expr.push_back(llvm::dwarf::DW_OP_deref);
3795       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3796       // offset of x field
3797       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3798       Expr.push_back(offset.getQuantity());
3799     }
3800   } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
3801     // If VD is an anonymous union then Storage represents value for
3802     // all union fields.
3803     const RecordDecl *RD = RT->getDecl();
3804     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
3805       // GDB has trouble finding local variables in anonymous unions, so we emit
3806       // artificial local variables for each of the members.
3807       //
3808       // FIXME: Remove this code as soon as GDB supports this.
3809       // The debug info verifier in LLVM operates based on the assumption that a
3810       // variable has the same size as its storage and we had to disable the
3811       // check for artificial variables.
3812       for (const auto *Field : RD->fields()) {
3813         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3814         StringRef FieldName = Field->getName();
3815
3816         // Ignore unnamed fields. Do not ignore unnamed records.
3817         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3818           continue;
3819
3820         // Use VarDecl's Tag, Scope and Line number.
3821         auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
3822         auto *D = DBuilder.createAutoVariable(
3823             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3824             Flags | llvm::DINode::FlagArtificial, FieldAlign);
3825
3826         // Insert an llvm.dbg.declare into the current block.
3827         DBuilder.insertDeclare(
3828             Storage, D, DBuilder.createExpression(Expr),
3829             llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3830             Builder.GetInsertBlock());
3831       }
3832     }
3833   }
3834
3835   // Create the descriptor for the variable.
3836   auto *D = ArgNo ? DBuilder.createParameterVariable(
3837                         Scope, Name, *ArgNo, Unit, Line, Ty,
3838                         CGM.getLangOpts().Optimize, Flags)
3839                   : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3840                                                 CGM.getLangOpts().Optimize,
3841                                                 Flags, Align);
3842
3843   // Insert an llvm.dbg.declare into the current block.
3844   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3845                          llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3846                          Builder.GetInsertBlock());
3847
3848   return D;
3849 }
3850
3851 llvm::DILocalVariable *
3852 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
3853                                        CGBuilderTy &Builder) {
3854   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3855   return EmitDeclare(VD, Storage, llvm::None, Builder);
3856 }
3857
3858 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3859                                           llvm::DIType *Ty) {
3860   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3861   if (CachedTy)
3862     Ty = CachedTy;
3863   return DBuilder.createObjectPointerType(Ty);
3864 }
3865
3866 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3867     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3868     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3869   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3870   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3871
3872   if (Builder.GetInsertBlock() == nullptr)
3873     return;
3874   if (VD->hasAttr<NoDebugAttr>())
3875     return;
3876
3877   bool isByRef = VD->hasAttr<BlocksAttr>();
3878
3879   uint64_t XOffset = 0;
3880   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3881   llvm::DIType *Ty;
3882   if (isByRef)
3883     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
3884   else
3885     Ty = getOrCreateType(VD->getType(), Unit);
3886
3887   // Self is passed along as an implicit non-arg variable in a
3888   // block. Mark it as the object pointer.
3889   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
3890     if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3891       Ty = CreateSelfType(VD->getType(), Ty);
3892
3893   // Get location information.
3894   unsigned Line = getLineNumber(VD->getLocation());
3895   unsigned Column = getColumnNumber(VD->getLocation());
3896
3897   const llvm::DataLayout &target = CGM.getDataLayout();
3898
3899   CharUnits offset = CharUnits::fromQuantity(
3900       target.getStructLayout(blockInfo.StructureType)
3901           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3902
3903   SmallVector<int64_t, 9> addr;
3904   addr.push_back(llvm::dwarf::DW_OP_deref);
3905   addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3906   addr.push_back(offset.getQuantity());
3907   if (isByRef) {
3908     addr.push_back(llvm::dwarf::DW_OP_deref);
3909     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3910     // offset of __forwarding field
3911     offset =
3912         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3913     addr.push_back(offset.getQuantity());
3914     addr.push_back(llvm::dwarf::DW_OP_deref);
3915     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3916     // offset of x field
3917     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3918     addr.push_back(offset.getQuantity());
3919   }
3920
3921   // Create the descriptor for the variable.
3922   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3923   auto *D = DBuilder.createAutoVariable(
3924       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3925       Line, Ty, false, llvm::DINode::FlagZero, Align);
3926
3927   // Insert an llvm.dbg.declare into the current block.
3928   auto DL =
3929       llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
3930   auto *Expr = DBuilder.createExpression(addr);
3931   if (InsertPoint)
3932     DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
3933   else
3934     DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
3935 }
3936
3937 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3938                                            unsigned ArgNo,
3939                                            CGBuilderTy &Builder) {
3940   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3941   EmitDeclare(VD, AI, ArgNo, Builder);
3942 }
3943
3944 namespace {
3945 struct BlockLayoutChunk {
3946   uint64_t OffsetInBits;
3947   const BlockDecl::Capture *Capture;
3948 };
3949 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3950   return l.OffsetInBits < r.OffsetInBits;
3951 }
3952 } // namespace
3953
3954 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
3955     const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
3956     const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
3957     SmallVectorImpl<llvm::Metadata *> &Fields) {
3958   // Blocks in OpenCL have unique constraints which make the standard fields
3959   // redundant while requiring size and align fields for enqueue_kernel. See
3960   // initializeForBlockHeader in CGBlocks.cpp
3961   if (CGM.getLangOpts().OpenCL) {
3962     Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
3963                                      BlockLayout.getElementOffsetInBits(0),
3964                                      Unit, Unit));
3965     Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
3966                                      BlockLayout.getElementOffsetInBits(1),
3967                                      Unit, Unit));
3968   } else {
3969     Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
3970                                      BlockLayout.getElementOffsetInBits(0),
3971                                      Unit, Unit));
3972     Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
3973                                      BlockLayout.getElementOffsetInBits(1),
3974                                      Unit, Unit));
3975     Fields.push_back(
3976         createFieldType("__reserved", Context.IntTy, Loc, AS_public,
3977                         BlockLayout.getElementOffsetInBits(2), Unit, Unit));
3978     auto *FnTy = Block.getBlockExpr()->getFunctionType();
3979     auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3980     Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
3981                                      BlockLayout.getElementOffsetInBits(3),
3982                                      Unit, Unit));
3983     Fields.push_back(createFieldType(
3984         "__descriptor",
3985         Context.getPointerType(Block.NeedsCopyDispose
3986                                    ? Context.getBlockDescriptorExtendedType()
3987                                    : Context.getBlockDescriptorType()),
3988         Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
3989   }
3990 }
3991
3992 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3993                                                        StringRef Name,
3994                                                        unsigned ArgNo,
3995                                                        llvm::AllocaInst *Alloca,
3996                                                        CGBuilderTy &Builder) {
3997   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3998   ASTContext &C = CGM.getContext();
3999   const BlockDecl *blockDecl = block.getBlockDecl();
4000
4001   // Collect some general information about the block's location.
4002   SourceLocation loc = blockDecl->getCaretLocation();
4003   llvm::DIFile *tunit = getOrCreateFile(loc);
4004   unsigned line = getLineNumber(loc);
4005   unsigned column = getColumnNumber(loc);
4006
4007   // Build the debug-info type for the block literal.
4008   getDeclContextDescriptor(blockDecl);
4009
4010   const llvm::StructLayout *blockLayout =
4011       CGM.getDataLayout().getStructLayout(block.StructureType);
4012
4013   SmallVector<llvm::Metadata *, 16> fields;
4014   collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4015                                              fields);
4016
4017   // We want to sort the captures by offset, not because DWARF
4018   // requires this, but because we're paranoid about debuggers.
4019   SmallVector<BlockLayoutChunk, 8> chunks;
4020
4021   // 'this' capture.
4022   if (blockDecl->capturesCXXThis()) {
4023     BlockLayoutChunk chunk;
4024     chunk.OffsetInBits =
4025         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4026     chunk.Capture = nullptr;
4027     chunks.push_back(chunk);
4028   }
4029
4030   // Variable captures.
4031   for (const auto &capture : blockDecl->captures()) {
4032     const VarDecl *variable = capture.getVariable();
4033     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4034
4035     // Ignore constant captures.
4036     if (captureInfo.isConstant())
4037       continue;
4038
4039     BlockLayoutChunk chunk;
4040     chunk.OffsetInBits =
4041         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4042     chunk.Capture = &capture;
4043     chunks.push_back(chunk);
4044   }
4045
4046   // Sort by offset.
4047   llvm::array_pod_sort(chunks.begin(), chunks.end());
4048
4049   for (const BlockLayoutChunk &Chunk : chunks) {
4050     uint64_t offsetInBits = Chunk.OffsetInBits;
4051     const BlockDecl::Capture *capture = Chunk.Capture;
4052
4053     // If we have a null capture, this must be the C++ 'this' capture.
4054     if (!capture) {
4055       QualType type;
4056       if (auto *Method =
4057               cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4058         type = Method->getThisType();
4059       else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4060         type = QualType(RDecl->getTypeForDecl(), 0);
4061       else
4062         llvm_unreachable("unexpected block declcontext");
4063
4064       fields.push_back(createFieldType("this", type, loc, AS_public,
4065                                        offsetInBits, tunit, tunit));
4066       continue;
4067     }
4068
4069     const VarDecl *variable = capture->getVariable();
4070     StringRef name = variable->getName();
4071
4072     llvm::DIType *fieldType;
4073     if (capture->isByRef()) {
4074       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4075       auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4076       // FIXME: This recomputes the layout of the BlockByRefWrapper.
4077       uint64_t xoffset;
4078       fieldType =
4079           EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4080       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4081       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4082                                             PtrInfo.Width, Align, offsetInBits,
4083                                             llvm::DINode::FlagZero, fieldType);
4084     } else {
4085       auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4086       fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4087                                   offsetInBits, Align, tunit, tunit);
4088     }
4089     fields.push_back(fieldType);
4090   }
4091
4092   SmallString<36> typeName;
4093   llvm::raw_svector_ostream(typeName)
4094       << "__block_literal_" << CGM.getUniqueBlockCount();
4095
4096   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4097
4098   llvm::DIType *type =
4099       DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4100                                 CGM.getContext().toBits(block.BlockSize), 0,
4101                                 llvm::DINode::FlagZero, nullptr, fieldsArray);
4102   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4103
4104   // Get overall information about the block.
4105   llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4106   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4107
4108   // Create the descriptor for the parameter.
4109   auto *debugVar = DBuilder.createParameterVariable(
4110       scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4111
4112   // Insert an llvm.dbg.declare into the current block.
4113   DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4114                          llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
4115                          Builder.GetInsertBlock());
4116 }
4117
4118 llvm::DIDerivedType *
4119 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4120   if (!D->isStaticDataMember())
4121     return nullptr;
4122
4123   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4124   if (MI != StaticDataMemberCache.end()) {
4125     assert(MI->second && "Static data member declaration should still exist");
4126     return MI->second;
4127   }
4128
4129   // If the member wasn't found in the cache, lazily construct and add it to the
4130   // type (used when a limited form of the type is emitted).
4131   auto DC = D->getDeclContext();
4132   auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4133   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4134 }
4135
4136 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4137     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4138     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4139   llvm::DIGlobalVariableExpression *GVE = nullptr;
4140
4141   for (const auto *Field : RD->fields()) {
4142     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4143     StringRef FieldName = Field->getName();
4144
4145     // Ignore unnamed fields, but recurse into anonymous records.
4146     if (FieldName.empty()) {
4147       if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4148         GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4149                                      Var, DContext);
4150       continue;
4151     }
4152     // Use VarDecl's Tag, Scope and Line number.
4153     GVE = DBuilder.createGlobalVariableExpression(
4154         DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4155         Var->hasLocalLinkage());
4156     Var->addDebugInfo(GVE);
4157   }
4158   return GVE;
4159 }
4160
4161 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4162                                      const VarDecl *D) {
4163   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
4164   if (D->hasAttr<NoDebugAttr>())
4165     return;
4166
4167   // If we already created a DIGlobalVariable for this declaration, just attach
4168   // it to the llvm::GlobalVariable.
4169   auto Cached = DeclCache.find(D->getCanonicalDecl());
4170   if (Cached != DeclCache.end())
4171     return Var->addDebugInfo(
4172         cast<llvm::DIGlobalVariableExpression>(Cached->second));
4173
4174   // Create global variable debug descriptor.
4175   llvm::DIFile *Unit = nullptr;
4176   llvm::DIScope *DContext = nullptr;
4177   unsigned LineNo;
4178   StringRef DeclName, LinkageName;
4179   QualType T;
4180   llvm::MDTuple *TemplateParameters = nullptr;
4181   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4182                       TemplateParameters, DContext);
4183
4184   // Attempt to store one global variable for the declaration - even if we
4185   // emit a lot of fields.
4186   llvm::DIGlobalVariableExpression *GVE = nullptr;
4187
4188   // If this is an anonymous union then we'll want to emit a global
4189   // variable for each member of the anonymous union so that it's possible
4190   // to find the name of any field in the union.
4191   if (T->isUnionType() && DeclName.empty()) {
4192     const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4193     assert(RD->isAnonymousStructOrUnion() &&
4194            "unnamed non-anonymous struct or union?");
4195     GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4196   } else {
4197     auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4198
4199     SmallVector<int64_t, 4> Expr;
4200     unsigned AddressSpace =
4201         CGM.getContext().getTargetAddressSpace(D->getType());
4202     AppendAddressSpaceXDeref(AddressSpace, Expr);
4203
4204     GVE = DBuilder.createGlobalVariableExpression(
4205         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4206         Var->hasLocalLinkage(),
4207         Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4208         getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4209         Align);
4210     Var->addDebugInfo(GVE);
4211   }
4212   DeclCache[D->getCanonicalDecl()].reset(GVE);
4213 }
4214
4215 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4216   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
4217   if (VD->hasAttr<NoDebugAttr>())
4218     return;
4219   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4220   // Create the descriptor for the variable.
4221   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4222   StringRef Name = VD->getName();
4223   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4224   if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4225     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4226     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4227     Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4228   }
4229   // Do not use global variables for enums.
4230   //
4231   // FIXME: why not?
4232   if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
4233     return;
4234   // Do not emit separate definitions for function local const/statics.
4235   if (isa<FunctionDecl>(VD->getDeclContext()))
4236     return;
4237   VD = cast<ValueDecl>(VD->getCanonicalDecl());
4238   auto *VarD = cast<VarDecl>(VD);
4239   if (VarD->isStaticDataMember()) {
4240     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4241     getDeclContextDescriptor(VarD);
4242     // Ensure that the type is retained even though it's otherwise unreferenced.
4243     //
4244     // FIXME: This is probably unnecessary, since Ty should reference RD
4245     // through its scope.
4246     RetainedTypes.push_back(
4247         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4248     return;
4249   }
4250
4251   llvm::DIScope *DContext = getDeclContextDescriptor(VD);
4252
4253   auto &GV = DeclCache[VD];
4254   if (GV)
4255     return;
4256   llvm::DIExpression *InitExpr = nullptr;
4257   if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4258     // FIXME: Add a representation for integer constants wider than 64 bits.
4259     if (Init.isInt())
4260       InitExpr =
4261           DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4262     else if (Init.isFloat())
4263       InitExpr = DBuilder.createConstantValueExpression(
4264           Init.getFloat().bitcastToAPInt().getZExtValue());
4265   }
4266
4267   llvm::MDTuple *TemplateParameters = nullptr;
4268
4269   if (isa<VarTemplateSpecializationDecl>(VD))
4270     if (VarD) {
4271       llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4272       TemplateParameters = parameterNodes.get();
4273     }
4274
4275   GV.reset(DBuilder.createGlobalVariableExpression(
4276       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4277       true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4278       TemplateParameters, Align));
4279 }
4280
4281 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4282   if (!LexicalBlockStack.empty())
4283     return LexicalBlockStack.back();
4284   llvm::DIScope *Mod = getParentModuleOrNull(D);
4285   return getContextDescriptor(D, Mod ? Mod : TheCU);
4286 }
4287
4288 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4289   if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4290     return;
4291   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4292   if (!NSDecl->isAnonymousNamespace() ||
4293       CGM.getCodeGenOpts().DebugExplicitImport) {
4294     auto Loc = UD.getLocation();
4295     DBuilder.createImportedModule(
4296         getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4297         getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4298   }
4299 }
4300
4301 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4302   if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4303     return;
4304   assert(UD.shadow_size() &&
4305          "We shouldn't be codegening an invalid UsingDecl containing no decls");
4306   // Emitting one decl is sufficient - debuggers can detect that this is an
4307   // overloaded name & provide lookup for all the overloads.
4308   const UsingShadowDecl &USD = **UD.shadow_begin();
4309
4310   // FIXME: Skip functions with undeduced auto return type for now since we
4311   // don't currently have the plumbing for separate declarations & definitions
4312   // of free functions and mismatched types (auto in the declaration, concrete
4313   // return type in the definition)
4314   if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4315     if (const auto *AT =
4316             FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
4317       if (AT->getDeducedType().isNull())
4318         return;
4319   if (llvm::DINode *Target =
4320           getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4321     auto Loc = USD.getLocation();
4322     DBuilder.createImportedDeclaration(
4323         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4324         getOrCreateFile(Loc), getLineNumber(Loc));
4325   }
4326 }
4327
4328 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4329   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4330     return;
4331   if (Module *M = ID.getImportedModule()) {
4332     auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
4333     auto Loc = ID.getLocation();
4334     DBuilder.createImportedDeclaration(
4335         getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4336         getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4337         getLineNumber(Loc));
4338   }
4339 }
4340
4341 llvm::DIImportedEntity *
4342 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4343   if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4344     return nullptr;
4345   auto &VH = NamespaceAliasCache[&NA];
4346   if (VH)
4347     return cast<llvm::DIImportedEntity>(VH);
4348   llvm::DIImportedEntity *R;
4349   auto Loc = NA.getLocation();
4350   if (const auto *Underlying =
4351           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4352     // This could cache & dedup here rather than relying on metadata deduping.
4353     R = DBuilder.createImportedDeclaration(
4354         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4355         EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4356         getLineNumber(Loc), NA.getName());
4357   else
4358     R = DBuilder.createImportedDeclaration(
4359         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4360         getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4361         getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4362   VH.reset(R);
4363   return R;
4364 }
4365
4366 llvm::DINamespace *
4367 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4368   // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4369   // if necessary, and this way multiple declarations of the same namespace in
4370   // different parent modules stay distinct.
4371   auto I = NamespaceCache.find(NSDecl);
4372   if (I != NamespaceCache.end())
4373     return cast<llvm::DINamespace>(I->second);
4374
4375   llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4376   // Don't trust the context if it is a DIModule (see comment above).
4377   llvm::DINamespace *NS =
4378       DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4379   NamespaceCache[NSDecl].reset(NS);
4380   return NS;
4381 }
4382
4383 void CGDebugInfo::setDwoId(uint64_t Signature) {
4384   assert(TheCU && "no main compile unit");
4385   TheCU->setDWOId(Signature);
4386 }
4387
4388 void CGDebugInfo::finalize() {
4389   // Creating types might create further types - invalidating the current
4390   // element and the size(), so don't cache/reference them.
4391   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4392     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4393     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4394                            ? CreateTypeDefinition(E.Type, E.Unit)
4395                            : E.Decl;
4396     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4397   }
4398
4399   if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
4400     // Add methods to interface.
4401     for (const auto &P : ObjCMethodCache) {
4402       if (P.second.empty())
4403         continue;
4404
4405       QualType QTy(P.first->getTypeForDecl(), 0);
4406       auto It = TypeCache.find(QTy.getAsOpaquePtr());
4407       assert(It != TypeCache.end());
4408
4409       llvm::DICompositeType *InterfaceDecl =
4410           cast<llvm::DICompositeType>(It->second);
4411
4412       SmallVector<llvm::Metadata *, 16> EltTys;
4413       auto CurrenetElts = InterfaceDecl->getElements();
4414       EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
4415       for (auto &MD : P.second)
4416         EltTys.push_back(MD);
4417       llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4418       DBuilder.replaceArrays(InterfaceDecl, Elements);
4419     }
4420   }
4421
4422   for (const auto &P : ReplaceMap) {
4423     assert(P.second);
4424     auto *Ty = cast<llvm::DIType>(P.second);
4425     assert(Ty->isForwardDecl());
4426
4427     auto It = TypeCache.find(P.first);
4428     assert(It != TypeCache.end());
4429     assert(It->second);
4430
4431     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4432                               cast<llvm::DIType>(It->second));
4433   }
4434
4435   for (const auto &P : FwdDeclReplaceMap) {
4436     assert(P.second);
4437     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4438     llvm::Metadata *Repl;
4439
4440     auto It = DeclCache.find(P.first);
4441     // If there has been no definition for the declaration, call RAUW
4442     // with ourselves, that will destroy the temporary MDNode and
4443     // replace it with a standard one, avoiding leaking memory.
4444     if (It == DeclCache.end())
4445       Repl = P.second;
4446     else
4447       Repl = It->second;
4448
4449     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4450       Repl = GVE->getVariable();
4451     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4452   }
4453
4454   // We keep our own list of retained types, because we need to look
4455   // up the final type in the type cache.
4456   for (auto &RT : RetainedTypes)
4457     if (auto MD = TypeCache[RT])
4458       DBuilder.retainType(cast<llvm::DIType>(MD));
4459
4460   DBuilder.finalize();
4461 }
4462
4463 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4464   if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4465     return;
4466
4467   if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
4468     // Don't ignore in case of explicit cast where it is referenced indirectly.
4469     DBuilder.retainType(DieTy);
4470 }
4471
4472 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4473   if (LexicalBlockStack.empty())
4474     return llvm::DebugLoc();
4475
4476   llvm::MDNode *Scope = LexicalBlockStack.back();
4477   return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
4478 }
4479
4480 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4481   // Call site-related attributes are only useful in optimized programs, and
4482   // when there's a possibility of debugging backtraces.
4483   if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4484       DebugKind == codegenoptions::LocTrackingOnly)
4485     return llvm::DINode::FlagZero;
4486
4487   // Call site-related attributes are available in DWARF v5. Some debuggers,
4488   // while not fully DWARF v5-compliant, may accept these attributes as if they
4489   // were part of DWARF v4.
4490   bool SupportsDWARFv4Ext =
4491       CGM.getCodeGenOpts().DwarfVersion == 4 &&
4492       CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB;
4493   if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
4494     return llvm::DINode::FlagZero;
4495
4496   return llvm::DINode::FlagAllCallsDescribed;
4497 }