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