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