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