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