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