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