LLVM  14.0.0git
CodeViewDebug.cpp
Go to the documentation of this file.
1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
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 file contains support for writing Microsoft CodeView debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeViewDebug.h"
14 #include "DwarfExpression.h"
15 #include "llvm/ADT/APSInt.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/COFF.h"
36 #include "llvm/Config/llvm-config.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GlobalValue.h"
53 #include "llvm/IR/GlobalVariable.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Module.h"
56 #include "llvm/MC/MCAsmInfo.h"
57 #include "llvm/MC/MCContext.h"
58 #include "llvm/MC/MCSectionCOFF.h"
59 #include "llvm/MC/MCStreamer.h"
60 #include "llvm/MC/MCSymbol.h"
64 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/Endian.h"
67 #include "llvm/Support/Error.h"
70 #include "llvm/Support/Path.h"
71 #include "llvm/Support/Program.h"
72 #include "llvm/Support/SMLoc.h"
76 #include <algorithm>
77 #include <cassert>
78 #include <cctype>
79 #include <cstddef>
80 #include <iterator>
81 #include <limits>
82 
83 using namespace llvm;
84 using namespace llvm::codeview;
85 
86 namespace {
87 class CVMCAdapter : public CodeViewRecordStreamer {
88 public:
89  CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
90  : OS(&OS), TypeTable(TypeTable) {}
91 
92  void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
93 
94  void emitIntValue(uint64_t Value, unsigned Size) override {
95  OS->emitIntValueInHex(Value, Size);
96  }
97 
98  void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
99 
100  void AddComment(const Twine &T) override { OS->AddComment(T); }
101 
102  void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
103 
104  bool isVerboseAsm() override { return OS->isVerboseAsm(); }
105 
106  std::string getTypeName(TypeIndex TI) override {
107  std::string TypeName;
108  if (!TI.isNoneType()) {
109  if (TI.isSimple())
110  TypeName = std::string(TypeIndex::simpleTypeName(TI));
111  else
112  TypeName = std::string(TypeTable.getTypeName(TI));
113  }
114  return TypeName;
115  }
116 
117 private:
118  MCStreamer *OS = nullptr;
119  TypeCollection &TypeTable;
120 };
121 } // namespace
122 
124  switch (Type) {
126  return CPUType::Pentium3;
127  case Triple::ArchType::x86_64:
128  return CPUType::X64;
129  case Triple::ArchType::thumb:
130  // LLVM currently doesn't support Windows CE and so thumb
131  // here is indiscriminately mapped to ARMNT specifically.
132  return CPUType::ARMNT;
133  case Triple::ArchType::aarch64:
134  return CPUType::ARM64;
135  default:
136  report_fatal_error("target architecture doesn't map to a CodeView CPUType");
137  }
138 }
139 
141  : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
142 
143 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
144  std::string &Filepath = FileToFilepathMap[File];
145  if (!Filepath.empty())
146  return Filepath;
147 
148  StringRef Dir = File->getDirectory(), Filename = File->getFilename();
149 
150  // If this is a Unix-style path, just use it as is. Don't try to canonicalize
151  // it textually because one of the path components could be a symlink.
152  if (Dir.startswith("/") || Filename.startswith("/")) {
154  return Filename;
155  Filepath = std::string(Dir);
156  if (Dir.back() != '/')
157  Filepath += '/';
158  Filepath += Filename;
159  return Filepath;
160  }
161 
162  // Clang emits directory and relative filename info into the IR, but CodeView
163  // operates on full paths. We could change Clang to emit full paths too, but
164  // that would increase the IR size and probably not needed for other users.
165  // For now, just concatenate and canonicalize the path here.
166  if (Filename.find(':') == 1)
167  Filepath = std::string(Filename);
168  else
169  Filepath = (Dir + "\\" + Filename).str();
170 
171  // Canonicalize the path. We have to do it textually because we may no longer
172  // have access the file in the filesystem.
173  // First, replace all slashes with backslashes.
174  std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
175 
176  // Remove all "\.\" with "\".
177  size_t Cursor = 0;
178  while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
179  Filepath.erase(Cursor, 2);
180 
181  // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
182  // path should be well-formatted, e.g. start with a drive letter, etc.
183  Cursor = 0;
184  while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
185  // Something's wrong if the path starts with "\..\", abort.
186  if (Cursor == 0)
187  break;
188 
189  size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
190  if (PrevSlash == std::string::npos)
191  // Something's wrong, abort.
192  break;
193 
194  Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
195  // The next ".." might be following the one we've just erased.
196  Cursor = PrevSlash;
197  }
198 
199  // Remove all duplicate backslashes.
200  Cursor = 0;
201  while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
202  Filepath.erase(Cursor, 1);
203 
204  return Filepath;
205 }
206 
207 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
208  StringRef FullPath = getFullFilepath(F);
209  unsigned NextId = FileIdMap.size() + 1;
210  auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
211  if (Insertion.second) {
212  // We have to compute the full filepath and emit a .cv_file directive.
213  ArrayRef<uint8_t> ChecksumAsBytes;
215  if (F->getChecksum()) {
216  std::string Checksum = fromHex(F->getChecksum()->Value);
217  void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
218  memcpy(CKMem, Checksum.data(), Checksum.size());
219  ChecksumAsBytes = ArrayRef<uint8_t>(
220  reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
221  switch (F->getChecksum()->Kind) {
222  case DIFile::CSK_MD5:
223  CSKind = FileChecksumKind::MD5;
224  break;
225  case DIFile::CSK_SHA1:
226  CSKind = FileChecksumKind::SHA1;
227  break;
228  case DIFile::CSK_SHA256:
229  CSKind = FileChecksumKind::SHA256;
230  break;
231  }
232  }
233  bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
234  static_cast<unsigned>(CSKind));
235  (void)Success;
236  assert(Success && ".cv_file directive failed");
237  }
238  return Insertion.first->second;
239 }
240 
242 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
243  const DISubprogram *Inlinee) {
244  auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
245  InlineSite *Site = &SiteInsertion.first->second;
246  if (SiteInsertion.second) {
247  unsigned ParentFuncId = CurFn->FuncId;
248  if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
249  ParentFuncId =
250  getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
251  .SiteFuncId;
252 
253  Site->SiteFuncId = NextFuncId++;
255  Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
256  InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
257  Site->Inlinee = Inlinee;
258  InlinedSubprograms.insert(Inlinee);
259  getFuncIdForSubprogram(Inlinee);
260  }
261  return *Site;
262 }
263 
265  StringRef ScopeName = Scope->getName();
266  if (!ScopeName.empty())
267  return ScopeName;
268 
269  switch (Scope->getTag()) {
270  case dwarf::DW_TAG_enumeration_type:
271  case dwarf::DW_TAG_class_type:
272  case dwarf::DW_TAG_structure_type:
273  case dwarf::DW_TAG_union_type:
274  return "<unnamed-tag>";
275  case dwarf::DW_TAG_namespace:
276  return "`anonymous namespace'";
277  default:
278  return StringRef();
279  }
280 }
281 
282 const DISubprogram *CodeViewDebug::collectParentScopeNames(
283  const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
284  const DISubprogram *ClosestSubprogram = nullptr;
285  while (Scope != nullptr) {
286  if (ClosestSubprogram == nullptr)
287  ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
288 
289  // If a type appears in a scope chain, make sure it gets emitted. The
290  // frontend will be responsible for deciding if this should be a forward
291  // declaration or a complete type.
292  if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
293  DeferredCompleteTypes.push_back(Ty);
294 
295  StringRef ScopeName = getPrettyScopeName(Scope);
296  if (!ScopeName.empty())
297  QualifiedNameComponents.push_back(ScopeName);
298  Scope = Scope->getScope();
299  }
300  return ClosestSubprogram;
301 }
302 
303 static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
305  std::string FullyQualifiedName;
306  for (StringRef QualifiedNameComponent :
307  llvm::reverse(QualifiedNameComponents)) {
308  FullyQualifiedName.append(std::string(QualifiedNameComponent));
309  FullyQualifiedName.append("::");
310  }
311  FullyQualifiedName.append(std::string(TypeName));
312  return FullyQualifiedName;
313 }
314 
316  TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
318  // Don't decrement TypeEmissionLevel until after emitting deferred types, so
319  // inner TypeLoweringScopes don't attempt to emit deferred types.
320  if (CVD.TypeEmissionLevel == 1)
321  CVD.emitDeferredCompleteTypes();
322  --CVD.TypeEmissionLevel;
323  }
325 };
326 
327 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
328  StringRef Name) {
329  // Ensure types in the scope chain are emitted as soon as possible.
330  // This can create otherwise a situation where S_UDTs are emitted while
331  // looping in emitDebugInfoForUDTs.
332  TypeLoweringScope S(*this);
333  SmallVector<StringRef, 5> QualifiedNameComponents;
334  collectParentScopeNames(Scope, QualifiedNameComponents);
335  return formatNestedName(QualifiedNameComponents, Name);
336 }
337 
338 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
339  const DIScope *Scope = Ty->getScope();
340  return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
341 }
342 
343 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
344  // No scope means global scope and that uses the zero index.
345  //
346  // We also use zero index when the scope is a DISubprogram
347  // to suppress the emission of LF_STRING_ID for the function,
348  // which can trigger a link-time error with the linker in
349  // VS2019 version 16.11.2 or newer.
350  // Note, however, skipping the debug info emission for the DISubprogram
351  // is a temporary fix. The root issue here is that we need to figure out
352  // the proper way to encode a function nested in another function
353  // (as introduced by the Fortran 'contains' keyword) in CodeView.
354  if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
355  return TypeIndex();
356 
357  assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
358 
359  // Check if we've already translated this scope.
360  auto I = TypeIndices.find({Scope, nullptr});
361  if (I != TypeIndices.end())
362  return I->second;
363 
364  // Build the fully qualified name of the scope.
365  std::string ScopeName = getFullyQualifiedName(Scope);
366  StringIdRecord SID(TypeIndex(), ScopeName);
367  auto TI = TypeTable.writeLeafType(SID);
368  return recordTypeIndexForDINode(Scope, TI);
369 }
370 
372  // Remove template args from the display name. Assume that the template args
373  // are the last thing in the name.
374  if (Name.empty() || Name.back() != '>')
375  return Name;
376 
377  int OpenBrackets = 0;
378  for (int i = Name.size() - 1; i >= 0; --i) {
379  if (Name[i] == '>')
380  ++OpenBrackets;
381  else if (Name[i] == '<') {
382  --OpenBrackets;
383  if (OpenBrackets == 0)
384  return Name.substr(0, i);
385  }
386  }
387  return Name;
388 }
389 
390 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
391  assert(SP);
392 
393  // Check if we've already translated this subprogram.
394  auto I = TypeIndices.find({SP, nullptr});
395  if (I != TypeIndices.end())
396  return I->second;
397 
398  // The display name includes function template arguments. Drop them to match
399  // MSVC. We need to have the template arguments in the DISubprogram name
400  // because they are used in other symbol records, such as S_GPROC32_IDs.
401  StringRef DisplayName = removeTemplateArgs(SP->getName());
402 
403  const DIScope *Scope = SP->getScope();
404  TypeIndex TI;
405  if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
406  // If the scope is a DICompositeType, then this must be a method. Member
407  // function types take some special handling, and require access to the
408  // subprogram.
409  TypeIndex ClassType = getTypeIndex(Class);
410  MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
411  DisplayName);
412  TI = TypeTable.writeLeafType(MFuncId);
413  } else {
414  // Otherwise, this must be a free function.
415  TypeIndex ParentScope = getScopeIndex(Scope);
416  FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
417  TI = TypeTable.writeLeafType(FuncId);
418  }
419 
420  return recordTypeIndexForDINode(SP, TI);
421 }
422 
423 static bool isNonTrivial(const DICompositeType *DCTy) {
424  return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
425 }
426 
427 static FunctionOptions
429  const DICompositeType *ClassTy = nullptr,
430  StringRef SPName = StringRef("")) {
432  const DIType *ReturnTy = nullptr;
433  if (auto TypeArray = Ty->getTypeArray()) {
434  if (TypeArray.size())
435  ReturnTy = TypeArray[0];
436  }
437 
438  // Add CxxReturnUdt option to functions that return nontrivial record types
439  // or methods that return record types.
440  if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
441  if (isNonTrivial(ReturnDCTy) || ClassTy)
442  FO |= FunctionOptions::CxxReturnUdt;
443 
444  // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
445  if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
446  FO |= FunctionOptions::Constructor;
447 
448  // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
449 
450  }
451  return FO;
452 }
453 
454 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
455  const DICompositeType *Class) {
456  // Always use the method declaration as the key for the function type. The
457  // method declaration contains the this adjustment.
458  if (SP->getDeclaration())
459  SP = SP->getDeclaration();
460  assert(!SP->getDeclaration() && "should use declaration as key");
461 
462  // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
463  // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
464  auto I = TypeIndices.find({SP, Class});
465  if (I != TypeIndices.end())
466  return I->second;
467 
468  // Make sure complete type info for the class is emitted *after* the member
469  // function type, as the complete class type is likely to reference this
470  // member function type.
471  TypeLoweringScope S(*this);
472  const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
473 
474  FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
475  TypeIndex TI = lowerTypeMemberFunction(
476  SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
477  return recordTypeIndexForDINode(SP, TI, Class);
478 }
479 
480 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
481  TypeIndex TI,
482  const DIType *ClassTy) {
483  auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
484  (void)InsertResult;
485  assert(InsertResult.second && "DINode was already assigned a type index");
486  return TI;
487 }
488 
489 unsigned CodeViewDebug::getPointerSizeInBytes() {
490  return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
491 }
492 
493 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
494  const LexicalScope *LS) {
495  if (const DILocation *InlinedAt = LS->getInlinedAt()) {
496  // This variable was inlined. Associate it with the InlineSite.
497  const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
498  InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
499  Site.InlinedLocals.emplace_back(Var);
500  } else {
501  // This variable goes into the corresponding lexical scope.
502  ScopeVariables[LS].emplace_back(Var);
503  }
504 }
505 
507  const DILocation *Loc) {
508  if (!llvm::is_contained(Locs, Loc))
509  Locs.push_back(Loc);
510 }
511 
512 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
513  const MachineFunction *MF) {
514  // Skip this instruction if it has the same location as the previous one.
515  if (!DL || DL == PrevInstLoc)
516  return;
517 
518  const DIScope *Scope = DL.get()->getScope();
519  if (!Scope)
520  return;
521 
522  // Skip this line if it is longer than the maximum we can record.
523  LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
524  if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
525  LI.isNeverStepInto())
526  return;
527 
528  ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
529  if (CI.getStartColumn() != DL.getCol())
530  return;
531 
532  if (!CurFn->HaveLineInfo)
533  CurFn->HaveLineInfo = true;
534  unsigned FileId = 0;
535  if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
536  FileId = CurFn->LastFileId;
537  else
538  FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
539  PrevInstLoc = DL;
540 
541  unsigned FuncId = CurFn->FuncId;
542  if (const DILocation *SiteLoc = DL->getInlinedAt()) {
543  const DILocation *Loc = DL.get();
544 
545  // If this location was actually inlined from somewhere else, give it the ID
546  // of the inline call site.
547  FuncId =
548  getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
549 
550  // Ensure we have links in the tree of inline call sites.
551  bool FirstLoc = true;
552  while ((SiteLoc = Loc->getInlinedAt())) {
553  InlineSite &Site =
554  getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
555  if (!FirstLoc)
556  addLocIfNotPresent(Site.ChildSites, Loc);
557  FirstLoc = false;
558  Loc = SiteLoc;
559  }
560  addLocIfNotPresent(CurFn->ChildSites, Loc);
561  }
562 
563  OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
564  /*PrologueEnd=*/false, /*IsStmt=*/false,
565  DL->getFilename(), SMLoc());
566 }
567 
568 void CodeViewDebug::emitCodeViewMagicVersion() {
569  OS.emitValueToAlignment(4);
570  OS.AddComment("Debug section magic");
572 }
573 
574 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
575  switch (DWLang) {
576  case dwarf::DW_LANG_C:
577  case dwarf::DW_LANG_C89:
578  case dwarf::DW_LANG_C99:
579  case dwarf::DW_LANG_C11:
580  case dwarf::DW_LANG_ObjC:
581  return SourceLanguage::C;
582  case dwarf::DW_LANG_C_plus_plus:
583  case dwarf::DW_LANG_C_plus_plus_03:
584  case dwarf::DW_LANG_C_plus_plus_11:
585  case dwarf::DW_LANG_C_plus_plus_14:
586  return SourceLanguage::Cpp;
587  case dwarf::DW_LANG_Fortran77:
588  case dwarf::DW_LANG_Fortran90:
589  case dwarf::DW_LANG_Fortran95:
590  case dwarf::DW_LANG_Fortran03:
591  case dwarf::DW_LANG_Fortran08:
593  case dwarf::DW_LANG_Pascal83:
594  return SourceLanguage::Pascal;
595  case dwarf::DW_LANG_Cobol74:
596  case dwarf::DW_LANG_Cobol85:
597  return SourceLanguage::Cobol;
598  case dwarf::DW_LANG_Java:
599  return SourceLanguage::Java;
600  case dwarf::DW_LANG_D:
601  return SourceLanguage::D;
602  case dwarf::DW_LANG_Swift:
603  return SourceLanguage::Swift;
604  case dwarf::DW_LANG_Rust:
605  return SourceLanguage::Rust;
606  default:
607  // There's no CodeView representation for this language, and CV doesn't
608  // have an "unknown" option for the language field, so we'll use MASM,
609  // as it's very low level.
610  return SourceLanguage::Masm;
611  }
612 }
613 
615  // If module doesn't have named metadata anchors or COFF debug section
616  // is not available, skip any debug info related stuff.
617  NamedMDNode *CUs = M->getNamedMetadata("llvm.dbg.cu");
619  Asm = nullptr;
620  return;
621  }
622  // Tell MMI that we have and need debug info.
624 
625  TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
626 
627  // Get the current source language.
628  const MDNode *Node = *CUs->operands().begin();
629  const auto *CU = cast<DICompileUnit>(Node);
630 
631  CurrentSourceLanguage = MapDWLangToCVLang(CU->getSourceLanguage());
632 
633  collectGlobalVariableInfo();
634 
635  // Check if we should emit type record hashes.
636  ConstantInt *GH =
637  mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
638  EmitDebugGlobalHashes = GH && !GH->isZero();
639 }
640 
642  if (!Asm || !MMI->hasDebugInfo())
643  return;
644 
645  // The COFF .debug$S section consists of several subsections, each starting
646  // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
647  // of the payload followed by the payload itself. The subsections are 4-byte
648  // aligned.
649 
650  // Use the generic .debug$S section, and make a subsection for all the inlined
651  // subprograms.
652  switchToDebugSectionForSymbol(nullptr);
653 
654  MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
655  emitObjName();
656  emitCompilerInformation();
657  endCVSubsection(CompilerInfo);
658 
659  emitInlineeLinesSubsection();
660 
661  // Emit per-function debug information.
662  for (auto &P : FnDebugInfo)
663  if (!P.first->isDeclarationForLinker())
664  emitDebugInfoForFunction(P.first, *P.second);
665 
666  // Get types used by globals without emitting anything.
667  // This is meant to collect all static const data members so they can be
668  // emitted as globals.
669  collectDebugInfoForGlobals();
670 
671  // Emit retained types.
672  emitDebugInfoForRetainedTypes();
673 
674  // Emit global variable debug information.
675  setCurrentSubprogram(nullptr);
676  emitDebugInfoForGlobals();
677 
678  // Switch back to the generic .debug$S section after potentially processing
679  // comdat symbol sections.
680  switchToDebugSectionForSymbol(nullptr);
681 
682  // Emit UDT records for any types used by global variables.
683  if (!GlobalUDTs.empty()) {
684  MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
685  emitDebugInfoForUDTs(GlobalUDTs);
686  endCVSubsection(SymbolsEnd);
687  }
688 
689  // This subsection holds a file index to offset in string table table.
690  OS.AddComment("File index to string table offset subsection");
692 
693  // This subsection holds the string table.
694  OS.AddComment("String table");
696 
697  // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
698  // subsection in the generic .debug$S section at the end. There is no
699  // particular reason for this ordering other than to match MSVC.
700  emitBuildInfo();
701 
702  // Emit type information and hashes last, so that any types we translate while
703  // emitting function info are included.
704  emitTypeInformation();
705 
706  if (EmitDebugGlobalHashes)
707  emitTypeGlobalHashes();
708 
709  clear();
710 }
711 
712 static void
714  unsigned MaxFixedRecordLength = 0xF00) {
715  // The maximum CV record length is 0xFF00. Most of the strings we emit appear
716  // after a fixed length portion of the record. The fixed length portion should
717  // always be less than 0xF00 (3840) bytes, so truncate the string so that the
718  // overall record size is less than the maximum allowed.
719  SmallString<32> NullTerminatedString(
720  S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
721  NullTerminatedString.push_back('\0');
722  OS.emitBytes(NullTerminatedString);
723 }
724 
725 void CodeViewDebug::emitTypeInformation() {
726  if (TypeTable.empty())
727  return;
728 
729  // Start the .debug$T or .debug$P section with 0x4.
731  emitCodeViewMagicVersion();
732 
733  TypeTableCollection Table(TypeTable.records());
735 
736  // To emit type record using Codeview MCStreamer adapter
737  CVMCAdapter CVMCOS(OS, Table);
738  TypeRecordMapping typeMapping(CVMCOS);
739  Pipeline.addCallbackToPipeline(typeMapping);
740 
741  Optional<TypeIndex> B = Table.getFirst();
742  while (B) {
743  // This will fail if the record data is invalid.
744  CVType Record = Table.getType(*B);
745 
746  Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
747 
748  if (E) {
749  logAllUnhandledErrors(std::move(E), errs(), "error: ");
750  llvm_unreachable("produced malformed type record");
751  }
752 
753  B = Table.getNext(*B);
754  }
755 }
756 
757 void CodeViewDebug::emitTypeGlobalHashes() {
758  if (TypeTable.empty())
759  return;
760 
761  // Start the .debug$H section with the version and hash algorithm, currently
762  // hardcoded to version 0, SHA1.
764 
765  OS.emitValueToAlignment(4);
766  OS.AddComment("Magic");
768  OS.AddComment("Section Version");
769  OS.emitInt16(0);
770  OS.AddComment("Hash Algorithm");
771  OS.emitInt16(uint16_t(GlobalTypeHashAlg::SHA1_8));
772 
773  TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
774  for (const auto &GHR : TypeTable.hashes()) {
775  if (OS.isVerboseAsm()) {
776  // Emit an EOL-comment describing which TypeIndex this hash corresponds
777  // to, as well as the stringified SHA1 hash.
778  SmallString<32> Comment;
779  raw_svector_ostream CommentOS(Comment);
780  CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
781  OS.AddComment(Comment);
782  ++TI;
783  }
784  assert(GHR.Hash.size() == 8);
785  StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
786  GHR.Hash.size());
787  OS.emitBinaryData(S);
788  }
789 }
790 
791 void CodeViewDebug::emitObjName() {
792  MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
793 
795  llvm::SmallString<256> PathStore(PathRef);
796 
797  if (PathRef.empty() || PathRef == "-") {
798  // Don't emit the filename if we're writing to stdout or to /dev/null.
799  PathRef = {};
800  } else {
801  llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true);
802  PathRef = PathStore;
803  }
804 
805  OS.AddComment("Signature");
806  OS.emitIntValue(0, 4);
807 
808  OS.AddComment("Object name");
809  emitNullTerminatedSymbolName(OS, PathRef);
810 
811  endSymbolRecord(CompilerEnd);
812 }
813 
814 namespace {
815 struct Version {
816  int Part[4];
817 };
818 } // end anonymous namespace
819 
820 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
821 // the version number.
823  Version V = {{0}};
824  int N = 0;
825  for (const char C : Name) {
826  if (isdigit(C)) {
827  V.Part[N] *= 10;
828  V.Part[N] += C - '0';
829  } else if (C == '.') {
830  ++N;
831  if (N >= 4)
832  return V;
833  } else if (N > 0)
834  return V;
835  }
836  return V;
837 }
838 
839 void CodeViewDebug::emitCompilerInformation() {
840  MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
841  uint32_t Flags = 0;
842 
843  // The low byte of the flags indicates the source language.
844  Flags = CurrentSourceLanguage;
845  // TODO: Figure out which other flags need to be set.
846  if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
847  Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
848  }
849  using ArchType = llvm::Triple::ArchType;
850  ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch();
851  if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
852  Arch == ArchType::aarch64) {
853  Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
854  }
855 
856  OS.AddComment("Flags and language");
857  OS.emitInt32(Flags);
858 
859  OS.AddComment("CPUType");
860  OS.emitInt16(static_cast<uint64_t>(TheCPU));
861 
862  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
863  const MDNode *Node = *CUs->operands().begin();
864  const auto *CU = cast<DICompileUnit>(Node);
865 
866  StringRef CompilerVersion = CU->getProducer();
867  Version FrontVer = parseVersion(CompilerVersion);
868  OS.AddComment("Frontend version");
869  for (int N : FrontVer.Part) {
870  N = std::min<int>(N, std::numeric_limits<uint16_t>::max());
871  OS.emitInt16(N);
872  }
873 
874  // Some Microsoft tools, like Binscope, expect a backend version number of at
875  // least 8.something, so we'll coerce the LLVM version into a form that
876  // guarantees it'll be big enough without really lying about the version.
877  int Major = 1000 * LLVM_VERSION_MAJOR +
878  10 * LLVM_VERSION_MINOR +
879  LLVM_VERSION_PATCH;
880  // Clamp it for builds that use unusually large version numbers.
881  Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
882  Version BackVer = {{ Major, 0, 0, 0 }};
883  OS.AddComment("Backend version");
884  for (int N : BackVer.Part)
885  OS.emitInt16(N);
886 
887  OS.AddComment("Null-terminated compiler version string");
888  emitNullTerminatedSymbolName(OS, CompilerVersion);
889 
890  endSymbolRecord(CompilerEnd);
891 }
892 
894  StringRef S) {
895  StringIdRecord SIR(TypeIndex(0x0), S);
896  return TypeTable.writeLeafType(SIR);
897 }
898 
900  StringRef MainFilename) {
901  std::string FlatCmdLine;
902  raw_string_ostream OS(FlatCmdLine);
903  bool PrintedOneArg = false;
904  if (!StringRef(Args[0]).contains("-cc1")) {
905  llvm::sys::printArg(OS, "-cc1", /*Quote=*/true);
906  PrintedOneArg = true;
907  }
908  for (unsigned i = 0; i < Args.size(); i++) {
909  StringRef Arg = Args[i];
910  if (Arg.empty())
911  continue;
912  if (Arg == "-main-file-name" || Arg == "-o") {
913  i++; // Skip this argument and next one.
914  continue;
915  }
916  if (Arg.startswith("-object-file-name") || Arg == MainFilename)
917  continue;
918  if (PrintedOneArg)
919  OS << " ";
920  llvm::sys::printArg(OS, Arg, /*Quote=*/true);
921  PrintedOneArg = true;
922  }
923  OS.flush();
924  return FlatCmdLine;
925 }
926 
927 void CodeViewDebug::emitBuildInfo() {
928  // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
929  // build info. The known prefix is:
930  // - Absolute path of current directory
931  // - Compiler path
932  // - Main source file path, relative to CWD or absolute
933  // - Type server PDB file
934  // - Canonical compiler command line
935  // If frontend and backend compilation are separated (think llc or LTO), it's
936  // not clear if the compiler path should refer to the executable for the
937  // frontend or the backend. Leave it blank for now.
938  TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
939  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
940  const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
941  const auto *CU = cast<DICompileUnit>(Node);
942  const DIFile *MainSourceFile = CU->getFile();
943  BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
944  getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
945  BuildInfoArgs[BuildInfoRecord::SourceFile] =
946  getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
947  // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
948  BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
949  getStringIdTypeIdx(TypeTable, "");
950  if (Asm->TM.Options.MCOptions.Argv0 != nullptr) {
951  BuildInfoArgs[BuildInfoRecord::BuildTool] =
953  BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx(
955  MainSourceFile->getFilename()));
956  }
957  BuildInfoRecord BIR(BuildInfoArgs);
958  TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
959 
960  // Make a new .debug$S subsection for the S_BUILDINFO record, which points
961  // from the module symbols into the type stream.
962  MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
963  MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
964  OS.AddComment("LF_BUILDINFO index");
965  OS.emitInt32(BuildInfoIndex.getIndex());
966  endSymbolRecord(BIEnd);
967  endCVSubsection(BISubsecEnd);
968 }
969 
970 void CodeViewDebug::emitInlineeLinesSubsection() {
971  if (InlinedSubprograms.empty())
972  return;
973 
974  OS.AddComment("Inlinee lines subsection");
975  MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
976 
977  // We emit the checksum info for files. This is used by debuggers to
978  // determine if a pdb matches the source before loading it. Visual Studio,
979  // for instance, will display a warning that the breakpoints are not valid if
980  // the pdb does not match the source.
981  OS.AddComment("Inlinee lines signature");
982  OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
983 
984  for (const DISubprogram *SP : InlinedSubprograms) {
985  assert(TypeIndices.count({SP, nullptr}));
986  TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
987 
988  OS.AddBlankLine();
989  unsigned FileId = maybeRecordFile(SP->getFile());
990  OS.AddComment("Inlined function " + SP->getName() + " starts at " +
991  SP->getFilename() + Twine(':') + Twine(SP->getLine()));
992  OS.AddBlankLine();
993  OS.AddComment("Type index of inlined function");
994  OS.emitInt32(InlineeIdx.getIndex());
995  OS.AddComment("Offset into filechecksum table");
997  OS.AddComment("Starting line number");
998  OS.emitInt32(SP->getLine());
999  }
1000 
1001  endCVSubsection(InlineEnd);
1002 }
1003 
1004 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
1005  const DILocation *InlinedAt,
1006  const InlineSite &Site) {
1007  assert(TypeIndices.count({Site.Inlinee, nullptr}));
1008  TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
1009 
1010  // SymbolRecord
1011  MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
1012 
1013  OS.AddComment("PtrParent");
1014  OS.emitInt32(0);
1015  OS.AddComment("PtrEnd");
1016  OS.emitInt32(0);
1017  OS.AddComment("Inlinee type index");
1018  OS.emitInt32(InlineeIdx.getIndex());
1019 
1020  unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
1021  unsigned StartLineNum = Site.Inlinee->getLine();
1022 
1023  OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
1024  FI.Begin, FI.End);
1025 
1026  endSymbolRecord(InlineEnd);
1027 
1028  emitLocalVariableList(FI, Site.InlinedLocals);
1029 
1030  // Recurse on child inlined call sites before closing the scope.
1031  for (const DILocation *ChildSite : Site.ChildSites) {
1032  auto I = FI.InlineSites.find(ChildSite);
1033  assert(I != FI.InlineSites.end() &&
1034  "child site not in function inline site map");
1035  emitInlinedCallSite(FI, ChildSite, I->second);
1036  }
1037 
1038  // Close the scope.
1039  emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
1040 }
1041 
1042 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
1043  // If we have a symbol, it may be in a section that is COMDAT. If so, find the
1044  // comdat key. A section may be comdat because of -ffunction-sections or
1045  // because it is comdat in the IR.
1046  MCSectionCOFF *GVSec =
1047  GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
1048  const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
1049 
1050  MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
1052  DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
1053 
1054  OS.SwitchSection(DebugSec);
1055 
1056  // Emit the magic version number if this is the first time we've switched to
1057  // this section.
1058  if (ComdatDebugSections.insert(DebugSec).second)
1059  emitCodeViewMagicVersion();
1060 }
1061 
1062 // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
1063 // The only supported thunk ordinal is currently the standard type.
1064 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
1065  FunctionInfo &FI,
1066  const MCSymbol *Fn) {
1067  std::string FuncName =
1068  std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1069  const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
1070 
1071  OS.AddComment("Symbol subsection for " + Twine(FuncName));
1072  MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1073 
1074  // Emit S_THUNK32
1075  MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
1076  OS.AddComment("PtrParent");
1077  OS.emitInt32(0);
1078  OS.AddComment("PtrEnd");
1079  OS.emitInt32(0);
1080  OS.AddComment("PtrNext");
1081  OS.emitInt32(0);
1082  OS.AddComment("Thunk section relative address");
1083  OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1084  OS.AddComment("Thunk section index");
1085  OS.EmitCOFFSectionIndex(Fn);
1086  OS.AddComment("Code size");
1087  OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
1088  OS.AddComment("Ordinal");
1089  OS.emitInt8(unsigned(ordinal));
1090  OS.AddComment("Function name");
1091  emitNullTerminatedSymbolName(OS, FuncName);
1092  // Additional fields specific to the thunk ordinal would go here.
1093  endSymbolRecord(ThunkRecordEnd);
1094 
1095  // Local variables/inlined routines are purposely omitted here. The point of
1096  // marking this as a thunk is so Visual Studio will NOT stop in this routine.
1097 
1098  // Emit S_PROC_ID_END
1099  emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1100 
1101  endCVSubsection(SymbolsEnd);
1102 }
1103 
1104 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
1105  FunctionInfo &FI) {
1106  // For each function there is a separate subsection which holds the PC to
1107  // file:line table.
1108  const MCSymbol *Fn = Asm->getSymbol(GV);
1109  assert(Fn);
1110 
1111  // Switch to the to a comdat section, if appropriate.
1112  switchToDebugSectionForSymbol(Fn);
1113 
1114  std::string FuncName;
1115  auto *SP = GV->getSubprogram();
1116  assert(SP);
1117  setCurrentSubprogram(SP);
1118 
1119  if (SP->isThunk()) {
1120  emitDebugInfoForThunk(GV, FI, Fn);
1121  return;
1122  }
1123 
1124  // If we have a display name, build the fully qualified name by walking the
1125  // chain of scopes.
1126  if (!SP->getName().empty())
1127  FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1128 
1129  // If our DISubprogram name is empty, use the mangled name.
1130  if (FuncName.empty())
1131  FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1132 
1133  // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1135  OS.EmitCVFPOData(Fn);
1136 
1137  // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1138  OS.AddComment("Symbol subsection for " + Twine(FuncName));
1139  MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1140  {
1141  SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1142  : SymbolKind::S_GPROC32_ID;
1143  MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1144 
1145  // These fields are filled in by tools like CVPACK which run after the fact.
1146  OS.AddComment("PtrParent");
1147  OS.emitInt32(0);
1148  OS.AddComment("PtrEnd");
1149  OS.emitInt32(0);
1150  OS.AddComment("PtrNext");
1151  OS.emitInt32(0);
1152  // This is the important bit that tells the debugger where the function
1153  // code is located and what's its size:
1154  OS.AddComment("Code size");
1155  OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1156  OS.AddComment("Offset after prologue");
1157  OS.emitInt32(0);
1158  OS.AddComment("Offset before epilogue");
1159  OS.emitInt32(0);
1160  OS.AddComment("Function type index");
1161  OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
1162  OS.AddComment("Function section relative address");
1163  OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1164  OS.AddComment("Function section index");
1165  OS.EmitCOFFSectionIndex(Fn);
1166  OS.AddComment("Flags");
1167  OS.emitInt8(0);
1168  // Emit the function display name as a null-terminated string.
1169  OS.AddComment("Function name");
1170  // Truncate the name so we won't overflow the record length field.
1171  emitNullTerminatedSymbolName(OS, FuncName);
1172  endSymbolRecord(ProcRecordEnd);
1173 
1174  MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1175  // Subtract out the CSR size since MSVC excludes that and we include it.
1176  OS.AddComment("FrameSize");
1177  OS.emitInt32(FI.FrameSize - FI.CSRSize);
1178  OS.AddComment("Padding");
1179  OS.emitInt32(0);
1180  OS.AddComment("Offset of padding");
1181  OS.emitInt32(0);
1182  OS.AddComment("Bytes of callee saved registers");
1183  OS.emitInt32(FI.CSRSize);
1184  OS.AddComment("Exception handler offset");
1185  OS.emitInt32(0);
1186  OS.AddComment("Exception handler section");
1187  OS.emitInt16(0);
1188  OS.AddComment("Flags (defines frame register)");
1189  OS.emitInt32(uint32_t(FI.FrameProcOpts));
1190  endSymbolRecord(FrameProcEnd);
1191 
1192  emitLocalVariableList(FI, FI.Locals);
1193  emitGlobalVariableList(FI.Globals);
1194  emitLexicalBlockList(FI.ChildBlocks, FI);
1195 
1196  // Emit inlined call site information. Only emit functions inlined directly
1197  // into the parent function. We'll emit the other sites recursively as part
1198  // of their parent inline site.
1199  for (const DILocation *InlinedAt : FI.ChildSites) {
1200  auto I = FI.InlineSites.find(InlinedAt);
1201  assert(I != FI.InlineSites.end() &&
1202  "child site not in function inline site map");
1203  emitInlinedCallSite(FI, InlinedAt, I->second);
1204  }
1205 
1206  for (auto Annot : FI.Annotations) {
1207  MCSymbol *Label = Annot.first;
1208  MDTuple *Strs = cast<MDTuple>(Annot.second);
1209  MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1210  OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1211  // FIXME: Make sure we don't overflow the max record size.
1212  OS.EmitCOFFSectionIndex(Label);
1213  OS.emitInt16(Strs->getNumOperands());
1214  for (Metadata *MD : Strs->operands()) {
1215  // MDStrings are null terminated, so we can do EmitBytes and get the
1216  // nice .asciz directive.
1217  StringRef Str = cast<MDString>(MD)->getString();
1218  assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1219  OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
1220  }
1221  endSymbolRecord(AnnotEnd);
1222  }
1223 
1224  for (auto HeapAllocSite : FI.HeapAllocSites) {
1225  const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1226  const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1227  const DIType *DITy = std::get<2>(HeapAllocSite);
1228  MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1229  OS.AddComment("Call site offset");
1230  OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1231  OS.AddComment("Call site section index");
1232  OS.EmitCOFFSectionIndex(BeginLabel);
1233  OS.AddComment("Call instruction length");
1234  OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1235  OS.AddComment("Type index");
1236  OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
1237  endSymbolRecord(HeapAllocEnd);
1238  }
1239 
1240  if (SP != nullptr)
1241  emitDebugInfoForUDTs(LocalUDTs);
1242 
1243  // We're done with this function.
1244  emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1245  }
1246  endCVSubsection(SymbolsEnd);
1247 
1248  // We have an assembler directive that takes care of the whole line table.
1249  OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1250 }
1251 
1252 CodeViewDebug::LocalVarDefRange
1253 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1254  LocalVarDefRange DR;
1255  DR.InMemory = -1;
1256  DR.DataOffset = Offset;
1257  assert(DR.DataOffset == Offset && "truncation");
1258  DR.IsSubfield = 0;
1259  DR.StructOffset = 0;
1260  DR.CVRegister = CVRegister;
1261  return DR;
1262 }
1263 
1264 void CodeViewDebug::collectVariableInfoFromMFTable(
1265  DenseSet<InlinedEntity> &Processed) {
1266  const MachineFunction &MF = *Asm->MF;
1267  const TargetSubtargetInfo &TSI = MF.getSubtarget();
1268  const TargetFrameLowering *TFI = TSI.getFrameLowering();
1269  const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1270 
1272  if (!VI.Var)
1273  continue;
1274  assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1275  "Expected inlined-at fields to agree");
1276 
1277  Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1279 
1280  // If variable scope is not found then skip this variable.
1281  if (!Scope)
1282  continue;
1283 
1284  // If the variable has an attached offset expression, extract it.
1285  // FIXME: Try to handle DW_OP_deref as well.
1286  int64_t ExprOffset = 0;
1287  bool Deref = false;
1288  if (VI.Expr) {
1289  // If there is one DW_OP_deref element, use offset of 0 and keep going.
1290  if (VI.Expr->getNumElements() == 1 &&
1291  VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1292  Deref = true;
1293  else if (!VI.Expr->extractIfOffset(ExprOffset))
1294  continue;
1295  }
1296 
1297  // Get the frame register used and the offset.
1298  Register FrameReg;
1299  StackOffset FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1300  uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1301 
1302  assert(!FrameOffset.getScalable() &&
1303  "Frame offsets with a scalable component are not supported");
1304 
1305  // Calculate the label ranges.
1306  LocalVarDefRange DefRange =
1307  createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset);
1308 
1309  for (const InsnRange &Range : Scope->getRanges()) {
1310  const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1311  const MCSymbol *End = getLabelAfterInsn(Range.second);
1312  End = End ? End : Asm->getFunctionEnd();
1313  DefRange.Ranges.emplace_back(Begin, End);
1314  }
1315 
1316  LocalVariable Var;
1317  Var.DIVar = VI.Var;
1318  Var.DefRanges.emplace_back(std::move(DefRange));
1319  if (Deref)
1320  Var.UseReferenceType = true;
1321 
1322  recordLocalVariable(std::move(Var), Scope);
1323  }
1324 }
1325 
1326 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1327  return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1328 }
1329 
1330 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1331  return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1332 }
1333 
1334 void CodeViewDebug::calculateRanges(
1335  LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1337 
1338  // Calculate the definition ranges.
1339  for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1340  const auto &Entry = *I;
1341  if (!Entry.isDbgValue())
1342  continue;
1343  const MachineInstr *DVInst = Entry.getInstr();
1344  assert(DVInst->isDebugValue() && "Invalid History entry");
1345  // FIXME: Find a way to represent constant variables, since they are
1346  // relatively common.
1349  if (!Location)
1350  continue;
1351 
1352  // CodeView can only express variables in register and variables in memory
1353  // at a constant offset from a register. However, for variables passed
1354  // indirectly by pointer, it is common for that pointer to be spilled to a
1355  // stack location. For the special case of one offseted load followed by a
1356  // zero offset load (a pointer spilled to the stack), we change the type of
1357  // the local variable from a value type to a reference type. This tricks the
1358  // debugger into doing the load for us.
1359  if (Var.UseReferenceType) {
1360  // We're using a reference type. Drop the last zero offset load.
1361  if (canUseReferenceType(*Location))
1362  Location->LoadChain.pop_back();
1363  else
1364  continue;
1365  } else if (needsReferenceType(*Location)) {
1366  // This location can't be expressed without switching to a reference type.
1367  // Start over using that.
1368  Var.UseReferenceType = true;
1369  Var.DefRanges.clear();
1370  calculateRanges(Var, Entries);
1371  return;
1372  }
1373 
1374  // We can only handle a register or an offseted load of a register.
1375  if (Location->Register == 0 || Location->LoadChain.size() > 1)
1376  continue;
1377  {
1378  LocalVarDefRange DR;
1379  DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1380  DR.InMemory = !Location->LoadChain.empty();
1381  DR.DataOffset =
1382  !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1383  if (Location->FragmentInfo) {
1384  DR.IsSubfield = true;
1385  DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1386  } else {
1387  DR.IsSubfield = false;
1388  DR.StructOffset = 0;
1389  }
1390 
1391  if (Var.DefRanges.empty() ||
1392  Var.DefRanges.back().isDifferentLocation(DR)) {
1393  Var.DefRanges.emplace_back(std::move(DR));
1394  }
1395  }
1396 
1397  // Compute the label range.
1398  const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1399  const MCSymbol *End;
1400  if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1401  auto &EndingEntry = Entries[Entry.getEndIndex()];
1402  End = EndingEntry.isDbgValue()
1403  ? getLabelBeforeInsn(EndingEntry.getInstr())
1404  : getLabelAfterInsn(EndingEntry.getInstr());
1405  } else
1406  End = Asm->getFunctionEnd();
1407 
1408  // If the last range end is our begin, just extend the last range.
1409  // Otherwise make a new range.
1411  Var.DefRanges.back().Ranges;
1412  if (!R.empty() && R.back().second == Begin)
1413  R.back().second = End;
1414  else
1415  R.emplace_back(Begin, End);
1416 
1417  // FIXME: Do more range combining.
1418  }
1419 }
1420 
1421 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1422  DenseSet<InlinedEntity> Processed;
1423  // Grab the variable info that was squirreled away in the MMI side-table.
1424  collectVariableInfoFromMFTable(Processed);
1425 
1426  for (const auto &I : DbgValues) {
1427  InlinedEntity IV = I.first;
1428  if (Processed.count(IV))
1429  continue;
1430  const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1431  const DILocation *InlinedAt = IV.second;
1432 
1433  // Instruction ranges, specifying where IV is accessible.
1434  const auto &Entries = I.second;
1435 
1436  LexicalScope *Scope = nullptr;
1437  if (InlinedAt)
1438  Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1439  else
1440  Scope = LScopes.findLexicalScope(DIVar->getScope());
1441  // If variable scope is not found then skip this variable.
1442  if (!Scope)
1443  continue;
1444 
1445  LocalVariable Var;
1446  Var.DIVar = DIVar;
1447 
1448  calculateRanges(Var, Entries);
1449  recordLocalVariable(std::move(Var), Scope);
1450  }
1451 }
1452 
1454  const TargetSubtargetInfo &TSI = MF->getSubtarget();
1455  const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1456  const MachineFrameInfo &MFI = MF->getFrameInfo();
1457  const Function &GV = MF->getFunction();
1458  auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1459  assert(Insertion.second && "function already has info");
1460  CurFn = Insertion.first->second.get();
1461  CurFn->FuncId = NextFuncId++;
1462  CurFn->Begin = Asm->getFunctionBegin();
1463 
1464  // The S_FRAMEPROC record reports the stack size, and how many bytes of
1465  // callee-saved registers were used. For targets that don't use a PUSH
1466  // instruction (AArch64), this will be zero.
1467  CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1468  CurFn->FrameSize = MFI.getStackSize();
1469  CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1470  CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
1471 
1472  // For this function S_FRAMEPROC record, figure out which codeview register
1473  // will be the frame pointer.
1474  CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1475  CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1476  if (CurFn->FrameSize > 0) {
1477  if (!TSI.getFrameLowering()->hasFP(*MF)) {
1478  CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1479  CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1480  } else {
1481  // If there is an FP, parameters are always relative to it.
1482  CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1483  if (CurFn->HasStackRealignment) {
1484  // If the stack needs realignment, locals are relative to SP or VFRAME.
1485  CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1486  } else {
1487  // Otherwise, locals are relative to EBP, and we probably have VLAs or
1488  // other stack adjustments.
1489  CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1490  }
1491  }
1492  }
1493 
1494  // Compute other frame procedure options.
1496  if (MFI.hasVarSizedObjects())
1497  FPO |= FrameProcedureOptions::HasAlloca;
1498  if (MF->exposesReturnsTwice())
1499  FPO |= FrameProcedureOptions::HasSetJmp;
1500  // FIXME: Set HasLongJmp if we ever track that info.
1501  if (MF->hasInlineAsm())
1502  FPO |= FrameProcedureOptions::HasInlineAssembly;
1503  if (GV.hasPersonalityFn()) {
1506  FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1507  else
1508  FPO |= FrameProcedureOptions::HasExceptionHandling;
1509  }
1510  if (GV.hasFnAttribute(Attribute::InlineHint))
1511  FPO |= FrameProcedureOptions::MarkedInline;
1512  if (GV.hasFnAttribute(Attribute::Naked))
1513  FPO |= FrameProcedureOptions::Naked;
1514  if (MFI.hasStackProtectorIndex())
1515  FPO |= FrameProcedureOptions::SecurityChecks;
1516  FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1517  FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1518  if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1519  !GV.hasOptSize() && !GV.hasOptNone())
1520  FPO |= FrameProcedureOptions::OptimizedForSpeed;
1521  if (GV.hasProfileData()) {
1522  FPO |= FrameProcedureOptions::ValidProfileCounts;
1523  FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
1524  }
1525  // FIXME: Set GuardCfg when it is implemented.
1526  CurFn->FrameProcOpts = FPO;
1527 
1528  OS.EmitCVFuncIdDirective(CurFn->FuncId);
1529 
1530  // Find the end of the function prolog. First known non-DBG_VALUE and
1531  // non-frame setup location marks the beginning of the function body.
1532  // FIXME: is there a simpler a way to do this? Can we just search
1533  // for the first instruction of the function, not the last of the prolog?
1535  bool EmptyPrologue = true;
1536  for (const auto &MBB : *MF) {
1537  for (const auto &MI : MBB) {
1538  if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1539  MI.getDebugLoc()) {
1540  PrologEndLoc = MI.getDebugLoc();
1541  break;
1542  } else if (!MI.isMetaInstruction()) {
1543  EmptyPrologue = false;
1544  }
1545  }
1546  }
1547 
1548  // Record beginning of function if we have a non-empty prologue.
1549  if (PrologEndLoc && !EmptyPrologue) {
1550  DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1551  maybeRecordLocation(FnStartDL, MF);
1552  }
1553 
1554  // Find heap alloc sites and emit labels around them.
1555  for (const auto &MBB : *MF) {
1556  for (const auto &MI : MBB) {
1557  if (MI.getHeapAllocMarker()) {
1560  }
1561  }
1562  }
1563 }
1564 
1565 static bool shouldEmitUdt(const DIType *T) {
1566  if (!T)
1567  return false;
1568 
1569  // MSVC does not emit UDTs for typedefs that are scoped to classes.
1570  if (T->getTag() == dwarf::DW_TAG_typedef) {
1571  if (DIScope *Scope = T->getScope()) {
1572  switch (Scope->getTag()) {
1573  case dwarf::DW_TAG_structure_type:
1574  case dwarf::DW_TAG_class_type:
1575  case dwarf::DW_TAG_union_type:
1576  return false;
1577  default:
1578  // do nothing.
1579  ;
1580  }
1581  }
1582  }
1583 
1584  while (true) {
1585  if (!T || T->isForwardDecl())
1586  return false;
1587 
1588  const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1589  if (!DT)
1590  return true;
1591  T = DT->getBaseType();
1592  }
1593  return true;
1594 }
1595 
1596 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1597  // Don't record empty UDTs.
1598  if (Ty->getName().empty())
1599  return;
1600  if (!shouldEmitUdt(Ty))
1601  return;
1602 
1603  SmallVector<StringRef, 5> ParentScopeNames;
1604  const DISubprogram *ClosestSubprogram =
1605  collectParentScopeNames(Ty->getScope(), ParentScopeNames);
1606 
1607  std::string FullyQualifiedName =
1608  formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
1609 
1610  if (ClosestSubprogram == nullptr) {
1611  GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1612  } else if (ClosestSubprogram == CurrentSubprogram) {
1613  LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1614  }
1615 
1616  // TODO: What if the ClosestSubprogram is neither null or the current
1617  // subprogram? Currently, the UDT just gets dropped on the floor.
1618  //
1619  // The current behavior is not desirable. To get maximal fidelity, we would
1620  // need to perform all type translation before beginning emission of .debug$S
1621  // and then make LocalUDTs a member of FunctionInfo
1622 }
1623 
1624 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1625  // Generic dispatch for lowering an unknown type.
1626  switch (Ty->getTag()) {
1627  case dwarf::DW_TAG_array_type:
1628  return lowerTypeArray(cast<DICompositeType>(Ty));
1629  case dwarf::DW_TAG_typedef:
1630  return lowerTypeAlias(cast<DIDerivedType>(Ty));
1631  case dwarf::DW_TAG_base_type:
1632  return lowerTypeBasic(cast<DIBasicType>(Ty));
1633  case dwarf::DW_TAG_pointer_type:
1634  if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1635  return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1637  case dwarf::DW_TAG_reference_type:
1638  case dwarf::DW_TAG_rvalue_reference_type:
1639  return lowerTypePointer(cast<DIDerivedType>(Ty));
1640  case dwarf::DW_TAG_ptr_to_member_type:
1641  return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1642  case dwarf::DW_TAG_restrict_type:
1643  case dwarf::DW_TAG_const_type:
1644  case dwarf::DW_TAG_volatile_type:
1645  // TODO: add support for DW_TAG_atomic_type here
1646  return lowerTypeModifier(cast<DIDerivedType>(Ty));
1647  case dwarf::DW_TAG_subroutine_type:
1648  if (ClassTy) {
1649  // The member function type of a member function pointer has no
1650  // ThisAdjustment.
1651  return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1652  /*ThisAdjustment=*/0,
1653  /*IsStaticMethod=*/false);
1654  }
1655  return lowerTypeFunction(cast<DISubroutineType>(Ty));
1656  case dwarf::DW_TAG_enumeration_type:
1657  return lowerTypeEnum(cast<DICompositeType>(Ty));
1658  case dwarf::DW_TAG_class_type:
1659  case dwarf::DW_TAG_structure_type:
1660  return lowerTypeClass(cast<DICompositeType>(Ty));
1661  case dwarf::DW_TAG_union_type:
1662  return lowerTypeUnion(cast<DICompositeType>(Ty));
1663  case dwarf::DW_TAG_string_type:
1664  return lowerTypeString(cast<DIStringType>(Ty));
1665  case dwarf::DW_TAG_unspecified_type:
1666  if (Ty->getName() == "decltype(nullptr)")
1667  return TypeIndex::NullptrT();
1668  return TypeIndex::None();
1669  default:
1670  // Use the null type index.
1671  return TypeIndex();
1672  }
1673 }
1674 
1675 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1676  TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1677  StringRef TypeName = Ty->getName();
1678 
1679  addToUDTs(Ty);
1680 
1681  if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1682  TypeName == "HRESULT")
1683  return TypeIndex(SimpleTypeKind::HResult);
1684  if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1685  TypeName == "wchar_t")
1686  return TypeIndex(SimpleTypeKind::WideCharacter);
1687 
1688  return UnderlyingTypeIndex;
1689 }
1690 
1691 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1692  const DIType *ElementType = Ty->getBaseType();
1693  TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1694  // IndexType is size_t, which depends on the bitness of the target.
1695  TypeIndex IndexType = getPointerSizeInBytes() == 8
1696  ? TypeIndex(SimpleTypeKind::UInt64Quad)
1698 
1699  uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1700 
1701  // Add subranges to array type.
1702  DINodeArray Elements = Ty->getElements();
1703  for (int i = Elements.size() - 1; i >= 0; --i) {
1704  const DINode *Element = Elements[i];
1705  assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1706 
1707  const DISubrange *Subrange = cast<DISubrange>(Element);
1708  int64_t Count = -1;
1709 
1710  // If Subrange has a Count field, use it.
1711  // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1712  // where lowerbound is from the LowerBound field of the Subrange,
1713  // or the language default lowerbound if that field is unspecified.
1714  if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt *>())
1715  Count = CI->getSExtValue();
1716  else if (auto *UI = Subrange->getUpperBound().dyn_cast<ConstantInt *>()) {
1717  // Fortran uses 1 as the default lowerbound; other languages use 0.
1718  int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
1719  auto *LI = Subrange->getLowerBound().dyn_cast<ConstantInt *>();
1720  Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1721  Count = UI->getSExtValue() - Lowerbound + 1;
1722  }
1723 
1724  // Forward declarations of arrays without a size and VLAs use a count of -1.
1725  // Emit a count of zero in these cases to match what MSVC does for arrays
1726  // without a size. MSVC doesn't support VLAs, so it's not clear what we
1727  // should do for them even if we could distinguish them.
1728  if (Count == -1)
1729  Count = 0;
1730 
1731  // Update the element size and element type index for subsequent subranges.
1732  ElementSize *= Count;
1733 
1734  // If this is the outermost array, use the size from the array. It will be
1735  // more accurate if we had a VLA or an incomplete element type size.
1736  uint64_t ArraySize =
1737  (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1738 
1739  StringRef Name = (i == 0) ? Ty->getName() : "";
1740  ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1741  ElementTypeIndex = TypeTable.writeLeafType(AR);
1742  }
1743 
1744  return ElementTypeIndex;
1745 }
1746 
1747 // This function lowers a Fortran character type (DIStringType).
1748 // Note that it handles only the character*n variant (using SizeInBits
1749 // field in DIString to describe the type size) at the moment.
1750 // Other variants (leveraging the StringLength and StringLengthExp
1751 // fields in DIStringType) remain TBD.
1752 TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1753  TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1754  uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1755  StringRef Name = Ty->getName();
1756  // IndexType is size_t, which depends on the bitness of the target.
1757  TypeIndex IndexType = getPointerSizeInBytes() == 8
1758  ? TypeIndex(SimpleTypeKind::UInt64Quad)
1760 
1761  // Create a type of character array of ArraySize.
1762  ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1763 
1764  return TypeTable.writeLeafType(AR);
1765 }
1766 
1767 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1768  TypeIndex Index;
1770  uint32_t ByteSize;
1771 
1772  Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1773  ByteSize = Ty->getSizeInBits() / 8;
1774 
1776  switch (Kind) {
1777  case dwarf::DW_ATE_address:
1778  // FIXME: Translate
1779  break;
1780  case dwarf::DW_ATE_boolean:
1781  switch (ByteSize) {
1782  case 1: STK = SimpleTypeKind::Boolean8; break;
1783  case 2: STK = SimpleTypeKind::Boolean16; break;
1784  case 4: STK = SimpleTypeKind::Boolean32; break;
1785  case 8: STK = SimpleTypeKind::Boolean64; break;
1786  case 16: STK = SimpleTypeKind::Boolean128; break;
1787  }
1788  break;
1789  case dwarf::DW_ATE_complex_float:
1790  switch (ByteSize) {
1791  case 2: STK = SimpleTypeKind::Complex16; break;
1792  case 4: STK = SimpleTypeKind::Complex32; break;
1793  case 8: STK = SimpleTypeKind::Complex64; break;
1794  case 10: STK = SimpleTypeKind::Complex80; break;
1795  case 16: STK = SimpleTypeKind::Complex128; break;
1796  }
1797  break;
1798  case dwarf::DW_ATE_float:
1799  switch (ByteSize) {
1800  case 2: STK = SimpleTypeKind::Float16; break;
1801  case 4: STK = SimpleTypeKind::Float32; break;
1802  case 6: STK = SimpleTypeKind::Float48; break;
1803  case 8: STK = SimpleTypeKind::Float64; break;
1804  case 10: STK = SimpleTypeKind::Float80; break;
1805  case 16: STK = SimpleTypeKind::Float128; break;
1806  }
1807  break;
1808  case dwarf::DW_ATE_signed:
1809  switch (ByteSize) {
1810  case 1: STK = SimpleTypeKind::SignedCharacter; break;
1811  case 2: STK = SimpleTypeKind::Int16Short; break;
1812  case 4: STK = SimpleTypeKind::Int32; break;
1813  case 8: STK = SimpleTypeKind::Int64Quad; break;
1814  case 16: STK = SimpleTypeKind::Int128Oct; break;
1815  }
1816  break;
1817  case dwarf::DW_ATE_unsigned:
1818  switch (ByteSize) {
1819  case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1820  case 2: STK = SimpleTypeKind::UInt16Short; break;
1821  case 4: STK = SimpleTypeKind::UInt32; break;
1822  case 8: STK = SimpleTypeKind::UInt64Quad; break;
1823  case 16: STK = SimpleTypeKind::UInt128Oct; break;
1824  }
1825  break;
1826  case dwarf::DW_ATE_UTF:
1827  switch (ByteSize) {
1828  case 2: STK = SimpleTypeKind::Character16; break;
1829  case 4: STK = SimpleTypeKind::Character32; break;
1830  }
1831  break;
1832  case dwarf::DW_ATE_signed_char:
1833  if (ByteSize == 1)
1834  STK = SimpleTypeKind::SignedCharacter;
1835  break;
1836  case dwarf::DW_ATE_unsigned_char:
1837  if (ByteSize == 1)
1838  STK = SimpleTypeKind::UnsignedCharacter;
1839  break;
1840  default:
1841  break;
1842  }
1843 
1844  // Apply some fixups based on the source-level type name.
1845  // Include some amount of canonicalization from an old naming scheme Clang
1846  // used to use for integer types (in an outdated effort to be compatible with
1847  // GCC's debug info/GDB's behavior, which has since been addressed).
1848  if (STK == SimpleTypeKind::Int32 &&
1849  (Ty->getName() == "long int" || Ty->getName() == "long"))
1850  STK = SimpleTypeKind::Int32Long;
1851  if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1852  Ty->getName() == "unsigned long"))
1853  STK = SimpleTypeKind::UInt32Long;
1854  if (STK == SimpleTypeKind::UInt16Short &&
1855  (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1856  STK = SimpleTypeKind::WideCharacter;
1857  if ((STK == SimpleTypeKind::SignedCharacter ||
1858  STK == SimpleTypeKind::UnsignedCharacter) &&
1859  Ty->getName() == "char")
1860  STK = SimpleTypeKind::NarrowCharacter;
1861 
1862  return TypeIndex(STK);
1863 }
1864 
1865 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1866  PointerOptions PO) {
1867  TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1868 
1869  // Pointers to simple types without any options can use SimpleTypeMode, rather
1870  // than having a dedicated pointer type record.
1871  if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1872  PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1873  Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1874  SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1875  ? SimpleTypeMode::NearPointer64
1876  : SimpleTypeMode::NearPointer32;
1877  return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1878  }
1879 
1880  PointerKind PK =
1881  Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1882  PointerMode PM = PointerMode::Pointer;
1883  switch (Ty->getTag()) {
1884  default: llvm_unreachable("not a pointer tag type");
1885  case dwarf::DW_TAG_pointer_type:
1886  PM = PointerMode::Pointer;
1887  break;
1888  case dwarf::DW_TAG_reference_type:
1889  PM = PointerMode::LValueReference;
1890  break;
1891  case dwarf::DW_TAG_rvalue_reference_type:
1892  PM = PointerMode::RValueReference;
1893  break;
1894  }
1895 
1896  if (Ty->isObjectPointer())
1897  PO |= PointerOptions::Const;
1898 
1899  PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1900  return TypeTable.writeLeafType(PR);
1901 }
1902 
1904 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1905  // SizeInBytes being zero generally implies that the member pointer type was
1906  // incomplete, which can happen if it is part of a function prototype. In this
1907  // case, use the unknown model instead of the general model.
1908  if (IsPMF) {
1909  switch (Flags & DINode::FlagPtrToMemberRep) {
1910  case 0:
1911  return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1912  : PointerToMemberRepresentation::GeneralFunction;
1913  case DINode::FlagSingleInheritance:
1914  return PointerToMemberRepresentation::SingleInheritanceFunction;
1915  case DINode::FlagMultipleInheritance:
1916  return PointerToMemberRepresentation::MultipleInheritanceFunction;
1917  case DINode::FlagVirtualInheritance:
1918  return PointerToMemberRepresentation::VirtualInheritanceFunction;
1919  }
1920  } else {
1921  switch (Flags & DINode::FlagPtrToMemberRep) {
1922  case 0:
1923  return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1924  : PointerToMemberRepresentation::GeneralData;
1925  case DINode::FlagSingleInheritance:
1926  return PointerToMemberRepresentation::SingleInheritanceData;
1927  case DINode::FlagMultipleInheritance:
1928  return PointerToMemberRepresentation::MultipleInheritanceData;
1929  case DINode::FlagVirtualInheritance:
1930  return PointerToMemberRepresentation::VirtualInheritanceData;
1931  }
1932  }
1933  llvm_unreachable("invalid ptr to member representation");
1934 }
1935 
1936 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1937  PointerOptions PO) {
1938  assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1939  bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1940  TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1941  TypeIndex PointeeTI =
1942  getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
1943  PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1944  : PointerKind::Near32;
1945  PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1946  : PointerMode::PointerToDataMember;
1947 
1948  assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1949  uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1950  MemberPointerInfo MPI(
1951  ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1952  PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1953  return TypeTable.writeLeafType(PR);
1954 }
1955 
1956 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1957 /// have a translation, use the NearC convention.
1959  switch (DwarfCC) {
1960  case dwarf::DW_CC_normal: return CallingConvention::NearC;
1961  case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1962  case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1963  case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1964  case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1965  case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1966  }
1967  return CallingConvention::NearC;
1968 }
1969 
1970 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1973  bool IsModifier = true;
1974  const DIType *BaseTy = Ty;
1975  while (IsModifier && BaseTy) {
1976  // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1977  switch (BaseTy->getTag()) {
1978  case dwarf::DW_TAG_const_type:
1979  Mods |= ModifierOptions::Const;
1980  PO |= PointerOptions::Const;
1981  break;
1982  case dwarf::DW_TAG_volatile_type:
1983  Mods |= ModifierOptions::Volatile;
1984  PO |= PointerOptions::Volatile;
1985  break;
1986  case dwarf::DW_TAG_restrict_type:
1987  // Only pointer types be marked with __restrict. There is no known flag
1988  // for __restrict in LF_MODIFIER records.
1989  PO |= PointerOptions::Restrict;
1990  break;
1991  default:
1992  IsModifier = false;
1993  break;
1994  }
1995  if (IsModifier)
1996  BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1997  }
1998 
1999  // Check if the inner type will use an LF_POINTER record. If so, the
2000  // qualifiers will go in the LF_POINTER record. This comes up for types like
2001  // 'int *const' and 'int *__restrict', not the more common cases like 'const
2002  // char *'.
2003  if (BaseTy) {
2004  switch (BaseTy->getTag()) {
2005  case dwarf::DW_TAG_pointer_type:
2006  case dwarf::DW_TAG_reference_type:
2007  case dwarf::DW_TAG_rvalue_reference_type:
2008  return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
2009  case dwarf::DW_TAG_ptr_to_member_type:
2010  return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
2011  default:
2012  break;
2013  }
2014  }
2015 
2016  TypeIndex ModifiedTI = getTypeIndex(BaseTy);
2017 
2018  // Return the base type index if there aren't any modifiers. For example, the
2019  // metadata could contain restrict wrappers around non-pointer types.
2020  if (Mods == ModifierOptions::None)
2021  return ModifiedTI;
2022 
2023  ModifierRecord MR(ModifiedTI, Mods);
2024  return TypeTable.writeLeafType(MR);
2025 }
2026 
2027 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
2028  SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
2029  for (const DIType *ArgType : Ty->getTypeArray())
2030  ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
2031 
2032  // MSVC uses type none for variadic argument.
2033  if (ReturnAndArgTypeIndices.size() > 1 &&
2034  ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
2035  ReturnAndArgTypeIndices.back() = TypeIndex::None();
2036  }
2037  TypeIndex ReturnTypeIndex = TypeIndex::Void();
2038  ArrayRef<TypeIndex> ArgTypeIndices = None;
2039  if (!ReturnAndArgTypeIndices.empty()) {
2040  auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
2041  ReturnTypeIndex = ReturnAndArgTypesRef.front();
2042  ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
2043  }
2044 
2045  ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2046  TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2047 
2049 
2051  ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
2052  ArgListIndex);
2053  return TypeTable.writeLeafType(Procedure);
2054 }
2055 
2056 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
2057  const DIType *ClassTy,
2058  int ThisAdjustment,
2059  bool IsStaticMethod,
2060  FunctionOptions FO) {
2061  // Lower the containing class type.
2062  TypeIndex ClassType = getTypeIndex(ClassTy);
2063 
2064  DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
2065 
2066  unsigned Index = 0;
2067  SmallVector<TypeIndex, 8> ArgTypeIndices;
2068  TypeIndex ReturnTypeIndex = TypeIndex::Void();
2069  if (ReturnAndArgs.size() > Index) {
2070  ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
2071  }
2072 
2073  // If the first argument is a pointer type and this isn't a static method,
2074  // treat it as the special 'this' parameter, which is encoded separately from
2075  // the arguments.
2076  TypeIndex ThisTypeIndex;
2077  if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
2078  if (const DIDerivedType *PtrTy =
2079  dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
2080  if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2081  ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
2082  Index++;
2083  }
2084  }
2085  }
2086 
2087  while (Index < ReturnAndArgs.size())
2088  ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
2089 
2090  // MSVC uses type none for variadic argument.
2091  if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
2092  ArgTypeIndices.back() = TypeIndex::None();
2093 
2094  ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2095  TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2096 
2098 
2099  MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
2100  ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
2101  return TypeTable.writeLeafType(MFR);
2102 }
2103 
2104 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
2105  unsigned VSlotCount =
2106  Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
2107  SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
2108 
2109  VFTableShapeRecord VFTSR(Slots);
2110  return TypeTable.writeLeafType(VFTSR);
2111 }
2112 
2113 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
2114  switch (Flags & DINode::FlagAccessibility) {
2115  case DINode::FlagPrivate: return MemberAccess::Private;
2116  case DINode::FlagPublic: return MemberAccess::Public;
2117  case DINode::FlagProtected: return MemberAccess::Protected;
2118  case 0:
2119  // If there was no explicit access control, provide the default for the tag.
2120  return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2121  : MemberAccess::Public;
2122  }
2123  llvm_unreachable("access flags are exclusive");
2124 }
2125 
2127  if (SP->isArtificial())
2128  return MethodOptions::CompilerGenerated;
2129 
2130  // FIXME: Handle other MethodOptions.
2131 
2132  return MethodOptions::None;
2133 }
2134 
2136  bool Introduced) {
2137  if (SP->getFlags() & DINode::FlagStaticMember)
2138  return MethodKind::Static;
2139 
2140  switch (SP->getVirtuality()) {
2141  case dwarf::DW_VIRTUALITY_none:
2142  break;
2143  case dwarf::DW_VIRTUALITY_virtual:
2144  return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
2145  case dwarf::DW_VIRTUALITY_pure_virtual:
2146  return Introduced ? MethodKind::PureIntroducingVirtual
2147  : MethodKind::PureVirtual;
2148  default:
2149  llvm_unreachable("unhandled virtuality case");
2150  }
2151 
2152  return MethodKind::Vanilla;
2153 }
2154 
2156  switch (Ty->getTag()) {
2157  case dwarf::DW_TAG_class_type:
2158  return TypeRecordKind::Class;
2159  case dwarf::DW_TAG_structure_type:
2160  return TypeRecordKind::Struct;
2161  default:
2162  llvm_unreachable("unexpected tag");
2163  }
2164 }
2165 
2166 /// Return ClassOptions that should be present on both the forward declaration
2167 /// and the defintion of a tag type.
2170 
2171  // MSVC always sets this flag, even for local types. Clang doesn't always
2172  // appear to give every type a linkage name, which may be problematic for us.
2173  // FIXME: Investigate the consequences of not following them here.
2174  if (!Ty->getIdentifier().empty())
2175  CO |= ClassOptions::HasUniqueName;
2176 
2177  // Put the Nested flag on a type if it appears immediately inside a tag type.
2178  // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2179  // here. That flag is only set on definitions, and not forward declarations.
2180  const DIScope *ImmediateScope = Ty->getScope();
2181  if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2182  CO |= ClassOptions::Nested;
2183 
2184  // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2185  // type only when it has an immediate function scope. Clang never puts enums
2186  // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2187  // always in function, class, or file scopes.
2188  if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2189  if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2190  CO |= ClassOptions::Scoped;
2191  } else {
2192  for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2193  Scope = Scope->getScope()) {
2194  if (isa<DISubprogram>(Scope)) {
2195  CO |= ClassOptions::Scoped;
2196  break;
2197  }
2198  }
2199  }
2200 
2201  return CO;
2202 }
2203 
2204 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2205  switch (Ty->getTag()) {
2206  case dwarf::DW_TAG_class_type:
2207  case dwarf::DW_TAG_structure_type:
2208  case dwarf::DW_TAG_union_type:
2209  case dwarf::DW_TAG_enumeration_type:
2210  break;
2211  default:
2212  return;
2213  }
2214 
2215  if (const auto *File = Ty->getFile()) {
2216  StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2217  TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2218 
2219  UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2220  TypeTable.writeLeafType(USLR);
2221  }
2222 }
2223 
2224 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2226  TypeIndex FTI;
2227  unsigned EnumeratorCount = 0;
2228 
2229  if (Ty->isForwardDecl()) {
2230  CO |= ClassOptions::ForwardReference;
2231  } else {
2232  ContinuationRecordBuilder ContinuationBuilder;
2233  ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2234  for (const DINode *Element : Ty->getElements()) {
2235  // We assume that the frontend provides all members in source declaration
2236  // order, which is what MSVC does.
2237  if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2238  // FIXME: Is it correct to always emit these as unsigned here?
2239  EnumeratorRecord ER(MemberAccess::Public,
2240  APSInt(Enumerator->getValue(), true),
2241  Enumerator->getName());
2242  ContinuationBuilder.writeMemberType(ER);
2243  EnumeratorCount++;
2244  }
2245  }
2246  FTI = TypeTable.insertRecord(ContinuationBuilder);
2247  }
2248 
2249  std::string FullName = getFullyQualifiedName(Ty);
2250 
2251  EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2252  getTypeIndex(Ty->getBaseType()));
2253  TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2254 
2255  addUDTSrcLine(Ty, EnumTI);
2256 
2257  return EnumTI;
2258 }
2259 
2260 //===----------------------------------------------------------------------===//
2261 // ClassInfo
2262 //===----------------------------------------------------------------------===//
2263 
2265  struct MemberInfo {
2268  };
2269  // [MemberInfo]
2270  using MemberList = std::vector<MemberInfo>;
2271 
2273  // MethodName -> MethodsList
2275 
2276  /// Base classes.
2277  std::vector<const DIDerivedType *> Inheritance;
2278 
2279  /// Direct members.
2281  // Direct overloaded methods gathered by name.
2283 
2285 
2286  std::vector<const DIType *> NestedTypes;
2287 };
2288 
2289 void CodeViewDebug::clear() {
2290  assert(CurFn == nullptr);
2291  FileIdMap.clear();
2292  FnDebugInfo.clear();
2293  FileToFilepathMap.clear();
2294  LocalUDTs.clear();
2295  GlobalUDTs.clear();
2296  TypeIndices.clear();
2297  CompleteTypeIndices.clear();
2298  ScopeGlobals.clear();
2299  CVGlobalVariableOffsets.clear();
2300 }
2301 
2302 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2303  const DIDerivedType *DDTy) {
2304  if (!DDTy->getName().empty()) {
2305  Info.Members.push_back({DDTy, 0});
2306 
2307  // Collect static const data members with values.
2308  if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2309  DINode::FlagStaticMember) {
2310  if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2311  isa<ConstantFP>(DDTy->getConstant())))
2312  StaticConstMembers.push_back(DDTy);
2313  }
2314 
2315  return;
2316  }
2317 
2318  // An unnamed member may represent a nested struct or union. Attempt to
2319  // interpret the unnamed member as a DICompositeType possibly wrapped in
2320  // qualifier types. Add all the indirect fields to the current record if that
2321  // succeeds, and drop the member if that fails.
2322  assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2323  uint64_t Offset = DDTy->getOffsetInBits();
2324  const DIType *Ty = DDTy->getBaseType();
2325  bool FullyResolved = false;
2326  while (!FullyResolved) {
2327  switch (Ty->getTag()) {
2328  case dwarf::DW_TAG_const_type:
2329  case dwarf::DW_TAG_volatile_type:
2330  // FIXME: we should apply the qualifier types to the indirect fields
2331  // rather than dropping them.
2332  Ty = cast<DIDerivedType>(Ty)->getBaseType();
2333  break;
2334  default:
2335  FullyResolved = true;
2336  break;
2337  }
2338  }
2339 
2340  const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2341  if (!DCTy)
2342  return;
2343 
2344  ClassInfo NestedInfo = collectClassInfo(DCTy);
2345  for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2346  Info.Members.push_back(
2347  {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2348 }
2349 
2350 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2351  ClassInfo Info;
2352  // Add elements to structure type.
2353  DINodeArray Elements = Ty->getElements();
2354  for (auto *Element : Elements) {
2355  // We assume that the frontend provides all members in source declaration
2356  // order, which is what MSVC does.
2357  if (!Element)
2358  continue;
2359  if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2360  Info.Methods[SP->getRawName()].push_back(SP);
2361  } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2362  if (DDTy->getTag() == dwarf::DW_TAG_member) {
2363  collectMemberInfo(Info, DDTy);
2364  } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2365  Info.Inheritance.push_back(DDTy);
2366  } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2367  DDTy->getName() == "__vtbl_ptr_type") {
2368  Info.VShapeTI = getTypeIndex(DDTy);
2369  } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2370  Info.NestedTypes.push_back(DDTy);
2371  } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2372  // Ignore friend members. It appears that MSVC emitted info about
2373  // friends in the past, but modern versions do not.
2374  }
2375  } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2376  Info.NestedTypes.push_back(Composite);
2377  }
2378  // Skip other unrecognized kinds of elements.
2379  }
2380  return Info;
2381 }
2382 
2384  // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2385  // if a complete type should be emitted instead of a forward reference.
2386  return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2387  !Ty->isForwardDecl();
2388 }
2389 
2390 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2391  // Emit the complete type for unnamed structs. C++ classes with methods
2392  // which have a circular reference back to the class type are expected to
2393  // be named by the front-end and should not be "unnamed". C unnamed
2394  // structs should not have circular references.
2396  // If this unnamed complete type is already in the process of being defined
2397  // then the description of the type is malformed and cannot be emitted
2398  // into CodeView correctly so report a fatal error.
2399  auto I = CompleteTypeIndices.find(Ty);
2400  if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2401  report_fatal_error("cannot debug circular reference to unnamed type");
2402  return getCompleteTypeIndex(Ty);
2403  }
2404 
2405  // First, construct the forward decl. Don't look into Ty to compute the
2406  // forward decl options, since it might not be available in all TUs.
2408  ClassOptions CO =
2409  ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2410  std::string FullName = getFullyQualifiedName(Ty);
2411  ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2412  FullName, Ty->getIdentifier());
2413  TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2414  if (!Ty->isForwardDecl())
2415  DeferredCompleteTypes.push_back(Ty);
2416  return FwdDeclTI;
2417 }
2418 
2419 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2420  // Construct the field list and complete type record.
2423  TypeIndex FieldTI;
2424  TypeIndex VShapeTI;
2425  unsigned FieldCount;
2426  bool ContainsNestedClass;
2427  std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2428  lowerRecordFieldList(Ty);
2429 
2430  if (ContainsNestedClass)
2431  CO |= ClassOptions::ContainsNestedClass;
2432 
2433  // MSVC appears to set this flag by searching any destructor or method with
2434  // FunctionOptions::Constructor among the emitted members. Clang AST has all
2435  // the members, however special member functions are not yet emitted into
2436  // debug information. For now checking a class's non-triviality seems enough.
2437  // FIXME: not true for a nested unnamed struct.
2438  if (isNonTrivial(Ty))
2439  CO |= ClassOptions::HasConstructorOrDestructor;
2440 
2441  std::string FullName = getFullyQualifiedName(Ty);
2442 
2443  uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2444 
2445  ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2446  SizeInBytes, FullName, Ty->getIdentifier());
2447  TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2448 
2449  addUDTSrcLine(Ty, ClassTI);
2450 
2451  addToUDTs(Ty);
2452 
2453  return ClassTI;
2454 }
2455 
2456 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2457  // Emit the complete type for unnamed unions.
2459  return getCompleteTypeIndex(Ty);
2460 
2461  ClassOptions CO =
2462  ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2463  std::string FullName = getFullyQualifiedName(Ty);
2464  UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2465  TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2466  if (!Ty->isForwardDecl())
2467  DeferredCompleteTypes.push_back(Ty);
2468  return FwdDeclTI;
2469 }
2470 
2471 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2472  ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2473  TypeIndex FieldTI;
2474  unsigned FieldCount;
2475  bool ContainsNestedClass;
2476  std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2477  lowerRecordFieldList(Ty);
2478 
2479  if (ContainsNestedClass)
2480  CO |= ClassOptions::ContainsNestedClass;
2481 
2482  uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2483  std::string FullName = getFullyQualifiedName(Ty);
2484 
2485  UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2486  Ty->getIdentifier());
2487  TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2488 
2489  addUDTSrcLine(Ty, UnionTI);
2490 
2491  addToUDTs(Ty);
2492 
2493  return UnionTI;
2494 }
2495 
2496 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2497 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2498  // Manually count members. MSVC appears to count everything that generates a
2499  // field list record. Each individual overload in a method overload group
2500  // contributes to this count, even though the overload group is a single field
2501  // list record.
2502  unsigned MemberCount = 0;
2503  ClassInfo Info = collectClassInfo(Ty);
2504  ContinuationRecordBuilder ContinuationBuilder;
2505  ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2506 
2507  // Create base classes.
2508  for (const DIDerivedType *I : Info.Inheritance) {
2509  if (I->getFlags() & DINode::FlagVirtual) {
2510  // Virtual base.
2511  unsigned VBPtrOffset = I->getVBPtrOffset();
2512  // FIXME: Despite the accessor name, the offset is really in bytes.
2513  unsigned VBTableIndex = I->getOffsetInBits() / 4;
2514  auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2515  ? TypeRecordKind::IndirectVirtualBaseClass
2516  : TypeRecordKind::VirtualBaseClass;
2518  RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2519  getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2520  VBTableIndex);
2521 
2522  ContinuationBuilder.writeMemberType(VBCR);
2523  MemberCount++;
2524  } else {
2525  assert(I->getOffsetInBits() % 8 == 0 &&
2526  "bases must be on byte boundaries");
2527  BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2528  getTypeIndex(I->getBaseType()),
2529  I->getOffsetInBits() / 8);
2530  ContinuationBuilder.writeMemberType(BCR);
2531  MemberCount++;
2532  }
2533  }
2534 
2535  // Create members.
2536  for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2537  const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2538  TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2539  StringRef MemberName = Member->getName();
2540  MemberAccess Access =
2541  translateAccessFlags(Ty->getTag(), Member->getFlags());
2542 
2543  if (Member->isStaticMember()) {
2544  StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2545  ContinuationBuilder.writeMemberType(SDMR);
2546  MemberCount++;
2547  continue;
2548  }
2549 
2550  // Virtual function pointer member.
2551  if ((Member->getFlags() & DINode::FlagArtificial) &&
2552  Member->getName().startswith("_vptr$")) {
2553  VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2554  ContinuationBuilder.writeMemberType(VFPR);
2555  MemberCount++;
2556  continue;
2557  }
2558 
2559  // Data member.
2560  uint64_t MemberOffsetInBits =
2561  Member->getOffsetInBits() + MemberInfo.BaseOffset;
2562  if (Member->isBitField()) {
2563  uint64_t StartBitOffset = MemberOffsetInBits;
2564  if (const auto *CI =
2565  dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2566  MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2567  }
2568  StartBitOffset -= MemberOffsetInBits;
2569  BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2570  StartBitOffset);
2571  MemberBaseType = TypeTable.writeLeafType(BFR);
2572  }
2573  uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2574  DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2575  MemberName);
2576  ContinuationBuilder.writeMemberType(DMR);
2577  MemberCount++;
2578  }
2579 
2580  // Create methods
2581  for (auto &MethodItr : Info.Methods) {
2582  StringRef Name = MethodItr.first->getString();
2583 
2584  std::vector<OneMethodRecord> Methods;
2585  for (const DISubprogram *SP : MethodItr.second) {
2586  TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2587  bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2588 
2589  unsigned VFTableOffset = -1;
2590  if (Introduced)
2591  VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2592 
2593  Methods.push_back(OneMethodRecord(
2594  MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2595  translateMethodKindFlags(SP, Introduced),
2596  translateMethodOptionFlags(SP), VFTableOffset, Name));
2597  MemberCount++;
2598  }
2599  assert(!Methods.empty() && "Empty methods map entry");
2600  if (Methods.size() == 1)
2601  ContinuationBuilder.writeMemberType(Methods[0]);
2602  else {
2603  // FIXME: Make this use its own ContinuationBuilder so that
2604  // MethodOverloadList can be split correctly.
2605  MethodOverloadListRecord MOLR(Methods);
2606  TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2607 
2608  OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2609  ContinuationBuilder.writeMemberType(OMR);
2610  }
2611  }
2612 
2613  // Create nested classes.
2614  for (const DIType *Nested : Info.NestedTypes) {
2615  NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2616  ContinuationBuilder.writeMemberType(R);
2617  MemberCount++;
2618  }
2619 
2620  TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2621  return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2622  !Info.NestedTypes.empty());
2623 }
2624 
2625 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2626  if (!VBPType.getIndex()) {
2627  // Make a 'const int *' type.
2628  ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2629  TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2630 
2631  PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2632  : PointerKind::Near32;
2633  PointerMode PM = PointerMode::Pointer;
2635  PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2636  VBPType = TypeTable.writeLeafType(PR);
2637  }
2638 
2639  return VBPType;
2640 }
2641 
2642 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2643  // The null DIType is the void type. Don't try to hash it.
2644  if (!Ty)
2645  return TypeIndex::Void();
2646 
2647  // Check if we've already translated this type. Don't try to do a
2648  // get-or-create style insertion that caches the hash lookup across the
2649  // lowerType call. It will update the TypeIndices map.
2650  auto I = TypeIndices.find({Ty, ClassTy});
2651  if (I != TypeIndices.end())
2652  return I->second;
2653 
2654  TypeLoweringScope S(*this);
2655  TypeIndex TI = lowerType(Ty, ClassTy);
2656  return recordTypeIndexForDINode(Ty, TI, ClassTy);
2657 }
2658 
2660 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2661  const DISubroutineType *SubroutineTy) {
2662  assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2663  "this type must be a pointer type");
2664 
2666  if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2667  Options = PointerOptions::LValueRefThisPointer;
2668  else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2669  Options = PointerOptions::RValueRefThisPointer;
2670 
2671  // Check if we've already translated this type. If there is no ref qualifier
2672  // on the function then we look up this pointer type with no associated class
2673  // so that the TypeIndex for the this pointer can be shared with the type
2674  // index for other pointers to this class type. If there is a ref qualifier
2675  // then we lookup the pointer using the subroutine as the parent type.
2676  auto I = TypeIndices.find({PtrTy, SubroutineTy});
2677  if (I != TypeIndices.end())
2678  return I->second;
2679 
2680  TypeLoweringScope S(*this);
2681  TypeIndex TI = lowerTypePointer(PtrTy, Options);
2682  return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2683 }
2684 
2685 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2686  PointerRecord PR(getTypeIndex(Ty),
2687  getPointerSizeInBytes() == 8 ? PointerKind::Near64
2688  : PointerKind::Near32,
2689  PointerMode::LValueReference, PointerOptions::None,
2690  Ty->getSizeInBits() / 8);
2691  return TypeTable.writeLeafType(PR);
2692 }
2693 
2694 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2695  // The null DIType is the void type. Don't try to hash it.
2696  if (!Ty)
2697  return TypeIndex::Void();
2698 
2699  // Look through typedefs when getting the complete type index. Call
2700  // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2701  // emitted only once.
2702  if (Ty->getTag() == dwarf::DW_TAG_typedef)
2703  (void)getTypeIndex(Ty);
2704  while (Ty->getTag() == dwarf::DW_TAG_typedef)
2705  Ty = cast<DIDerivedType>(Ty)->getBaseType();
2706 
2707  // If this is a non-record type, the complete type index is the same as the
2708  // normal type index. Just call getTypeIndex.
2709  switch (Ty->getTag()) {
2710  case dwarf::DW_TAG_class_type:
2711  case dwarf::DW_TAG_structure_type:
2712  case dwarf::DW_TAG_union_type:
2713  break;
2714  default:
2715  return getTypeIndex(Ty);
2716  }
2717 
2718  const auto *CTy = cast<DICompositeType>(Ty);
2719 
2720  TypeLoweringScope S(*this);
2721 
2722  // Make sure the forward declaration is emitted first. It's unclear if this
2723  // is necessary, but MSVC does it, and we should follow suit until we can show
2724  // otherwise.
2725  // We only emit a forward declaration for named types.
2726  if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2727  TypeIndex FwdDeclTI = getTypeIndex(CTy);
2728 
2729  // Just use the forward decl if we don't have complete type info. This
2730  // might happen if the frontend is using modules and expects the complete
2731  // definition to be emitted elsewhere.
2732  if (CTy->isForwardDecl())
2733  return FwdDeclTI;
2734  }
2735 
2736  // Check if we've already translated the complete record type.
2737  // Insert the type with a null TypeIndex to signify that the type is currently
2738  // being lowered.
2739  auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2740  if (!InsertResult.second)
2741  return InsertResult.first->second;
2742 
2743  TypeIndex TI;
2744  switch (CTy->getTag()) {
2745  case dwarf::DW_TAG_class_type:
2746  case dwarf::DW_TAG_structure_type:
2747  TI = lowerCompleteTypeClass(CTy);
2748  break;
2749  case dwarf::DW_TAG_union_type:
2750  TI = lowerCompleteTypeUnion(CTy);
2751  break;
2752  default:
2753  llvm_unreachable("not a record");
2754  }
2755 
2756  // Update the type index associated with this CompositeType. This cannot
2757  // use the 'InsertResult' iterator above because it is potentially
2758  // invalidated by map insertions which can occur while lowering the class
2759  // type above.
2760  CompleteTypeIndices[CTy] = TI;
2761  return TI;
2762 }
2763 
2764 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2765 /// and do this until fixpoint, as each complete record type typically
2766 /// references
2767 /// many other record types.
2768 void CodeViewDebug::emitDeferredCompleteTypes() {
2770  while (!DeferredCompleteTypes.empty()) {
2771  std::swap(DeferredCompleteTypes, TypesToEmit);
2772  for (const DICompositeType *RecordTy : TypesToEmit)
2773  getCompleteTypeIndex(RecordTy);
2774  TypesToEmit.clear();
2775  }
2776 }
2777 
2778 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2779  ArrayRef<LocalVariable> Locals) {
2780  // Get the sorted list of parameters and emit them first.
2782  for (const LocalVariable &L : Locals)
2783  if (L.DIVar->isParameter())
2784  Params.push_back(&L);
2785  llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2786  return L->DIVar->getArg() < R->DIVar->getArg();
2787  });
2788  for (const LocalVariable *L : Params)
2789  emitLocalVariable(FI, *L);
2790 
2791  // Next emit all non-parameters in the order that we found them.
2792  for (const LocalVariable &L : Locals)
2793  if (!L.DIVar->isParameter())
2794  emitLocalVariable(FI, L);
2795 }
2796 
2797 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2798  const LocalVariable &Var) {
2799  // LocalSym record, see SymbolRecord.h for more info.
2800  MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2801 
2803  if (Var.DIVar->isParameter())
2804  Flags |= LocalSymFlags::IsParameter;
2805  if (Var.DefRanges.empty())
2806  Flags |= LocalSymFlags::IsOptimizedOut;
2807 
2808  OS.AddComment("TypeIndex");
2809  TypeIndex TI = Var.UseReferenceType
2810  ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2811  : getCompleteTypeIndex(Var.DIVar->getType());
2812  OS.emitInt32(TI.getIndex());
2813  OS.AddComment("Flags");
2814  OS.emitInt16(static_cast<uint16_t>(Flags));
2815  // Truncate the name so we won't overflow the record length field.
2816  emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2817  endSymbolRecord(LocalEnd);
2818 
2819  // Calculate the on disk prefix of the appropriate def range record. The
2820  // records and on disk formats are described in SymbolRecords.h. BytePrefix
2821  // should be big enough to hold all forms without memory allocation.
2822  SmallString<20> BytePrefix;
2823  for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2824  BytePrefix.clear();
2825  if (DefRange.InMemory) {
2826  int Offset = DefRange.DataOffset;
2827  unsigned Reg = DefRange.CVRegister;
2828 
2829  // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2830  // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2831  // instead. In frames without stack realignment, $T0 will be the CFA.
2832  if (RegisterId(Reg) == RegisterId::ESP) {
2833  Reg = unsigned(RegisterId::VFRAME);
2834  Offset += FI.OffsetAdjustment;
2835  }
2836 
2837  // If we can use the chosen frame pointer for the frame and this isn't a
2838  // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2839  // Otherwise, use S_DEFRANGE_REGISTER_REL.
2841  if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2842  (bool(Flags & LocalSymFlags::IsParameter)
2843  ? (EncFP == FI.EncodedParamFramePtrReg)
2844  : (EncFP == FI.EncodedLocalFramePtrReg))) {
2846  DRHdr.Offset = Offset;
2847  OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2848  } else {
2849  uint16_t RegRelFlags = 0;
2850  if (DefRange.IsSubfield) {
2851  RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2852  (DefRange.StructOffset
2853  << DefRangeRegisterRelSym::OffsetInParentShift);
2854  }
2856  DRHdr.Register = Reg;
2857  DRHdr.Flags = RegRelFlags;
2858  DRHdr.BasePointerOffset = Offset;
2859  OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2860  }
2861  } else {
2862  assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2863  if (DefRange.IsSubfield) {
2865  DRHdr.Register = DefRange.CVRegister;
2866  DRHdr.MayHaveNoName = 0;
2867  DRHdr.OffsetInParent = DefRange.StructOffset;
2868  OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2869  } else {
2870  DefRangeRegisterHeader DRHdr;
2871  DRHdr.Register = DefRange.CVRegister;
2872  DRHdr.MayHaveNoName = 0;
2873  OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2874  }
2875  }
2876  }
2877 }
2878 
2879 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2880  const FunctionInfo& FI) {
2881  for (LexicalBlock *Block : Blocks)
2882  emitLexicalBlock(*Block, FI);
2883 }
2884 
2885 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2886 /// lexical block scope.
2887 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2888  const FunctionInfo& FI) {
2889  MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2890  OS.AddComment("PtrParent");
2891  OS.emitInt32(0); // PtrParent
2892  OS.AddComment("PtrEnd");
2893  OS.emitInt32(0); // PtrEnd
2894  OS.AddComment("Code size");
2895  OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2896  OS.AddComment("Function section relative address");
2897  OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2898  OS.AddComment("Function section index");
2899  OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2900  OS.AddComment("Lexical block name");
2901  emitNullTerminatedSymbolName(OS, Block.Name); // Name
2902  endSymbolRecord(RecordEnd);
2903 
2904  // Emit variables local to this lexical block.
2905  emitLocalVariableList(FI, Block.Locals);
2906  emitGlobalVariableList(Block.Globals);
2907 
2908  // Emit lexical blocks contained within this block.
2909  emitLexicalBlockList(Block.Children, FI);
2910 
2911  // Close the lexical block scope.
2912  emitEndSymbolRecord(SymbolKind::S_END);
2913 }
2914 
2915 /// Convenience routine for collecting lexical block information for a list
2916 /// of lexical scopes.
2917 void CodeViewDebug::collectLexicalBlockInfo(
2922  for (LexicalScope *Scope : Scopes)
2923  collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2924 }
2925 
2926 /// Populate the lexical blocks and local variable lists of the parent with
2927 /// information about the specified lexical scope.
2928 void CodeViewDebug::collectLexicalBlockInfo(
2930  SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2931  SmallVectorImpl<LocalVariable> &ParentLocals,
2932  SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2933  if (Scope.isAbstractScope())
2934  return;
2935 
2936  // Gather information about the lexical scope including local variables,
2937  // global variables, and address ranges.
2938  bool IgnoreScope = false;
2939  auto LI = ScopeVariables.find(&Scope);
2941  LI != ScopeVariables.end() ? &LI->second : nullptr;
2942  auto GI = ScopeGlobals.find(Scope.getScopeNode());
2944  GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2945  const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2946  const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2947 
2948  // Ignore lexical scopes which do not contain variables.
2949  if (!Locals && !Globals)
2950  IgnoreScope = true;
2951 
2952  // Ignore lexical scopes which are not lexical blocks.
2953  if (!DILB)
2954  IgnoreScope = true;
2955 
2956  // Ignore scopes which have too many address ranges to represent in the
2957  // current CodeView format or do not have a valid address range.
2958  //
2959  // For lexical scopes with multiple address ranges you may be tempted to
2960  // construct a single range covering every instruction where the block is
2961  // live and everything in between. Unfortunately, Visual Studio only
2962  // displays variables from the first matching lexical block scope. If the
2963  // first lexical block contains exception handling code or cold code which
2964  // is moved to the bottom of the routine creating a single range covering
2965  // nearly the entire routine, then it will hide all other lexical blocks
2966  // and the variables they contain.
2967  if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2968  IgnoreScope = true;
2969 
2970  if (IgnoreScope) {
2971  // This scope can be safely ignored and eliminating it will reduce the
2972  // size of the debug information. Be sure to collect any variable and scope
2973  // information from the this scope or any of its children and collapse them
2974  // into the parent scope.
2975  if (Locals)
2976  ParentLocals.append(Locals->begin(), Locals->end());
2977  if (Globals)
2978  ParentGlobals.append(Globals->begin(), Globals->end());
2979  collectLexicalBlockInfo(Scope.getChildren(),
2980  ParentBlocks,
2981  ParentLocals,
2982  ParentGlobals);
2983  return;
2984  }
2985 
2986  // Create a new CodeView lexical block for this lexical scope. If we've
2987  // seen this DILexicalBlock before then the scope tree is malformed and
2988  // we can handle this gracefully by not processing it a second time.
2989  auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2990  if (!BlockInsertion.second)
2991  return;
2992 
2993  // Create a lexical block containing the variables and collect the the
2994  // lexical block information for the children.
2995  const InsnRange &Range = Ranges.front();
2996  assert(Range.first && Range.second);
2997  LexicalBlock &Block = BlockInsertion.first->second;
2998  Block.Begin = getLabelBeforeInsn(Range.first);
2999  Block.End = getLabelAfterInsn(Range.second);
3000  assert(Block.Begin && "missing label for scope begin");
3001  assert(Block.End && "missing label for scope end");
3002  Block.Name = DILB->getName();
3003  if (Locals)
3004  Block.Locals = std::move(*Locals);
3005  if (Globals)
3006  Block.Globals = std::move(*Globals);
3007  ParentBlocks.push_back(&Block);
3008  collectLexicalBlockInfo(Scope.getChildren(),
3009  Block.Children,
3010  Block.Locals,
3011  Block.Globals);
3012 }
3013 
3015  const Function &GV = MF->getFunction();
3016  assert(FnDebugInfo.count(&GV));
3017  assert(CurFn == FnDebugInfo[&GV].get());
3018 
3019  collectVariableInfo(GV.getSubprogram());
3020 
3021  // Build the lexical block structure to emit for this routine.
3023  collectLexicalBlockInfo(*CFS,
3024  CurFn->ChildBlocks,
3025  CurFn->Locals,
3026  CurFn->Globals);
3027 
3028  // Clear the scope and variable information from the map which will not be
3029  // valid after we have finished processing this routine. This also prepares
3030  // the map for the subsequent routine.
3031  ScopeVariables.clear();
3032 
3033  // Don't emit anything if we don't have any line tables.
3034  // Thunks are compiler-generated and probably won't have source correlation.
3035  if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
3036  FnDebugInfo.erase(&GV);
3037  CurFn = nullptr;
3038  return;
3039  }
3040 
3041  // Find heap alloc sites and add to list.
3042  for (const auto &MBB : *MF) {
3043  for (const auto &MI : MBB) {
3044  if (MDNode *MD = MI.getHeapAllocMarker()) {
3045  CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
3047  dyn_cast<DIType>(MD)));
3048  }
3049  }
3050  }
3051 
3052  CurFn->Annotations = MF->getCodeViewAnnotations();
3053 
3054  CurFn->End = Asm->getFunctionEnd();
3055 
3056  CurFn = nullptr;
3057 }
3058 
3059 // Usable locations are valid with non-zero line numbers. A line number of zero
3060 // corresponds to optimized code that doesn't have a distinct source location.
3061 // In this case, we try to use the previous or next source location depending on
3062 // the context.
3064  return DL && DL.getLine() != 0;
3065 }
3066 
3069 
3070  // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3071  if (!Asm || !CurFn || MI->isDebugInstr() ||
3072  MI->getFlag(MachineInstr::FrameSetup))
3073  return;
3074 
3075  // If the first instruction of a new MBB has no location, find the first
3076  // instruction with a location and use that.
3077  DebugLoc DL = MI->getDebugLoc();
3078  if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
3079  for (const auto &NextMI : *MI->getParent()) {
3080  if (NextMI.isDebugInstr())
3081  continue;
3082  DL = NextMI.getDebugLoc();
3083  if (isUsableDebugLoc(DL))
3084  break;
3085  }
3086  // FIXME: Handle the case where the BB has no valid locations. This would
3087  // probably require doing a real dataflow analysis.
3088  }
3089  PrevInstBB = MI->getParent();
3090 
3091  // If we still don't have a debug location, don't record a location.
3092  if (!isUsableDebugLoc(DL))
3093  return;
3094 
3095  maybeRecordLocation(DL, Asm->MF);
3096 }
3097 
3098 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
3099  MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3100  *EndLabel = MMI->getContext().createTempSymbol();
3101  OS.emitInt32(unsigned(Kind));
3102  OS.AddComment("Subsection size");
3103  OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
3104  OS.emitLabel(BeginLabel);
3105  return EndLabel;
3106 }
3107 
3108 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
3109  OS.emitLabel(EndLabel);
3110  // Every subsection must be aligned to a 4-byte boundary.
3111  OS.emitValueToAlignment(4);
3112 }
3113 
3115  for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
3116  if (EE.Value == SymKind)
3117  return EE.Name;
3118  return "";
3119 }
3120 
3121 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
3122  MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3123  *EndLabel = MMI->getContext().createTempSymbol();
3124  OS.AddComment("Record length");
3125  OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
3126  OS.emitLabel(BeginLabel);
3127  if (OS.isVerboseAsm())
3128  OS.AddComment("Record kind: " + getSymbolName(SymKind));
3129  OS.emitInt16(unsigned(SymKind));
3130  return EndLabel;
3131 }
3132 
3133 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
3134  // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
3135  // an extra copy of every symbol record in LLD. This increases object file
3136  // size by less than 1% in the clang build, and is compatible with the Visual
3137  // C++ linker.
3138  OS.emitValueToAlignment(4);
3139  OS.emitLabel(SymEnd);
3140 }
3141 
3142 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
3143  OS.AddComment("Record length");
3144  OS.emitInt16(2);
3145  if (OS.isVerboseAsm())
3146  OS.AddComment("Record kind: " + getSymbolName(EndKind));
3147  OS.emitInt16(uint16_t(EndKind)); // Record Kind
3148 }
3149 
3150 void CodeViewDebug::emitDebugInfoForUDTs(
3151  const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3152 #ifndef NDEBUG
3153  size_t OriginalSize = UDTs.size();
3154 #endif
3155  for (const auto &UDT : UDTs) {
3156  const DIType *T = UDT.second;
3158  MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3159  OS.AddComment("Type");
3160  OS.emitInt32(getCompleteTypeIndex(T).getIndex());
3161  assert(OriginalSize == UDTs.size() &&
3162  "getCompleteTypeIndex found new UDTs!");
3163  emitNullTerminatedSymbolName(OS, UDT.first);
3164  endSymbolRecord(UDTRecordEnd);
3165  }
3166 }
3167 
3168 void CodeViewDebug::collectGlobalVariableInfo() {
3170  GlobalMap;
3171  for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3173  GV.getDebugInfo(GVEs);
3174  for (const auto *GVE : GVEs)
3175  GlobalMap[GVE] = &GV;
3176  }
3177 
3178  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3179  for (const MDNode *Node : CUs->operands()) {
3180  const auto *CU = cast<DICompileUnit>(Node);
3181  for (const auto *GVE : CU->getGlobalVariables()) {
3182  const DIGlobalVariable *DIGV = GVE->getVariable();
3183  const DIExpression *DIE = GVE->getExpression();
3184 
3185  if ((DIE->getNumElements() == 2) &&
3186  (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3187  // Record the constant offset for the variable.
3188  //
3189  // A Fortran common block uses this idiom to encode the offset
3190  // of a variable from the common block's starting address.
3191  CVGlobalVariableOffsets.insert(
3192  std::make_pair(DIGV, DIE->getElement(1)));
3193 
3194  // Emit constant global variables in a global symbol section.
3195  if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
3196  CVGlobalVariable CVGV = {DIGV, DIE};
3197  GlobalVariables.emplace_back(std::move(CVGV));
3198  }
3199 
3200  const auto *GV = GlobalMap.lookup(GVE);
3201  if (!GV || GV->isDeclarationForLinker())
3202  continue;
3203 
3204  DIScope *Scope = DIGV->getScope();
3205  SmallVector<CVGlobalVariable, 1> *VariableList;
3206  if (Scope && isa<DILocalScope>(Scope)) {
3207  // Locate a global variable list for this scope, creating one if
3208  // necessary.
3209  auto Insertion = ScopeGlobals.insert(
3210  {Scope, std::unique_ptr<GlobalVariableList>()});
3211  if (Insertion.second)
3212  Insertion.first->second = std::make_unique<GlobalVariableList>();
3213  VariableList = Insertion.first->second.get();
3214  } else if (GV->hasComdat())
3215  // Emit this global variable into a COMDAT section.
3216  VariableList = &ComdatVariables;
3217  else
3218  // Emit this global variable in a single global symbol section.
3219  VariableList = &GlobalVariables;
3220  CVGlobalVariable CVGV = {DIGV, GV};
3221  VariableList->emplace_back(std::move(CVGV));
3222  }
3223  }
3224 }
3225 
3226 void CodeViewDebug::collectDebugInfoForGlobals() {
3227  for (const CVGlobalVariable &CVGV : GlobalVariables) {
3228  const DIGlobalVariable *DIGV = CVGV.DIGV;
3229  const DIScope *Scope = DIGV->getScope();
3230  getCompleteTypeIndex(DIGV->getType());
3231  getFullyQualifiedName(Scope, DIGV->getName());
3232  }
3233 
3234  for (const CVGlobalVariable &CVGV : ComdatVariables) {
3235  const DIGlobalVariable *DIGV = CVGV.DIGV;
3236  const DIScope *Scope = DIGV->getScope();
3237  getCompleteTypeIndex(DIGV->getType());
3238  getFullyQualifiedName(Scope, DIGV->getName());
3239  }
3240 }
3241 
3242 void CodeViewDebug::emitDebugInfoForGlobals() {
3243  // First, emit all globals that are not in a comdat in a single symbol
3244  // substream. MSVC doesn't like it if the substream is empty, so only open
3245  // it if we have at least one global to emit.
3246  switchToDebugSectionForSymbol(nullptr);
3247  if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3248  OS.AddComment("Symbol subsection for globals");
3249  MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3250  emitGlobalVariableList(GlobalVariables);
3251  emitStaticConstMemberList();
3252  endCVSubsection(EndLabel);
3253  }
3254 
3255  // Second, emit each global that is in a comdat into its own .debug$S
3256  // section along with its own symbol substream.
3257  for (const CVGlobalVariable &CVGV : ComdatVariables) {
3258  const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
3259  MCSymbol *GVSym = Asm->getSymbol(GV);
3260  OS.AddComment("Symbol subsection for " +
3262  switchToDebugSectionForSymbol(GVSym);
3263  MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3264  // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3265  emitDebugInfoForGlobal(CVGV);
3266  endCVSubsection(EndLabel);
3267  }
3268 }
3269 
3270 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3271  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3272  for (const MDNode *Node : CUs->operands()) {
3273  for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3274  if (DIType *RT = dyn_cast<DIType>(Ty)) {
3275  getTypeIndex(RT);
3276  // FIXME: Add to global/local DTU list.
3277  }
3278  }
3279  }
3280 }
3281 
3282 // Emit each global variable in the specified array.
3283 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3284  for (const CVGlobalVariable &CVGV : Globals) {
3285  // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3286  emitDebugInfoForGlobal(CVGV);
3287  }
3288 }
3289 
3290 void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3291  const std::string &QualifiedName) {
3292  MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3293  OS.AddComment("Type");
3294  OS.emitInt32(getTypeIndex(DTy).getIndex());
3295 
3296  OS.AddComment("Value");
3297 
3298  // Encoded integers shouldn't need more than 10 bytes.
3299  uint8_t Data[10];
3301  CodeViewRecordIO IO(Writer);
3302  cantFail(IO.mapEncodedInteger(Value));
3303  StringRef SRef((char *)Data, Writer.getOffset());
3304  OS.emitBinaryData(SRef);
3305 
3306  OS.AddComment("Name");
3308  endSymbolRecord(SConstantEnd);
3309 }
3310 
3311 void CodeViewDebug::emitStaticConstMemberList() {
3312  for (const DIDerivedType *DTy : StaticConstMembers) {
3313  const DIScope *Scope = DTy->getScope();
3314 
3315  APSInt Value;
3316  if (const ConstantInt *CI =
3317  dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3318  Value = APSInt(CI->getValue(),
3319  DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3320  else if (const ConstantFP *CFP =
3321  dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3322  Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3323  else
3324  llvm_unreachable("cannot emit a constant without a value");
3325 
3326  emitConstantSymbolRecord(DTy->getBaseType(), Value,
3327  getFullyQualifiedName(Scope, DTy->getName()));
3328  }
3329 }
3330 
3331 static bool isFloatDIType(const DIType *Ty) {
3332  if (isa<DICompositeType>(Ty))
3333  return false;
3334 
3335  if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3336  dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3337  if (T == dwarf::DW_TAG_pointer_type ||
3338  T == dwarf::DW_TAG_ptr_to_member_type ||
3339  T == dwarf::DW_TAG_reference_type ||
3340  T == dwarf::DW_TAG_rvalue_reference_type)
3341  return false;
3342  assert(DTy->getBaseType() && "Expected valid base type");
3343  return isFloatDIType(DTy->getBaseType());
3344  }
3345 
3346  auto *BTy = cast<DIBasicType>(Ty);
3347  return (BTy->getEncoding() == dwarf::DW_ATE_float);
3348 }
3349 
3350 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3351  const DIGlobalVariable *DIGV = CVGV.DIGV;
3352 
3353  const DIScope *Scope = DIGV->getScope();
3354  // For static data members, get the scope from the declaration.
3355  if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3357  Scope = MemberDecl->getScope();
3358  // For Fortran, the scoping portion is elided in its name so that we can
3359  // reference the variable in the command line of the VS debugger.
3360  std::string QualifiedName =
3361  (moduleIsInFortran()) ? std::string(DIGV->getName())
3362  : getFullyQualifiedName(Scope, DIGV->getName());
3363 
3364  if (const GlobalVariable *GV =
3365  CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3366  // DataSym record, see SymbolRecord.h for more info. Thread local data
3367  // happens to have the same format as global data.
3368  MCSymbol *GVSym = Asm->getSymbol(GV);
3370  ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3371  : SymbolKind::S_GTHREAD32)
3372  : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3373  : SymbolKind::S_GDATA32);
3374  MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3375  OS.AddComment("Type");
3376  OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
3377  OS.AddComment("DataOffset");
3378 
3379  uint64_t Offset = 0;
3380  if (CVGlobalVariableOffsets.find(DIGV) != CVGlobalVariableOffsets.end())
3381  // Use the offset seen while collecting info on globals.
3382  Offset = CVGlobalVariableOffsets[DIGV];
3383  OS.EmitCOFFSecRel32(GVSym, Offset);
3384 
3385  OS.AddComment("Segment");
3386  OS.EmitCOFFSectionIndex(GVSym);
3387  OS.AddComment("Name");
3388  const unsigned LengthOfDataRecord = 12;
3389  emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
3390  endSymbolRecord(DataEnd);
3391  } else {
3392  const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3393  assert(DIE->isConstant() &&
3394  "Global constant variables must contain a constant expression.");
3395 
3396  // Use unsigned for floats.
3397  bool isUnsigned = isFloatDIType(DIGV->getType())
3398  ? true
3400  APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3401  emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
3402  }
3403 }
llvm::DIScope::getFilename
StringRef getFilename() const
Definition: DebugInfoMetadata.h:642
mapArchToCVCPUType
static CPUType mapArchToCVCPUType(Triple::ArchType Type)
Definition: CodeViewDebug.cpp:123
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
llvm::ClassInfo::MemberInfo::MemberTypeNode
const DIDerivedType * MemberTypeNode
Definition: CodeViewDebug.cpp:2266
llvm::MCStreamer::emitCVInlineLinetableDirective
virtual void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym)
This implements the CodeView '.cv_inline_linetable' assembler directive.
Definition: MCStreamer.cpp:342
llvm::codeview::CPUType::ARM64
@ ARM64
llvm::DIType::getScope
DIScope * getScope() const
Definition: DebugInfoMetadata.h:710
llvm::MachineInstr::isDebugValue
bool isDebugValue() const
Definition: MachineInstr.h:1210
i
i
Definition: README.txt:29
llvm::MachineFunction::hasInlineAsm
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
Definition: MachineFunction.h:714
AsmPrinter.h
llvm::codeview::TypeIndex::isNoneType
bool isNoneType() const
Definition: TypeIndex.h:116
llvm::TargetMachine::getOptLevel
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Definition: TargetMachine.cpp:188
llvm::isAsynchronousEHPersonality
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
Definition: EHPersonalities.h:50
BinaryStreamReader.h
llvm::StringRef::back
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:168
llvm::MachineFrameInfo::hasVarSizedObjects
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
Definition: MachineFrameInfo.h:353
llvm::MCStreamer::emitCVFileChecksumsDirective
virtual void emitCVFileChecksumsDirective()
This implements the CodeView '.cv_filechecksums' assembler directive.
Definition: MCStreamer.h:979
llvm::StringRef::startswith
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:286
llvm::DebugHandlerBase::LScopes
LexicalScopes LScopes
Definition: DebugHandlerBase.h:78
llvm::codeview::MemberAccess
MemberAccess
Source-level access specifier. (CV_access_e)
Definition: CodeView.h:265
getName
static StringRef getName(Value *V)
Definition: ProvenanceAnalysisEvaluator.cpp:42
shouldEmitUdt
static bool shouldEmitUdt(const DIType *T)
Definition: CodeViewDebug.cpp:1565
llvm::DICompositeType::getBaseType
DIType * getBaseType() const
Definition: DebugInfoMetadata.h:1205
llvm::codeview::DefRangeRegisterHeader::MayHaveNoName
ulittle16_t MayHaveNoName
Definition: SymbolRecord.h:481
llvm::DebugHandlerBase::beginInstruction
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
Definition: DebugHandlerBase.cpp:349
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:105
MachineInstr.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:22
llvm::AsmPrinter::getFunctionEnd
MCSymbol * getFunctionEnd() const
Definition: AsmPrinter.h:251
llvm::DIType
Base class for types.
Definition: DebugInfoMetadata.h:665
llvm::DbgVariableLocation::FragmentInfo
llvm::Optional< llvm::DIExpression::FragmentInfo > FragmentInfo
Present if the location is part of a larger variable.
Definition: DebugHandlerBase.h:40
llvm::DebugHandlerBase::getLabelAfterInsn
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
Definition: DebugHandlerBase.cpp:143
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::InlineSite
std::tuple< uint64_t, uint32_t > InlineSite
Definition: MCPseudoProbe.h:89
llvm::NamedMDNode
A tuple of MDNodes.
Definition: Metadata.h:1421
TargetFrameLowering.h
Optional.h
llvm::TargetFrameLowering
Information about stack frame layout on the target.
Definition: TargetFrameLowering.h:43
llvm::MachineFunction::getVariableDbgInfo
VariableDbgInfoMapTy & getVariableDbgInfo()
Definition: MachineFunction.h:1192
Metadata.h
llvm::MachineModuleInfo::getContext
const MCContext & getContext() const
Definition: MachineModuleInfo.h:166
llvm::DIType::getSizeInBits
uint64_t getSizeInBits() const
Definition: DebugInfoMetadata.h:704
dwarfCCToCodeView
static CallingConvention dwarfCCToCodeView(unsigned DwarfCC)
Given a DWARF calling convention, get the CodeView equivalent.
Definition: CodeViewDebug.cpp:1958
llvm::MCStreamer::EmitCVFileDirective
virtual bool EmitCVFileDirective(unsigned FileNo, StringRef Filename, ArrayRef< uint8_t > Checksum, unsigned ChecksumKind)
Associate a filename with a specified logical file number, and also specify that file's checksum info...
Definition: MCStreamer.cpp:286
llvm::sys::path::Style::posix
@ posix
DebugInfoMetadata.h
llvm::Function::hasOptNone
bool hasOptNone() const
Do not optimize this function (-O0).
Definition: Function.h:655
llvm::pdb::PDB_DataKind::Member
@ Member
llvm::GlobalValue::dropLLVMManglingEscape
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:488
llvm::FPOpFusion::Standard
@ Standard
Definition: TargetOptions.h:38
T
llvm::Function
Definition: Function.h:62
llvm::codeview::ModifierOptions
ModifierOptions
Equivalent to CV_modifier_t.
Definition: CodeView.h:304
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::lookup
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:197
llvm::codeview::StringIdRecord
Definition: TypeRecord.h:595
StringRef.h
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
BinaryByteStream.h
llvm::codeview::SymbolKind
SymbolKind
Duplicate copy of the above enum, but using the official CV names.
Definition: CodeView.h:47
llvm::codeview::NestedTypeRecord
Definition: TypeRecord.h:370
llvm::Triple::x86
@ x86
Definition: Triple.h:82
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:632
llvm::AsmPrinter::MAI
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:88
SymbolRecord.h
contains
return AArch64::GPR64RegClass contains(Reg)
llvm::codeview::FunctionOptions
FunctionOptions
Definition: CodeView.h:249
llvm::BinaryStreamWriter
Provides write only access to a subclass of WritableBinaryStream.
Definition: BinaryStreamWriter.h:30
llvm::codeview::DefRangeFramePointerRelHeader
Definition: SymbolRecord.h:525
llvm::MCStreamer::emitInt8
void emitInt8(uint64_t Value)
Definition: MCStreamer.h:717
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1176
Path.h
llvm::codeview::DataSym
Definition: SymbolRecord.h:936
llvm::DIStringType
String type, Fortran CHARACTER(n)
Definition: DebugInfoMetadata.h:839
llvm::codeview::FileChecksumKind
FileChecksumKind
Definition: CodeView.h:566
llvm::LexicalScope
LexicalScope - This class is used to track scope information.
Definition: LexicalScopes.h:44
llvm::MachineFrameInfo::getCVBytesOfCalleeSavedRegisters
unsigned getCVBytesOfCalleeSavedRegisters() const
Returns how many bytes of callee-saved registers the target pushed in the prologue.
Definition: MachineFrameInfo.h:636
llvm::sys::path::is_absolute
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition: Path.cpp:672
llvm::Function::getSubprogram
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1541
ErrorHandling.h
llvm::MachineFunction::exposesReturnsTwice
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
Definition: MachineFunction.h:703
llvm::codeview::TypeRecordMapping
Definition: TypeRecordMapping.h:23
llvm::X86Disassembler::Reg
Reg
All possible values of the reg field in the ModR/M byte.
Definition: X86DisassemblerDecoder.h:462
MCSectionCOFF.h
llvm::GlobalVariable
Definition: GlobalVariable.h:39
llvm::MCStreamer::EmitCOFFSecRel32
virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset)
Emits a COFF section relative relocation.
Definition: MCStreamer.cpp:969
llvm::MCObjectFileInfo::getCOFFDebugSymbolsSection
MCSection * getCOFFDebugSymbolsSection() const
Definition: MCObjectFileInfo.h:331
Error.h
llvm::MachineFrameInfo::getOffsetAdjustment
int getOffsetAdjustment() const
Return the correction for frame offsets.
Definition: MachineFrameInfo.h:562
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
llvm::lltok::APSInt
@ APSInt
Definition: LLToken.h:498
llvm::DIScope::getName
StringRef getName() const
Definition: DebugInfoMetadata.cpp:262
COFF.h
llvm::TargetSubtargetInfo::getRegisterInfo
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Definition: TargetSubtargetInfo.h:124
llvm::MCStreamer::emitCVLinetableDirective
virtual void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart, const MCSymbol *FnEnd)
This implements the CodeView '.cv_linetable' assembler directive.
Definition: MCStreamer.cpp:338
llvm::DebugHandlerBase::PrevInstLoc
DebugLoc PrevInstLoc
Previous instruction's location information.
Definition: DebugHandlerBase.h:67
llvm::codeview::DefRangeSubfieldRegisterHeader::MayHaveNoName
ulittle16_t MayHaveNoName
Definition: SymbolRecord.h:503
llvm::MachineModuleInfo::hasDebugInfo
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition: MachineModuleInfo.h:202
llvm::codeview::SimpleTypeKind
SimpleTypeKind
Definition: TypeIndex.h:27
llvm::TargetRegisterInfo
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Definition: TargetRegisterInfo.h:233
llvm::DILocation
Debug location.
Definition: DebugInfoMetadata.h:1592
true
basic Basic Alias true
Definition: BasicAliasAnalysis.cpp:1886
llvm::codeview::VFTableShapeRecord
Definition: TypeRecord.h:553
llvm::DISubrange::getUpperBound
BoundType getUpperBound() const
Definition: DebugInfoMetadata.cpp:412
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
llvm::MCTargetOptions::Argv0
const char * Argv0
Definition: MCTargetOptions.h:66
Module.h
llvm::reverse
auto reverse(ContainerTy &&C, std::enable_if_t< has_rbegin< ContainerTy >::value > *=nullptr)
Definition: STLExtras.h:357
llvm::MCStreamer::EmitCVInlineSiteIdDirective
virtual bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc, unsigned IAFile, unsigned IALine, unsigned IACol, SMLoc Loc)
Introduces an inline call site id for use with .cv_loc.
Definition: MCStreamer.cpp:297
llvm::DbgVariableLocation::extractFromMachineInstruction
static Optional< DbgVariableLocation > extractFromMachineInstruction(const MachineInstr &Instruction)
Extract a VariableLocation from a MachineInstr.
Definition: DebugHandlerBase.cpp:35
llvm::codeview::BaseClassRecord
Definition: TypeRecord.h:864
llvm::MCStreamer::emitInt32
void emitInt32(uint64_t Value)
Definition: MCStreamer.h:719
llvm::DebugHandlerBase::requestLabelAfterInsn
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
Definition: DebugHandlerBase.h:105
llvm::MCContext::allocate
void * allocate(unsigned Size, unsigned Align=8)
Definition: MCContext.h:807
llvm::MCAsmInfo::getCodePointerSize
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:536
llvm::Optional
Definition: APInt.h:33
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::count
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:145
llvm::MCStreamer::AddBlankLine
virtual void AddBlankLine()
AddBlankLine - Emit a blank line to a .s file to pretty it up.
Definition: MCStreamer.h:363
llvm::MapVector< MDString *, MethodsList >
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:80
llvm::TargetOptions::ObjectFilenameForDebug
std::string ObjectFilenameForDebug
Stores the filename/path of the final .o/.obj file, to be written in the debug information.
Definition: TargetOptions.h:428
llvm::MCStreamer::emitCVLocDirective
virtual void emitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line, unsigned Column, bool PrologueEnd, bool IsStmt, StringRef FileName, SMLoc Loc)
This implements the CodeView '.cv_loc' assembler directive.
Definition: MCStreamer.cpp:311
llvm::DIE
A structured debug information entry.
Definition: DIE.h:739
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:893
llvm::Module::getProfileSummary
Metadata * getProfileSummary(bool IsCS) const
Returns profile summary metadata.
Definition: Module.cpp:644
llvm::codeview::CPUType::X64
@ X64
STLExtras.h
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2608
llvm::dwarf::Tag
Tag
Definition: Dwarf.h:105
llvm::DINode::FlagAccessibility
@ FlagAccessibility
Definition: DebugInfoMetadata.h:170
replace
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New)
Definition: ConstantMerge.cpp:116
llvm::codeview::PointerRecord
Definition: TypeRecord.h:264
llvm::DINode::FlagPtrToMemberRep
@ FlagPtrToMemberRep
Definition: DebugInfoMetadata.h:171
x86
Note that only the low bits of effective_addr2 are used On bit we don t eliminate the computation of the top half of effective_addr2 because we don t have whole function selection dags On x86
Definition: README.txt:318
llvm::detail::DenseSetImpl< ValueT, DenseMap< ValueT, detail::DenseSetEmpty, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::insert
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:205
llvm::codeview::CPUType::ARMNT
@ ARMNT
llvm::detail::DenseSetImpl< ValueT, DenseMap< ValueT, detail::DenseSetEmpty, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::count
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:96
llvm::CodeViewDebug::TypeLoweringScope::TypeLoweringScope
TypeLoweringScope(CodeViewDebug &CVD)
Definition: CodeViewDebug.cpp:316
TRI
unsigned const TargetRegisterInfo * TRI
Definition: MachineSink.cpp:1564
llvm::codeview::DataMemberRecord
Definition: TypeRecord.h:784
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
translatePtrToMemberRep
static PointerToMemberRepresentation translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags)
Definition: CodeViewDebug.cpp:1904
llvm::MCTargetOptions::CommandLineArgs
ArrayRef< std::string > CommandLineArgs
Definition: MCTargetOptions.h:67
llvm::DILexicalBlock
Definition: DebugInfoMetadata.h:2127
EnumTables.h
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::RISCVFenceField::R
@ R
Definition: RISCVBaseInfo.h:208
llvm::MDNode::operands
op_range operands() const
Definition: Metadata.h:1135
llvm::EnumEntry
Definition: ScopedPrinter.h:24
llvm::CodeViewDebug::endFunctionImpl
void endFunctionImpl(const MachineFunction *) override
Gather post-function debug information.
Definition: CodeViewDebug.cpp:3014
llvm::MDNode::getNumOperands
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1143
getStringIdTypeIdx
static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, StringRef S)
Definition: CodeViewDebug.cpp:893
llvm::codeview::ClassOptions::ContainsNestedClass
@ ContainsNestedClass
llvm::classifyEHPersonality
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Definition: EHPersonalities.cpp:21
llvm::DITypeRefArray
Definition: DebugInfoMetadata.h:67
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:185
CommandLine.h
llvm::MCStreamer
Streaming machine code generation interface.
Definition: MCStreamer.h:199
DwarfExpression.h
llvm::formatv
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Definition: FormatVariadic.h:251
llvm::codeview::EncodedFramePtrReg
EncodedFramePtrReg
Two-bit value indicating which register is the designated frame pointer register.
Definition: CodeView.h:541
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::Intrinsic::getType
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
Definition: Function.cpp:1356
llvm::codeview::ArgListRecord
Definition: TypeRecord.h:236
llvm::codeview::ContinuationRecordBuilder::writeMemberType
void writeMemberType(RecordType &Record)
Definition: ContinuationRecordBuilder.cpp:78
llvm::DIType::getFlags
DIFlags getFlags() const
Definition: DebugInfoMetadata.h:708
llvm::codeview::EnumRecord
Definition: TypeRecord.h:519
GlobalValue.h
llvm::DebugHandlerBase::PrologEndLoc
DebugLoc PrologEndLoc
This location indicates end of function prologue and beginning of function body.
Definition: DebugHandlerBase.h:73
TargetMachine.h
llvm::MCSymbol::getSection
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:262
llvm::Triple::ArchType
ArchType
Definition: Triple.h:46
llvm::SMLoc
Represents a location in source code.
Definition: SMLoc.h:23
llvm::DISubrange::getCount
BoundType getCount() const
Definition: DebugInfoMetadata.cpp:370
llvm::N86::ESP
@ ESP
Definition: X86MCTargetDesc.h:51
Constants.h
llvm::codeview::DefRangeRegisterRelHeader::BasePointerOffset
little32_t BasePointerOffset
Definition: SymbolRecord.h:554
llvm::Module::globals
iterator_range< global_iterator > globals()
Definition: Module.h:609
llvm::ClassInfo::NestedTypes
std::vector< const DIType * > NestedTypes
Definition: CodeViewDebug.cpp:2286
SmallString.h
llvm::DILocalVariable
Local variable.
Definition: DebugInfoMetadata.h:3116
llvm::DebugHandlerBase::Asm
AsmPrinter * Asm
Target of debug info emission.
Definition: DebugHandlerBase.h:58
llvm::codeview::CodeViewRecordIO
Definition: CodeViewRecordIO.h:43
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::DebugLoc::getFnDebugLoc
DebugLoc getFnDebugLoc() const
Find the debug info location for the start of the function.
Definition: DebugLoc.cpp:49
llvm::DIGlobalVariable::isLocalToUnit
bool isLocalToUnit() const
Definition: DebugInfoMetadata.h:3032
llvm::SmallVectorImpl::append
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:656
flattenCommandLine
static std::string flattenCommandLine(ArrayRef< std::string > Args, StringRef MainFilename)
Definition: CodeViewDebug.cpp:899
llvm::support::little
@ little
Definition: Endian.h:27
TypeVisitorCallbackPipeline.h
llvm::CodeViewDebug::moduleIsInFortran
bool moduleIsInFortran()
Check if the current module is in Fortran.
Definition: CodeViewDebug.h:478
llvm::MCStreamer::EmitCOFFSectionIndex
virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol)
Emits a COFF section index.
Definition: MCStreamer.cpp:967
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::HighlightColor::Enumerator
@ Enumerator
llvm::codeview::Masm
@ Masm
Definition: CodeView.h:150
Twine.h
llvm::codeview::BitFieldRecord
Definition: TypeRecord.h:535
MCContext.h
llvm::DIType::getLine
unsigned getLine() const
Definition: DebugInfoMetadata.h:703
llvm::MCStreamer::emitLabel
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:415
llvm::codeview::MethodOverloadListRecord
Definition: TypeRecord.h:752
llvm::codeview::PointerOptions
PointerOptions
Equivalent to misc lfPointerAttr bitfields.
Definition: CodeView.h:362
MCSymbol.h
llvm::MDTuple
Tuple of metadata.
Definition: Metadata.h:1174
llvm::codeview::TypeCollection
Definition: TypeCollection.h:18
llvm::DIType::getName
StringRef getName() const
Definition: DebugInfoMetadata.h:711
llvm::pdb::PDB_SymType::UDT
@ UDT
llvm::DISubrange
Array subrange.
Definition: DebugInfoMetadata.h:298
llvm::TargetOptions::MCOptions
MCTargetOptions MCOptions
Machine level options.
Definition: TargetOptions.h:423
FramePtr
static const unsigned FramePtr
Definition: XCoreFrameLowering.cpp:34
llvm::pdb::UInt32
@ UInt32
Definition: PDBTypes.h:404
llvm::codeview::MethodKind
MethodKind
Part of member attribute flags. (CV_methodprop_e)
Definition: CodeView.h:273
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::DIBasicType::getEncoding
unsigned getEncoding() const
Definition: DebugInfoMetadata.h:825
llvm::MachineInstr::FrameSetup
@ FrameSetup
Definition: MachineInstr.h:82
llvm::DebugHandlerBase::requestLabelBeforeInsn
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
Definition: DebugHandlerBase.h:100
translateMethodOptionFlags
static MethodOptions translateMethodOptionFlags(const DISubprogram *SP)
Definition: CodeViewDebug.cpp:2126
llvm::codeview::TypeTableCollection
Definition: TypeTableCollection.h:20
llvm::ClassInfo::Methods
MethodsMap Methods
Definition: CodeViewDebug.cpp:2282
SMLoc.h
llvm::TargetFrameLowering::hasFP
virtual bool hasFP(const MachineFunction &MF) const =0
hasFP - Return true if the specified function should have a dedicated frame pointer register.
LexicalScopes.h
llvm::APSInt
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:22
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
llvm::DbgVariableLocation::Register
unsigned Register
Base register.
Definition: DebugHandlerBase.h:33
Options
const char LLVMTargetMachineRef LLVMPassBuilderOptionsRef Options
Definition: PassBuilderBindings.cpp:48
llvm::ConstantFP
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:257
llvm::Function::hasPersonalityFn
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:775
llvm::MCStreamer::emitCVFileChecksumOffsetDirective
virtual void emitCVFileChecksumOffsetDirective(unsigned FileNo)
This implements the CodeView '.cv_filechecksumoffset' assembler directive.
Definition: MCStreamer.h:983
llvm::CodeViewDebug::TypeLoweringScope
Definition: CodeViewDebug.cpp:315
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:187
llvm::MCObjectFileInfo::getCOFFGlobalTypeHashesSection
MCSection * getCOFFGlobalTypeHashesSection() const
Definition: MCObjectFileInfo.h:337
llvm::codeview::TypeRecordKind
TypeRecordKind
Distinguishes individual records in .debug$T or .debug$P section or PDB type stream.
Definition: CodeView.h:26
llvm::codeview::SimpleTypeKind::UInt32Long
@ UInt32Long
llvm::MachineFrameInfo::getStackSize
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
Definition: MachineFrameInfo.h:553
Info
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
llvm::DbgVariableLocation::LoadChain
SmallVector< int64_t, 1 > LoadChain
Chain of offsetted loads necessary to load the value if it lives in memory.
Definition: DebugHandlerBase.h:37
llvm::codeview::TypeVisitorCallbackPipeline
Definition: TypeVisitorCallbackPipeline.h:21
llvm::codeview::TypeVisitorCallbackPipeline::addCallbackToPipeline
void addCallbackToPipeline(TypeVisitorCallbacks &Callbacks)
Definition: TypeVisitorCallbackPipeline.h:81
llvm::codeview::ModifierRecord
Definition: TypeRecord.h:130
llvm::codeview::DefRangeRegisterHeader::Register
ulittle16_t Register
Definition: SymbolRecord.h:480
llvm::ClassInfo::MemberList
std::vector< MemberInfo > MemberList
Definition: CodeViewDebug.cpp:2270
llvm::codeview::OverloadedMethodRecord
For method overload sets. LF_METHOD.
Definition: TypeRecord.h:765
llvm::codeview::CodeViewRecordStreamer
Definition: CodeViewRecordIO.h:31
llvm::codeview::ClassOptions
ClassOptions
Definition: CodeView.h:206
llvm::Metadata
Root of the metadata hierarchy.
Definition: Metadata.h:62
llvm::Triple::getArch
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:311
FormatVariadic.h
llvm::DebugHandlerBase::getLabelBeforeInsn
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
Definition: DebugHandlerBase.cpp:136
llvm::codeview::MemberFunctionRecord
Definition: TypeRecord.h:171
llvm::MCContext::getAssociativeCOFFSection
MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=GenericSectionID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym.
Definition: MCContext.cpp:668
llvm::codeview::Java
@ Java
Definition: CodeView.h:160
llvm::codeview::visitTypeRecord
Error visitTypeRecord(CVType &Record, TypeIndex Index, TypeVisitorCallbacks &Callbacks, VisitorDataSource Source=VDS_BytesPresent)
Definition: CVTypeVisitor.cpp:218
llvm::MachineModuleInfo::setDebugInfoAvailability
void setDebugInfoAvailability(bool avail)
Definition: MachineModuleInfo.h:203
llvm::None
const NoneType None
Definition: None.h:23
llvm::lltok::Kind
Kind
Definition: LLToken.h:18
llvm::AsmPrinter::getFunctionBegin
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:250
llvm::CodeViewDebug
Collects and handles line tables information in a CodeView format.
Definition: CodeViewDebug.h:52
llvm::CodeViewDebug::beginModule
void beginModule(Module *M) override
Definition: CodeViewDebug.cpp:614
llvm::SmallString< 32 >
llvm::codeview::PointerMode
PointerMode
Equivalent to CV_ptrmode_e.
Definition: CodeView.h:353
llvm::codeview::GlobalTypeTableBuilder::hashes
ArrayRef< GloballyHashedType > hashes() const
Definition: GlobalTypeTableBuilder.cpp:78
Line.h
llvm::MCStreamer::emitBinaryData
virtual void emitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
Definition: MCStreamer.cpp:1193
llvm::DebugHandlerBase::getBaseTypeSize
static uint64_t getBaseTypeSize(const DIType *Ty)
If this type is derived from a base type then return base type size.
Definition: DebugHandlerBase.cpp:148
llvm::DILocalVariable::getScope
DILocalScope * getScope() const
Get the local scope for this variable.
Definition: DebugInfoMetadata.h:3174
llvm::codeview::FrameProcedureOptions
FrameProcedureOptions
Definition: CodeView.h:223
llvm::DbgVariableLocation
Represents the location at which a variable is stored.
Definition: DebugHandlerBase.h:31
needsReferenceType
static bool needsReferenceType(const DbgVariableLocation &Loc)
Definition: CodeViewDebug.cpp:1330
llvm::CodeViewDebug::CodeViewDebug
CodeViewDebug(AsmPrinter *AP)
Definition: CodeViewDebug.cpp:140
llvm::DenseSet
Implements a dense probed hash-table based set.
Definition: DenseSet.h:267
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:641
llvm::codeview::Fortran
@ Fortran
Definition: CodeView.h:149
llvm::codeview::DefRangeSubfieldRegisterHeader
Definition: SymbolRecord.h:501
llvm::Function::hasFnAttribute
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:626
llvm::MCStreamer::emitInt16
void emitInt16(uint64_t Value)
Definition: MCStreamer.h:718
llvm::codeview::DefRangeSubfieldRegisterHeader::Register
ulittle16_t Register
Definition: SymbolRecord.h:502
llvm::codeview::GlobalTypeTableBuilder
Definition: GlobalTypeTableBuilder.h:29
llvm::codeview::TypeIndex::getSimpleKind
SimpleTypeKind getSimpleKind() const
Definition: TypeIndex.h:136
addLocIfNotPresent
static void addLocIfNotPresent(SmallVectorImpl< const DILocation * > &Locs, const DILocation *Loc)
Definition: CodeViewDebug.cpp:506
llvm::codeview::ContinuationRecordBuilder
Definition: ContinuationRecordBuilder.h:33
llvm::DebugHandlerBase::PrevInstBB
const MachineBasicBlock * PrevInstBB
Definition: DebugHandlerBase.h:69
llvm::CodeViewDebug::beginFunctionImpl
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
Definition: CodeViewDebug.cpp:1453
VI
@ VI
Definition: SIInstrInfo.cpp:7695
llvm::sys::path::remove_dots
bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
In-place remove any '.
Definition: Path.cpp:716
llvm::ArrayRef::drop_front
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:202
llvm::ClassInfo
Definition: CodeViewDebug.cpp:2264
llvm::StringRef::empty
constexpr LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:153
llvm::DICompositeType::getElements
DINodeArray getElements() const
Definition: DebugInfoMetadata.h:1206
llvm::DenseMapBase::clear
void clear()
Definition: DenseMap.h:111
llvm::codeview::EnumeratorRecord
Definition: TypeRecord.h:830
llvm::codeview::OneMethodRecord
Definition: TypeRecord.h:720
Index
uint32_t Index
Definition: ELFObjHandler.cpp:83
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
llvm::DIFile::CSK_SHA256
@ CSK_SHA256
Definition: DebugInfoMetadata.h:546
uint64_t
llvm::pdb::Unknown
@ Unknown
Definition: PDBTypes.h:395
llvm::lltok::DwarfCC
@ DwarfCC
Definition: LLToken.h:485
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
llvm::codeview::ContinuationRecordBuilder::begin
void begin(ContinuationRecordKind RecordKind)
Definition: ContinuationRecordBuilder.cpp:51
TypeRecord.h
llvm::MachineFrameInfo::hasStackProtectorIndex
bool hasStackProtectorIndex() const
Definition: MachineFrameInfo.h:358
llvm::MCSectionCOFF::getCOMDATSymbol
MCSymbol * getCOMDATSymbol() const
Definition: MCSectionCOFF.h:67
llvm::codeview::VirtualBaseClassRecord
Definition: TypeRecord.h:885
parseVersion
static Version parseVersion(StringRef Name)
Definition: CodeViewDebug.cpp:822
llvm::DIGlobalVariable
Global variables.
Definition: DebugInfoMetadata.h:2969
QualifiedName
Definition: ItaniumDemangle.h:1020
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::pdb::Int32
@ Int32
Definition: PDBTypes.h:398
llvm::DenseMap
Definition: DenseMap.h:714
llvm::DICompositeType::getIdentifier
StringRef getIdentifier() const
Definition: DebugInfoMetadata.h:1215
llvm::DIGlobalVariable::getRawStaticDataMemberDeclaration
Metadata * getRawStaticDataMemberDeclaration() const
Definition: DebugInfoMetadata.h:3044
llvm::DbgValueHistoryMap::NoEntry
static const EntryIndex NoEntry
Special value to indicate that an entry is valid until the end of the function.
Definition: DbgEntityHistoryCalculator.h:53
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::DebugLoc::get
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
llvm::codeview::SimpleTypeMode
SimpleTypeMode
Definition: TypeIndex.h:82
TypeTableCollection.h
CodeViewRecordIO.h
FuncId
Profile::FuncID FuncId
Definition: Profile.cpp:321
llvm::StackOffset::getScalable
static StackOffset getScalable(ScalarTy Scalable)
Definition: TypeSize.h:144
llvm::codeview::GlobalTypeTableBuilder::writeLeafType
TypeIndex writeLeafType(T &Record)
Definition: GlobalTypeTableBuilder.h:110
llvm::is_contained
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1657
llvm::ClassInfo::Members
MemberList Members
Direct members.
Definition: CodeViewDebug.cpp:2280
llvm::codeview::DefRangeRegisterHeader
Definition: SymbolRecord.h:479
llvm::TargetMachine::Options
TargetOptions Options
Definition: TargetMachine.h:121
llvm::codeview::TypeCollection::empty
bool empty()
Definition: TypeCollection.h:22
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::AsmPrinter::getSymbol
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:494
llvm::MCSectionCOFF
This represents a section on Windows.
Definition: MCSectionCOFF.h:26
TypeDumpVisitor.h
llvm::MCStreamer::emitIntValue
virtual void emitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers.
Definition: MCStreamer.cpp:133
std::swap
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:852
llvm::MachineFunction::getFrameInfo
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Definition: MachineFunction.h:657
llvm::codeview::StaticDataMemberRecord
Definition: TypeRecord.h:809
memcpy
<%struct.s * > cast struct s *S to sbyte *< sbyte * > sbyte uint cast struct s *agg result to sbyte *< sbyte * > sbyte uint cast struct s *memtmp to sbyte *< sbyte * > sbyte uint ret void llc ends up issuing two memcpy or custom lower memcpy(of small size) to be ldmia/stmia. I think option 2 is better but the current register allocator cannot allocate a chunk of registers at a time. A feasible temporary solution is to use specific physical registers at the lowering time for small(<
llvm::GlobalValue::hasLocalLinkage
bool hasLocalLinkage() const
Definition: GlobalValue.h:451
llvm::GlobalValue::isThreadLocal
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:244
llvm::MCObjectFileInfo::getCOFFDebugTypesSection
MCSection * getCOFFDebugTypesSection() const
Definition: MCObjectFileInfo.h:334
llvm::AsmPrinter::MF
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:100
isFloatDIType
static bool isFloatDIType(const DIType *Ty)
Definition: CodeViewDebug.cpp:3331
llvm::MCStreamer::EmitCVFuncIdDirective
virtual bool EmitCVFuncIdDirective(unsigned FunctionId)
Introduces a function id for use with .cv_loc.
Definition: MCStreamer.cpp:293
APSInt.h
Mode
SI Whole Quad Mode
Definition: SIWholeQuadMode.cpp:262
llvm::codeview::RegisterId
RegisterId
Definition: CodeView.h:519
MachineModuleInfo.h
llvm::Record
Definition: Record.h:1485
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
llvm::MDNode
Metadata node.
Definition: Metadata.h:906
llvm::codeview::getSymbolTypeNames
ArrayRef< EnumEntry< SymbolKind > > getSymbolTypeNames()
Definition: EnumTables.cpp:439
TinyPtrVector.h
translateMethodKindFlags
static MethodKind translateMethodKindFlags(const DISubprogram *SP, bool Introduced)
Definition: CodeViewDebug.cpp:2135
llvm::DIVariable::getName
StringRef getName() const
Definition: DebugInfoMetadata.h:2554
llvm::codeview::FuncIdRecord
Definition: TypeRecord.h:610
llvm::GlobalObject::hasComdat
bool hasComdat() const
Definition: GlobalObject.h:122
llvm::DIBasicType
Basic type, like 'int' or 'float'.
Definition: DebugInfoMetadata.h:771
llvm::Record::getType
RecordRecTy * getType()
Definition: Record.cpp:2315
llvm::APInt
Class for arbitrary precision integers.
Definition: APInt.h:75
llvm::MachineFunction
Definition: MachineFunction.h:241
llvm::DINode::getTag
dwarf::Tag getTag() const
Definition: DebugInfoMetadata.h:160
llvm::codeview::DefRangeRegisterRelHeader
Definition: SymbolRecord.h:551
Triple.h
llvm::DISubroutineType::getCC
uint8_t getCC() const
Definition: DebugInfoMetadata.h:1335
llvm::CodeGenOpt::None
@ None
Definition: CodeGen.h:53
llvm::DISubroutineType
Type array for a subprogram.
Definition: DebugInfoMetadata.h:1295
llvm::DICompositeType
Composite types.
Definition: DebugInfoMetadata.h:1072
llvm::DIScope::getScope
DIScope * getScope() const
Definition: DebugInfoMetadata.cpp:238
llvm::InsnRange
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
InsnRange - This is used to track range of instructions with identical lexical scope.
Definition: LexicalScopes.h:39
llvm::COFF::DEBUG_HASHES_SECTION_MAGIC
@ DEBUG_HASHES_SECTION_MAGIC
Definition: COFF.h:727
llvm::codeview::SourceLanguage
SourceLanguage
These values correspond to the CV_CFL_LANG enumeration, and are documented here: https://msdn....
Definition: CodeView.h:146
llvm::codeview::encodeFramePtrReg
EncodedFramePtrReg encodeFramePtrReg(RegisterId Reg, CPUType CPU)
Definition: SymbolRecordMapping.cpp:520
llvm::ArrayRef< uint8_t >
None.h
MCAsmInfo.h
getCommonClassOptions
static ClassOptions getCommonClassOptions(const DICompositeType *Ty)
Return ClassOptions that should be present on both the forward declaration and the defintion of a tag...
Definition: CodeViewDebug.cpp:2168
llvm::codeview::TypeIndex::simpleTypeName
static StringRef simpleTypeName(TypeIndex TI)
Definition: TypeIndex.cpp:70
DataLayout.h
MapDWLangToCVLang
static SourceLanguage MapDWLangToCVLang(unsigned DWLang)
Definition: CodeViewDebug.cpp:574
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
Dwarf.h
llvm::codeview::CVRecord< TypeLeafKind >
llvm::DINode
Tagged DWARF-like metadata node.
Definition: DebugInfoMetadata.h:127
llvm::ClassInfo::MemberInfo::BaseOffset
uint64_t BaseOffset
Definition: CodeViewDebug.cpp:2267
canUseReferenceType
static bool canUseReferenceType(const DbgVariableLocation &Loc)
Definition: CodeViewDebug.cpp:1326
llvm::getTypeName
StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
Definition: TypeName.h:27
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:134
llvm::ConstantInt::isZero
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:194
TargetLoweringObjectFile.h
llvm::Reloc::Static
@ Static
Definition: CodeGen.h:22
llvm::cantFail
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:745
llvm::codeview::UdtSourceLineRecord
Definition: TypeRecord.h:628
uint32_t
llvm::StackOffset
StackOffset is a class to represent an offset with 2 dimensions, named fixed and scalable,...
Definition: TypeSize.h:134
TargetSubtargetInfo.h
llvm::codeview::TypeIndex::getSimpleMode
SimpleTypeMode getSimpleMode() const
Definition: TypeIndex.h:141
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
isNonTrivial
static bool isNonTrivial(const DICompositeType *DCTy)
Definition: CodeViewDebug.cpp:423
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::DIE::get
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
Definition: DIE.h:769
llvm::DIScope::getDirectory
StringRef getDirectory() const
Definition: DebugInfoMetadata.h:648
llvm::codeview::PointerToMemberRepresentation
PointerToMemberRepresentation
Equivalent to CV_pmtype_e.
Definition: CodeView.h:376
llvm::ConstantInt::getSExtValue
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:148
llvm::codeview::ColumnInfo
Definition: Line.h:63
llvm::codeview::Rust
@ Rust
Definition: CodeView.h:165
LLVM_FALLTHROUGH
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:287
llvm::Value::getName
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
llvm::MCContext::createTempSymbol
MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
Definition: MCContext.cpp:303
llvm::CodeViewDebug::beginInstruction
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
Definition: CodeViewDebug.cpp:3067
llvm::DenseMapBase::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:207
llvm::StackOffset::getFixed
static StackOffset getFixed(ScalarTy Fixed)
Definition: TypeSize.h:143
llvm::TargetSubtargetInfo
TargetSubtargetInfo - Generic base class for all target subtargets.
Definition: TargetSubtargetInfo.h:59
llvm::NamedMDNode::operands
iterator_range< op_iterator > operands()
Definition: Metadata.h:1517
llvm::Register
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
llvm::Function::hasOptSize
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:661
llvm::logAllUnhandledErrors
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:61
shouldAlwaysEmitCompleteClassType
static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty)
Definition: CodeViewDebug.cpp:2383
MBB
MachineBasicBlock & MBB
Definition: AArch64SLSHardening.cpp:74
llvm::codeview::ProcedureRecord
Definition: TypeRecord.h:146
llvm::codeview::GlobalTypeTableBuilder::insertRecord
TypeIndex insertRecord(ContinuationRecordBuilder &Builder)
Definition: GlobalTypeTableBuilder.cpp:106
llvm::DIType::isForwardDecl
bool isForwardDecl() const
Definition: DebugInfoMetadata.h:732
llvm::COFF::DEBUG_SECTION_MAGIC
@ DEBUG_SECTION_MAGIC
Definition: COFF.h:726
llvm::DISubrange::getLowerBound
BoundType getLowerBound() const
Definition: DebugInfoMetadata.cpp:391
llvm::dwarf::TypeKind
TypeKind
Definition: Dwarf.h:151
llvm::DITypeRefArray::size
unsigned size() const
Definition: DebugInfoMetadata.h:82
llvm::DIType::getOffsetInBits
uint64_t getOffsetInBits() const
Definition: DebugInfoMetadata.h:707
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:83
llvm::codeview::LineInfo
Definition: Line.h:21
llvm::pdb::PDB_SymType::Label
@ Label
DebugInlineeLinesSubsection.h
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:50
llvm::MachineFunction::getFunction
Function & getFunction()
Return the LLVM function that this machine code represents.
Definition: MachineFunction.h:607
llvm::pdb::PDB_SymType::Inlinee
@ Inlinee
llvm::TargetSubtargetInfo::getFrameLowering
virtual const TargetFrameLowering * getFrameLowering() const
Definition: TargetSubtargetInfo.h:93
llvm::DIScope
Base class for scope-like contexts.
Definition: DebugInfoMetadata.h:476
uint16_t
llvm::codeview::Pascal
@ Pascal
Definition: CodeView.h:151
get
Should compile to something r4 addze r3 instead we get
Definition: README.txt:24
llvm::AMDGPU::HSAMD::Kernel::Arg::Key::TypeName
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
Definition: AMDGPUMetadata.h:170
llvm::codeview::UnionRecord
Definition: TypeRecord.h:498
llvm::LexicalScopes::findInlinedScope
LexicalScope * findInlinedScope(const DILocalScope *N, const DILocation *IA)
findInlinedScope - Find an inlined scope for the given scope/inlined-at.
Definition: LexicalScopes.h:186
MachineFrameInfo.h
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
llvm::TargetFrameLowering::getFrameIndexReference
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
Definition: TargetFrameLoweringImpl.cpp:45
GlobalVariable.h
removeTemplateArgs
static StringRef removeTemplateArgs(StringRef Name)
Definition: CodeViewDebug.cpp:371
llvm::codeview::DefRangeRegisterRelHeader::Flags
ulittle16_t Flags
Definition: SymbolRecord.h:553
Success
#define Success
Definition: AArch64Disassembler.cpp:266
llvm::AArch64CC::LS
@ LS
Definition: AArch64BaseInfo.h:264
llvm::DIVariable::getScope
DIScope * getScope() const
Definition: DebugInfoMetadata.h:2553
llvm::LexicalScopes::findLexicalScope
LexicalScope * findLexicalScope(const DILocation *DL)
findLexicalScope - Find lexical scope, either regular or inlined, for the given DebugLoc.
Definition: LexicalScopes.cpp:124
CVTypeVisitor.h
Casting.h
llvm::MCStreamer::emitCVDefRangeDirective
virtual void emitCVDefRangeDirective(ArrayRef< std::pair< const MCSymbol *, const MCSymbol * >> Ranges, StringRef FixedSizePortion)
This implements the CodeView '.cv_def_range' assembler directive.
Definition: MCStreamer.cpp:360
llvm::DISubroutineType::getTypeArray
DITypeRefArray getTypeArray() const
Definition: DebugInfoMetadata.h:1337
Function.h
llvm::ClassInfo::VShapeTI
TypeIndex VShapeTI
Definition: CodeViewDebug.cpp:2284
llvm::codeview::CPUType
CPUType
These values correspond to the CV_CPU_TYPE_e enumeration, and are documented here: https://msdn....
Definition: CodeView.h:78
llvm::MCStreamer::emitAbsoluteSymbolDiff
virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size)
Emit the absolute difference between two symbols.
Definition: MCStreamer.cpp:1116
llvm::DenseMapBase::size
unsigned size() const
Definition: DenseMap.h:100
llvm::MCStreamer::emitCVStringTableDirective
virtual void emitCVStringTableDirective()
This implements the CodeView '.cv_stringtable' assembler directive.
Definition: MCStreamer.h:976
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1533
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
llvm::AsmPrinter
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:82
llvm::Function::hasProfileData
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
Definition: Function.h:292
llvm::SmallVectorImpl::clear
void clear()
Definition: SmallVector.h:580
llvm::codeview::TypeIndex::getIndex
uint32_t getIndex() const
Definition: TypeIndex.h:111
llvm::DIDerivedType
Derived types.
Definition: DebugInfoMetadata.h:931
llvm::codeview::VFPtrRecord
Definition: TypeRecord.h:851
llvm::Function::getPersonalityFn
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1846
ContinuationRecordBuilder.h
llvm::codeview::BuildInfoRecord
Definition: TypeRecord.h:667
llvm::codeview::MemberFuncIdRecord
Definition: TypeRecord.h:217
llvm::codeview::DebugSubsectionKind
DebugSubsectionKind
Definition: CodeView.h:315
llvm::codeview::DefRangeSubfieldRegisterHeader::OffsetInParent
ulittle32_t OffsetInParent
Definition: SymbolRecord.h:504
llvm::tgtok::Class
@ Class
Definition: TGLexer.h:50
llvm::codeview::Cobol
@ Cobol
Definition: CodeView.h:153
llvm::MCStreamer::EmitCVFPOData
virtual void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc={})
This implements the CodeView '.cv_fpo_data' assembler directive.
Definition: MCStreamer.h:986
llvm::codeview
Definition: AppendingTypeTableBuilder.h:22
llvm::makeArrayRef
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:474
getPrettyScopeName
static StringRef getPrettyScopeName(const DIScope *Scope)
Definition: CodeViewDebug.cpp:264
llvm::TargetRegisterInfo::hasStackRealignment
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
Definition: TargetRegisterInfo.h:936
llvm::codeview::ThunkOrdinal
ThunkOrdinal
These values correspond to the THUNK_ORDINAL enumeration.
Definition: CodeView.h:553
llvm::codeview::LocalSymFlags
LocalSymFlags
Corresponds to CV_LVARFLAGS bitfield.
Definition: CodeView.h:406
isUsableDebugLoc
static bool isUsableDebugLoc(DebugLoc DL)
Definition: CodeViewDebug.cpp:3063
llvm::MachineFrameInfo
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
Definition: MachineFrameInfo.h:107
llvm::CodeViewDebug::TypeLoweringScope::CVD
CodeViewDebug & CVD
Definition: CodeViewDebug.cpp:324
llvm::codeview::Cpp
@ Cpp
Definition: CodeView.h:148
llvm::codeview::TypeIndex::isSimple
bool isSimple() const
Definition: TypeIndex.h:113
llvm::MCStreamer::getContext
MCContext & getContext() const
Definition: MCStreamer.h:280
llvm::AsmPrinter::TM
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:85
Version
uint64_t Version
Definition: RawMemProfReader.cpp:25
llvm::codeview::GlobalTypeTableBuilder::records
ArrayRef< ArrayRef< uint8_t > > records() const
Definition: GlobalTypeTableBuilder.cpp:74
llvm::DIExpression::FragmentInfo::OffsetInBits
uint64_t OffsetInBits
Definition: DebugInfoMetadata.h:2774
llvm::CodeViewDebug::endModule
void endModule() override
Emit the COFF section that holds the line table information.
Definition: CodeViewDebug.cpp:641
llvm::codeview::ArrayRecord
Definition: TypeRecord.h:396
llvm::ClassInfo::MemberInfo
Definition: CodeViewDebug.cpp:2265
Allocator
Basic Register Allocator
Definition: RegAllocBasic.cpp:146
llvm::Module::getTargetTriple
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:255
llvm::codeview::MaxRecordLength
@ MaxRecordLength
Definition: RecordSerialization.h:31
llvm::AsmPrinter::getObjFileLowering
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:223
N
#define N
llvm::DIFile::CSK_MD5
@ CSK_MD5
Definition: DebugInfoMetadata.h:544
MCStreamer.h
Program.h
llvm::ClassInfo::Inheritance
std::vector< const DIDerivedType * > Inheritance
Base classes.
Definition: CodeViewDebug.cpp:2277
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
llvm::Module::getNamedMetadata
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:254
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
llvm::DIFile::CSK_SHA1
@ CSK_SHA1
Definition: DebugInfoMetadata.h:545
llvm::codeview::CallingConvention
CallingConvention
These values correspond to the CV_call_e enumeration, and are documented at the following locations: ...
Definition: CodeView.h:178
llvm::GlobalValue::isDeclarationForLinker
bool isDeclarationForLinker() const
Definition: GlobalValue.h:540
llvm::MCStreamer::isVerboseAsm
virtual bool isVerboseAsm() const
Return true if this streamer supports verbose assembly and if it is enabled.
Definition: MCStreamer.h:319
llvm::LexicalScopes::getCurrentFunctionScope
LexicalScope * getCurrentFunctionScope() const
getCurrentFunctionScope - Return lexical scope for the current function.
Definition: LexicalScopes.h:156
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:662
formatNestedName
static std::string formatNestedName(ArrayRef< StringRef > QualifiedNameComponents, StringRef TypeName)
Definition: CodeViewDebug.cpp:303
llvm::MCStreamer::emitValueToAlignment
virtual void emitValueToAlignment(unsigned ByteAlignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
Definition: MCStreamer.cpp:1202
llvm::DebugHandlerBase::MMI
MachineModuleInfo * MMI
Collected machine module information.
Definition: DebugHandlerBase.h:61
llvm::DebugHandlerBase
Base class for debug information backends.
Definition: DebugHandlerBase.h:53
llvm::MCStreamer::emitBytes
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
Definition: MCStreamer.cpp:1192
llvm::DISubprogram
Subprogram description.
Definition: DebugInfoMetadata.h:1838
llvm::SmallVectorImpl< StringRef >
llvm::codeview::PointerKind
PointerKind
Equivalent to CV_ptrtype_e.
Definition: CodeView.h:336
MachineOperand.h
llvm::codeview::TypeIndex
A 32-bit type reference.
Definition: TypeIndex.h:96
llvm::Module::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:401
BinaryStreamWriter.h
llvm::HexStyle::Asm
@ Asm
0ffh
Definition: MCInstPrinter.h:34
llvm::DataLayout::getPointerSizeInBits
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:412
llvm::MCRegisterInfo::getCodeViewRegNum
int getCodeViewRegNum(MCRegister RegNum) const
Map a target register to an equivalent CodeView register number.
Definition: MCRegisterInfo.cpp:115
llvm::codeview::ClassRecord
Definition: TypeRecord.h:465
llvm::DebugHandlerBase::isUnsignedDIType
static bool isUnsignedDIType(const DIType *Ty)
Return true if type encoding is unsigned.
Definition: DebugHandlerBase.cpp:177
llvm::DebugLoc
A debug info location.
Definition: DebugLoc.h:33
llvm::sys::printArg
void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote)
Print a command argument, and optionally quote it.
Definition: Program.cpp:83
llvm::AMDGPU::HSAMD::Kernel::Key::Args
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Definition: AMDGPUMetadata.h:389
llvm::DebugHandlerBase::DbgValues
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
Definition: DebugHandlerBase.h:82
emitNullTerminatedSymbolName
static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, unsigned MaxFixedRecordLength=0xF00)
Definition: CodeViewDebug.cpp:713
llvm::TinyPtrVector
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:30
llvm::MachineFunction::VariableDbgInfo
Definition: MachineFunction.h:394
MachineFunction.h
getSymbolName
static StringRef getSymbolName(SymbolKind SymKind)
Definition: CodeViewDebug.cpp:3114
Endian.h
llvm::pdb::PDB_SymType::Block
@ Block
llvm::DIType::isObjectPointer
bool isObjectPointer() const
Definition: DebugInfoMetadata.h:736
llvm::codeview::MemberPointerInfo
Definition: TypeRecord.h:100
llvm::MCStreamer::SwitchSection
virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
Definition: MCStreamer.cpp:1215
llvm::codeview::DefRangeRegisterRelHeader::Register
ulittle16_t Register
Definition: SymbolRecord.h:552
getRecordKind
static TypeRecordKind getRecordKind(const DICompositeType *Ty)
Definition: CodeViewDebug.cpp:2155
CU
Definition: AArch64AsmBackend.cpp:504
llvm::MachineModuleInfo::getModule
const Module * getModule() const
Definition: MachineModuleInfo.h:173
llvm::codeview::DefRangeFramePointerRelHeader::Offset
little32_t Offset
Definition: SymbolRecord.h:526
llvm::codeview::CPUType::Pentium3
@ Pentium3
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
translateAccessFlags
static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags)
Definition: CodeViewDebug.cpp:2113
TargetRegisterInfo.h
File
Instrumentation for Order File
Definition: InstrOrderFile.cpp:205
CodeViewDebug.h
llvm::codeview::ClassOptions::Nested
@ Nested
llvm::DIVariable::getType
DIType * getType() const
Definition: DebugInfoMetadata.h:2556
llvm::MCStreamer::AddComment
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition: MCStreamer.h:342
llvm::DIScope::getFile
DIFile * getFile() const
Definition: DebugInfoMetadata.h:484
llvm::DIFile
File.
Definition: DebugInfoMetadata.h:530
llvm::codeview::Swift
@ Swift
Definition: CodeView.h:170
getFunctionOptions
static FunctionOptions getFunctionOptions(const DISubroutineType *Ty, const DICompositeType *ClassTy=nullptr, StringRef SPName=StringRef(""))
Definition: CodeViewDebug.cpp:428
llvm::CodeViewDebug::TypeLoweringScope::~TypeLoweringScope
~TypeLoweringScope()
Definition: CodeViewDebug.cpp:317
llvm::SmallVectorImpl::emplace_back
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:916
llvm::codeview::MethodOptions
MethodOptions
Equivalent to CV_fldattr_t bitfield.
Definition: CodeView.h:284
llvm::TargetOptions::Hotpatch
unsigned Hotpatch
Emit the hotpatch flag in CodeView debug.
Definition: TargetOptions.h:346
ScopedPrinter.h