1//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===// 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 7//===----------------------------------------------------------------------===// 9// This file contains support for writing Microsoft CodeView debug info. 11//===----------------------------------------------------------------------===// 33#include "llvm/Config/llvm-config.h" 81 :
OS(&
OS), TypeTable(TypeTable) {}
103TypeName = std::string(TypeTable.getTypeName(TI));
116case Triple::ArchType::x86:
117return CPUType::Pentium3;
118case Triple::ArchType::x86_64:
120case Triple::ArchType::thumb:
121// LLVM currently doesn't support Windows CE and so thumb 122// here is indiscriminately mapped to ARMNT specifically. 123return CPUType::ARMNT;
124case Triple::ArchType::aarch64:
125return CPUType::ARM64;
126case Triple::ArchType::mipsel:
137 std::string &Filepath = FileToFilepathMap[File];
138if (!Filepath.empty())
141StringRef Dir = File->getDirectory(), Filename = File->getFilename();
143// If this is a Unix-style path, just use it as is. Don't try to canonicalize 144// it textually because one of the path components could be a symlink. 145if (Dir.
starts_with(
"/") || Filename.starts_with(
"/")) {
148 Filepath = std::string(Dir);
151 Filepath += Filename;
155// Clang emits directory and relative filename info into the IR, but CodeView 156// operates on full paths. We could change Clang to emit full paths too, but 157// that would increase the IR size and probably not needed for other users. 158// For now, just concatenate and canonicalize the path here. 159if (Filename.find(
':') == 1)
160 Filepath = std::string(Filename);
162 Filepath = (Dir +
"\\" + Filename).str();
164// Canonicalize the path. We have to do it textually because we may no longer 165// have access the file in the filesystem. 166// First, replace all slashes with backslashes. 167 std::replace(Filepath.begin(), Filepath.end(),
'/',
'\\');
169// Remove all "\.\" with "\". 171while ((Cursor = Filepath.find(
"\\.\\", Cursor)) != std::string::npos)
172 Filepath.erase(Cursor, 2);
174// Replace all "\XXX\..\" with "\". Don't try too hard though as the original 175// path should be well-formatted, e.g. start with a drive letter, etc. 177while ((Cursor = Filepath.find(
"\\..\\", Cursor)) != std::string::npos) {
178// Something's wrong if the path starts with "\..\", abort. 182size_t PrevSlash = Filepath.rfind(
'\\', Cursor - 1);
183if (PrevSlash == std::string::npos)
184// Something's wrong, abort. 187 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
188// The next ".." might be following the one we've just erased. 192// Remove all duplicate backslashes. 194while ((Cursor = Filepath.find(
"\\\\", Cursor)) != std::string::npos)
195 Filepath.erase(Cursor, 1);
200unsigned CodeViewDebug::maybeRecordFile(
constDIFile *
F) {
202unsigned NextId = FileIdMap.
size() + 1;
203auto Insertion = FileIdMap.
insert(std::make_pair(FullPath, NextId));
204if (Insertion.second) {
205// We have to compute the full filepath and emit a .cv_file directive. 208if (
F->getChecksum()) {
209 std::string Checksum = fromHex(
F->getChecksum()->Value);
211 memcpy(CKMem, Checksum.data(), Checksum.size());
213reinterpret_cast<constuint8_t *
>(CKMem), Checksum.size());
214switch (
F->getChecksum()->Kind) {
216 CSKind = FileChecksumKind::MD5;
219 CSKind = FileChecksumKind::SHA1;
222 CSKind = FileChecksumKind::SHA256;
227static_cast<unsigned>(CSKind));
231return Insertion.first->second;
234CodeViewDebug::InlineSite &
235CodeViewDebug::getInlineSite(
constDILocation *InlinedAt,
237auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt,
InlineSite()});
238InlineSite *Site = &SiteInsertion.first->second;
239if (SiteInsertion.second) {
240unsigned ParentFuncId = CurFn->FuncId;
241if (
constDILocation *OuterIA = InlinedAt->getInlinedAt())
243 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
246 Site->SiteFuncId = NextFuncId++;
248 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
249 InlinedAt->getLine(), InlinedAt->getColumn(),
SMLoc());
251 InlinedSubprograms.insert(Inlinee);
252auto InlineeIdx = getFuncIdForSubprogram(Inlinee);
254if (InlinedAt->getInlinedAt() ==
nullptr)
255 CurFn->Inlinees.insert(InlineeIdx);
262if (!ScopeName.
empty())
265switch (Scope->getTag()) {
266case dwarf::DW_TAG_enumeration_type:
267case dwarf::DW_TAG_class_type:
268case dwarf::DW_TAG_structure_type:
269case dwarf::DW_TAG_union_type:
270return"<unnamed-tag>";
271case dwarf::DW_TAG_namespace:
272return"`anonymous namespace'";
278constDISubprogram *CodeViewDebug::collectParentScopeNames(
281while (Scope !=
nullptr) {
282if (ClosestSubprogram ==
nullptr)
283 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
285// If a type appears in a scope chain, make sure it gets emitted. The 286// frontend will be responsible for deciding if this should be a forward 287// declaration or a complete type. 288if (
constauto *Ty = dyn_cast<DICompositeType>(Scope))
289 DeferredCompleteTypes.push_back(Ty);
292if (!ScopeName.
empty())
293 QualifiedNameComponents.
push_back(ScopeName);
296return ClosestSubprogram;
301 std::string FullyQualifiedName;
304 FullyQualifiedName.append(std::string(QualifiedNameComponent));
305 FullyQualifiedName.append(
"::");
307 FullyQualifiedName.append(std::string(TypeName));
308return FullyQualifiedName;
314// Don't decrement TypeEmissionLevel until after emitting deferred types, so 315// inner TypeLoweringScopes don't attempt to emit deferred types. 316if (
CVD.TypeEmissionLevel == 1)
317CVD.emitDeferredCompleteTypes();
318 --
CVD.TypeEmissionLevel;
323std::string CodeViewDebug::getFullyQualifiedName(
constDIScope *Scope,
325// Ensure types in the scope chain are emitted as soon as possible. 326// This can create otherwise a situation where S_UDTs are emitted while 327// looping in emitDebugInfoForUDTs. 330 collectParentScopeNames(Scope, QualifiedNameComponents);
334std::string CodeViewDebug::getFullyQualifiedName(
constDIScope *Ty) {
340// No scope means global scope and that uses the zero index. 342// We also use zero index when the scope is a DISubprogram 343// to suppress the emission of LF_STRING_ID for the function, 344// which can trigger a link-time error with the linker in 345// VS2019 version 16.11.2 or newer. 346// Note, however, skipping the debug info emission for the DISubprogram 347// is a temporary fix. The root issue here is that we need to figure out 348// the proper way to encode a function nested in another function 349// (as introduced by the Fortran 'contains' keyword) in CodeView. 350if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
353assert(!isa<DIType>(Scope) &&
"shouldn't make a namespace scope for a type");
355// Check if we've already translated this scope. 356autoI = TypeIndices.find({Scope,
nullptr});
357if (
I != TypeIndices.end())
360// Build the fully qualified name of the scope. 361 std::string ScopeName = getFullyQualifiedName(Scope);
364return recordTypeIndexForDINode(Scope, TI);
368// Remove template args from the display name. Assume that the template args 369// are the last thing in the name. 370if (
Name.empty() ||
Name.back() !=
'>')
374for (
int i =
Name.size() - 1; i >= 0; --i) {
377elseif (
Name[i] ==
'<') {
379if (OpenBrackets == 0)
380returnName.substr(0, i);
389// Check if we've already translated this subprogram. 390autoI = TypeIndices.find({SP,
nullptr});
391if (
I != TypeIndices.end())
394// The display name includes function template arguments. Drop them to match 395// MSVC. We need to have the template arguments in the DISubprogram name 396// because they are used in other symbol records, such as S_GPROC32_IDs. 401if (
constauto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
402// If the scope is a DICompositeType, then this must be a method. Member 403// function types take some special handling, and require access to the 405TypeIndex ClassType = getTypeIndex(Class);
410// Otherwise, this must be a free function. 411TypeIndex ParentScope = getScopeIndex(Scope);
416return recordTypeIndexForDINode(SP, TI);
420return ((DCTy->
getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
428constDIType *ReturnTy =
nullptr;
431 ReturnTy = TypeArray[0];
434// Add CxxReturnUdt option to functions that return nontrivial record types 435// or methods that return record types. 436if (
auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
438 FO |= FunctionOptions::CxxReturnUdt;
440// DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison. 441if (ClassTy &&
isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
442 FO |= FunctionOptions::Constructor;
444// TODO: put the FunctionOptions::ConstructorWithVirtualBases flag. 452// Always use the method declaration as the key for the function type. The 453// method declaration contains the this adjustment. 454if (SP->getDeclaration())
455 SP = SP->getDeclaration();
456assert(!SP->getDeclaration() &&
"should use declaration as key");
458// Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide 459// with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. 460autoI = TypeIndices.find({SP,
Class});
461if (
I != TypeIndices.end())
464// Make sure complete type info for the class is emitted *after* the member 465// function type, as the complete class type is likely to reference this 466// member function type. 467 TypeLoweringScope S(*
this);
468constbool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
472 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
473return recordTypeIndexForDINode(SP, TI, Class);
479auto InsertResult = TypeIndices.insert({{
Node, ClassTy}, TI});
481assert(InsertResult.second &&
"DINode was already assigned a type index");
485unsigned CodeViewDebug::getPointerSizeInBytes() {
489void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
492// This variable was inlined. Associate it with the InlineSite. 494InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
495 Site.InlinedLocals.emplace_back(std::move(Var));
497// This variable goes into the corresponding lexical scope. 498 ScopeVariables[
LS].emplace_back(std::move(Var));
508void CodeViewDebug::maybeRecordLocation(
constDebugLoc &
DL,
510// Skip this instruction if it has the same location as the previous one. 518// Skip this line if it is longer than the maximum we can record. 519LineInfo LI(
DL.getLine(),
DL.getLine(),
/*IsStatement=*/true);
520if (LI.getStartLine() !=
DL.getLine() || LI.isAlwaysStepInto() ||
521 LI.isNeverStepInto())
525if (CI.getStartColumn() !=
DL.getCol())
528if (!CurFn->HaveLineInfo)
529 CurFn->HaveLineInfo =
true;
532 FileId = CurFn->LastFileId;
534 FileId = CurFn->LastFileId = maybeRecordFile(
DL->getFile());
537unsignedFuncId = CurFn->FuncId;
541// If this location was actually inlined from somewhere else, give it the ID 542// of the inline call site. 544 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
546// Ensure we have links in the tree of inline call sites. 548while ((SiteLoc = Loc->getInlinedAt())) {
550 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
560/*PrologueEnd=*/false,
/*IsStmt=*/false,
564void CodeViewDebug::emitCodeViewMagicVersion() {
572case dwarf::DW_LANG_C:
573case dwarf::DW_LANG_C89:
574case dwarf::DW_LANG_C99:
575case dwarf::DW_LANG_C11:
576return SourceLanguage::C;
577case dwarf::DW_LANG_C_plus_plus:
578case dwarf::DW_LANG_C_plus_plus_03:
579case dwarf::DW_LANG_C_plus_plus_11:
580case dwarf::DW_LANG_C_plus_plus_14:
581return SourceLanguage::Cpp;
582case dwarf::DW_LANG_Fortran77:
583case dwarf::DW_LANG_Fortran90:
584case dwarf::DW_LANG_Fortran95:
585case dwarf::DW_LANG_Fortran03:
586case dwarf::DW_LANG_Fortran08:
587return SourceLanguage::Fortran;
588case dwarf::DW_LANG_Pascal83:
589return SourceLanguage::Pascal;
590case dwarf::DW_LANG_Cobol74:
591case dwarf::DW_LANG_Cobol85:
592return SourceLanguage::Cobol;
593case dwarf::DW_LANG_Java:
594return SourceLanguage::Java;
595case dwarf::DW_LANG_D:
596return SourceLanguage::D;
597case dwarf::DW_LANG_Swift:
598return SourceLanguage::Swift;
599case dwarf::DW_LANG_Rust:
600return SourceLanguage::Rust;
601case dwarf::DW_LANG_ObjC:
602return SourceLanguage::ObjC;
603case dwarf::DW_LANG_ObjC_plus_plus:
604return SourceLanguage::ObjCpp;
606// There's no CodeView representation for this language, and CV doesn't 607// have an "unknown" option for the language field, so we'll use MASM, 608// as it's very low level. 609return SourceLanguage::Masm;
614// If module doesn't have named metadata anchors or COFF debug section 615// is not available, skip any debug info related stuff. 624// Get the current source language. 625constMDNode *Node = *M->debug_compile_units_begin();
626constauto *
CU = cast<DICompileUnit>(Node);
630 collectGlobalVariableInfo();
632// Check if we should emit type record hashes. 634 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(
"CodeViewGHash"));
635 EmitDebugGlobalHashes = GH && !GH->
isZero();
642// The COFF .debug$S section consists of several subsections, each starting 643// with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 644// of the payload followed by the payload itself. The subsections are 4-byte 647// Use the generic .debug$S section, and make a subsection for all the inlined 649 switchToDebugSectionForSymbol(
nullptr);
651MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
653 emitCompilerInformation();
654 endCVSubsection(CompilerInfo);
656 emitInlineeLinesSubsection();
658// Emit per-function debug information. 659for (
auto &
P : FnDebugInfo)
660if (!
P.first->isDeclarationForLinker())
661 emitDebugInfoForFunction(
P.first, *
P.second);
663// Get types used by globals without emitting anything. 664// This is meant to collect all static const data members so they can be 665// emitted as globals. 666 collectDebugInfoForGlobals();
668// Emit retained types. 669 emitDebugInfoForRetainedTypes();
671// Emit global variable debug information. 672 setCurrentSubprogram(
nullptr);
673 emitDebugInfoForGlobals();
675// Switch back to the generic .debug$S section after potentially processing 676// comdat symbol sections. 677 switchToDebugSectionForSymbol(
nullptr);
679// Emit UDT records for any types used by global variables. 680if (!GlobalUDTs.empty()) {
681MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
682 emitDebugInfoForUDTs(GlobalUDTs);
683 endCVSubsection(SymbolsEnd);
686// This subsection holds a file index to offset in string table table. 687 OS.
AddComment(
"File index to string table offset subsection");
690// This subsection holds the string table. 694// Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol 695// subsection in the generic .debug$S section at the end. There is no 696// particular reason for this ordering other than to match MSVC. 699// Emit type information and hashes last, so that any types we translate while 700// emitting function info are included. 701 emitTypeInformation();
703if (EmitDebugGlobalHashes)
704 emitTypeGlobalHashes();
711unsigned MaxFixedRecordLength = 0xF00) {
712// The maximum CV record length is 0xFF00. Most of the strings we emit appear 713// after a fixed length portion of the record. The fixed length portion should 714// always be less than 0xF00 (3840) bytes, so truncate the string so that the 715// overall record size is less than the maximum allowed. 719OS.emitBytes(NullTerminatedString);
722void CodeViewDebug::emitTypeInformation() {
723if (TypeTable.
empty())
726// Start the .debug$T or .debug$P section with 0x4. 728 emitCodeViewMagicVersion();
733// To emit type record using Codeview MCStreamer adapter 734 CVMCAdapter CVMCOS(OS, Table);
738 std::optional<TypeIndex>
B = Table.getFirst();
740// This will fail if the record data is invalid. 750B = Table.getNext(*
B);
754void CodeViewDebug::emitTypeGlobalHashes() {
755if (TypeTable.
empty())
758// Start the .debug$H section with the version and hash algorithm, currently 759// hardcoded to version 0, SHA1. 771for (
constauto &GHR : TypeTable.
hashes()) {
773// Emit an EOL-comment describing which TypeIndex this hash corresponds 774// to, as well as the stringified SHA1 hash. 781assert(GHR.Hash.size() == 8);
782StringRef S(
reinterpret_cast<constchar *
>(GHR.Hash.data()),
788void CodeViewDebug::emitObjName() {
789MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
794if (PathRef.empty() || PathRef ==
"-") {
795// Don't emit the filename if we're writing to stdout or to /dev/null. 807 endSymbolRecord(CompilerEnd);
814}
// end anonymous namespace 816// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out 817// the version number. 821for (
constcharC :
Name) {
826 std::min<int>(V.Part[
N], std::numeric_limits<uint16_t>::max());
837void CodeViewDebug::emitCompilerInformation() {
838MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
841// The low byte of the flags indicates the source language. 842Flags = CurrentSourceLanguage;
843// TODO: Figure out which other flags need to be set. 850 Arch == ArchType::aarch64) {
862constauto *
CU = cast<DICompileUnit>(
Node);
867for (
intN : FrontVer.Part) {
871// Some Microsoft tools, like Binscope, expect a backend version number of at 872// least 8.something, so we'll coerce the LLVM version into a form that 873// guarantees it'll be big enough without really lying about the version. 874int Major = 1000 * LLVM_VERSION_MAJOR +
875 10 * LLVM_VERSION_MINOR +
877// Clamp it for builds that use unusually large version numbers. 878 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
879Version BackVer = {{ Major, 0, 0, 0 }};
881for (
intN : BackVer.Part)
884 OS.
AddComment(
"Null-terminated compiler version string");
887 endSymbolRecord(CompilerEnd);
896void CodeViewDebug::emitBuildInfo() {
897// First, make LF_BUILDINFO. It's a sequence of strings with various bits of 898// build info. The known prefix is: 899// - Absolute path of current directory 901// - Main source file path, relative to CWD or absolute 902// - Type server PDB file 903// - Canonical compiler command line 904// If frontend and backend compilation are separated (think llc or LTO), it's 905// not clear if the compiler path should refer to the executable for the 906// frontend or the backend. Leave it blank for now. 910constauto *
CU = cast<DICompileUnit>(
Node);
911constDIFile *MainSourceFile =
CU->getFile();
916// FIXME: PDB is intentionally blank unless we implement /Zi type servers. 927// Make a new .debug$S subsection for the S_BUILDINFO record, which points 928// from the module symbols into the type stream. 929MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
930MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
933 endSymbolRecord(BIEnd);
934 endCVSubsection(BISubsecEnd);
937void CodeViewDebug::emitInlineeLinesSubsection() {
938if (InlinedSubprograms.empty())
942MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
944// We emit the checksum info for files. This is used by debuggers to 945// determine if a pdb matches the source before loading it. Visual Studio, 946// for instance, will display a warning that the breakpoints are not valid if 947// the pdb does not match the source. 949 OS.
emitInt32(
unsigned(InlineeLinesSignature::Normal));
952assert(TypeIndices.count({SP, nullptr}));
953TypeIndex InlineeIdx = TypeIndices[{SP,
nullptr}];
956unsigned FileId = maybeRecordFile(SP->
getFile());
960 OS.
AddComment(
"Type index of inlined function");
962 OS.
AddComment(
"Offset into filechecksum table");
968 endCVSubsection(InlineEnd);
971void CodeViewDebug::emitInlinedCallSite(
const FunctionInfo &FI,
974assert(TypeIndices.count({Site.Inlinee, nullptr}));
975TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee,
nullptr}];
978MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
987unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
988unsigned StartLineNum = Site.Inlinee->getLine();
993 endSymbolRecord(InlineEnd);
995 emitLocalVariableList(FI, Site.InlinedLocals);
997// Recurse on child inlined call sites before closing the scope. 998for (
constDILocation *ChildSite : Site.ChildSites) {
999autoI = FI.InlineSites.find(ChildSite);
1000assert(
I != FI.InlineSites.end() &&
1001"child site not in function inline site map");
1002 emitInlinedCallSite(FI, ChildSite,
I->second);
1006 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
1009void CodeViewDebug::switchToDebugSectionForSymbol(
constMCSymbol *GVSym) {
1010// If we have a symbol, it may be in a section that is COMDAT. If so, find the 1011// comdat key. A section may be comdat because of -ffunction-sections or 1012// because it is comdat in the IR. 1014 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->
getSection()) : nullptr;
1023// Emit the magic version number if this is the first time we've switched to 1025if (ComdatDebugSections.insert(DebugSec).second)
1026 emitCodeViewMagicVersion();
1029// Emit an S_THUNK32/S_END symbol pair for a thunk routine. 1030// The only supported thunk ordinal is currently the standard type. 1031void CodeViewDebug::emitDebugInfoForThunk(
constFunction *GV,
1034 std::string FuncName =
1036constThunkOrdinal ordinal = ThunkOrdinal::Standard;
// Only supported kind. 1039MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1042MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
1049 OS.
AddComment(
"Thunk section relative address");
1059// Additional fields specific to the thunk ordinal would go here. 1060 endSymbolRecord(ThunkRecordEnd);
1062// Local variables/inlined routines are purposely omitted here. The point of 1063// marking this as a thunk is so Visual Studio will NOT stop in this routine. 1065// Emit S_PROC_ID_END 1066 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1068 endCVSubsection(SymbolsEnd);
1071void CodeViewDebug::emitDebugInfoForFunction(
constFunction *GV,
1073// For each function there is a separate subsection which holds the PC to 1078// Switch to the to a comdat section, if appropriate. 1079 switchToDebugSectionForSymbol(Fn);
1081 std::string FuncName;
1084 setCurrentSubprogram(SP);
1087 emitDebugInfoForThunk(GV, FI, Fn);
1091// If we have a display name, build the fully qualified name by walking the 1096// If our DISubprogram name is empty, use the mangled name. 1097if (FuncName.empty())
1100// Emit FPO data, but only on 32-bit x86. No other platforms use it. 1104// Emit a symbol subsection, required by VS2012+ to find function boundaries. 1106MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1109 : SymbolKind::S_GPROC32_ID;
1110MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1112// These fields are filled in by tools like CVPACK which run after the fact. 1119// This is the important bit that tells the debugger where the function 1120// code is located and what's its size: 1129 OS.
AddComment(
"Function section relative address");
1134ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo;
1135if (FI.HasFramePointer)
1136 ProcFlags |= ProcSymFlags::HasFP;
1138 ProcFlags |= ProcSymFlags::IsNoReturn;
1140 ProcFlags |= ProcSymFlags::IsNoInline;
1142// Emit the function display name as a null-terminated string. 1144// Truncate the name so we won't overflow the record length field. 1146 endSymbolRecord(ProcRecordEnd);
1148MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1149// Subtract out the CSR size since MSVC excludes that and we include it. 1151 OS.
emitInt32(FI.FrameSize - FI.CSRSize);
1156 OS.
AddComment(
"Bytes of callee saved registers");
1162 OS.
AddComment(
"Flags (defines frame register)");
1164 endSymbolRecord(FrameProcEnd);
1166 emitInlinees(FI.Inlinees);
1167 emitLocalVariableList(FI, FI.Locals);
1168 emitGlobalVariableList(FI.Globals);
1169 emitLexicalBlockList(FI.ChildBlocks, FI);
1171// Emit inlined call site information. Only emit functions inlined directly 1172// into the parent function. We'll emit the other sites recursively as part 1173// of their parent inline site. 1174for (
constDILocation *InlinedAt : FI.ChildSites) {
1175autoI = FI.InlineSites.find(InlinedAt);
1176assert(
I != FI.InlineSites.end() &&
1177"child site not in function inline site map");
1178 emitInlinedCallSite(FI, InlinedAt,
I->second);
1181for (
auto Annot : FI.Annotations) {
1183MDTuple *Strs = cast<MDTuple>(Annot.second);
1184MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1186// FIXME: Make sure we don't overflow the max record size. 1190// MDStrings are null terminated, so we can do EmitBytes and get the 1191// nice .asciz directive. 1192StringRef Str = cast<MDString>(MD)->getString();
1193assert(Str.data()[Str.size()] ==
'\0' &&
"non-nullterminated MDString");
1196 endSymbolRecord(AnnotEnd);
1199for (
auto HeapAllocSite : FI.HeapAllocSites) {
1200constMCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1201constMCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1202constDIType *DITy = std::get<2>(HeapAllocSite);
1203MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1211 OS.
emitInt32(getCompleteTypeIndex(DITy).getIndex());
1212 endSymbolRecord(HeapAllocEnd);
1216 emitDebugInfoForUDTs(LocalUDTs);
1218 emitDebugInfoForJumpTables(FI);
1220// We're done with this function. 1221 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1223 endCVSubsection(SymbolsEnd);
1225// We have an assembler directive that takes care of the whole line table. 1236 DR.StructOffset = 0;
1237 DR.CVRegister = CVRegister;
1241void CodeViewDebug::collectVariableInfoFromMFTable(
1252assert(
VI.Var->isValidLocationForIntrinsic(
VI.Loc) &&
1253"Expected inlined-at fields to agree");
1255 Processed.
insert(InlinedEntity(
VI.Var,
VI.Loc->getInlinedAt()));
1258// If variable scope is not found then skip this variable. 1262// If the variable has an attached offset expression, extract it. 1263// FIXME: Try to handle DW_OP_deref as well. 1264 int64_t ExprOffset = 0;
1267// If there is one DW_OP_deref element, use offset of 0 and keep going. 1268if (
VI.Expr->getNumElements() == 1 &&
1269VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1271elseif (!
VI.Expr->extractIfOffset(ExprOffset))
1275// Get the frame register used and the offset. 1282"Frame offsets with a scalable component are not supported");
1284// Calculate the label ranges. 1285 LocalVarDef DefRange =
1286 createDefRangeMem(CVReg, FrameOffset.
getFixed() + ExprOffset);
1295 Var.DefRanges[DefRange].emplace_back(Begin,
End);
1299 Var.UseReferenceType =
true;
1301 recordLocalVariable(std::move(Var), Scope);
1313void CodeViewDebug::calculateRanges(
1317// Calculate the definition ranges. 1318for (
autoI = Entries.begin(), E = Entries.end();
I != E; ++
I) {
1320if (!
Entry.isDbgValue())
1324// FIXME: Find a way to represent constant variables, since they are 1325// relatively common. 1326 std::optional<DbgVariableLocation>
Location =
1330// When we don't have a location this is usually because LLVM has 1331// transformed it into a constant and we only have an llvm.dbg.value. We 1332// can't represent these well in CodeView since S_LOCAL only works on 1333// registers and memory locations. Instead, we will pretend this to be a 1334// constant value to at least have it show up in the debugger. 1341// CodeView can only express variables in register and variables in memory 1342// at a constant offset from a register. However, for variables passed 1343// indirectly by pointer, it is common for that pointer to be spilled to a 1344// stack location. For the special case of one offseted load followed by a 1345// zero offset load (a pointer spilled to the stack), we change the type of 1346// the local variable from a value type to a reference type. This tricks the 1347// debugger into doing the load for us. 1348if (Var.UseReferenceType) {
1349// We're using a reference type. Drop the last zero offset load. 1355// This location can't be expressed without switching to a reference type. 1356// Start over using that. 1357 Var.UseReferenceType =
true;
1358 Var.DefRanges.clear();
1359 calculateRanges(Var, Entries);
1363// We can only handle a register or an offseted load of a register. 1367// Codeview can only express byte-aligned offsets, ensure that we have a 1368// byte-boundaried location. 1370if (
Location->FragmentInfo->OffsetInBits % 8)
1374 DR.CVRegister =
TRI->getCodeViewRegNum(
Location->Register);
1375 DR.InMemory = !
Location->LoadChain.empty();
1379 DR.IsSubfield =
true;
1380 DR.StructOffset =
Location->FragmentInfo->OffsetInBits / 8;
1382 DR.IsSubfield =
false;
1383 DR.StructOffset = 0;
1386// Compute the label range. 1390auto &EndingEntry = Entries[
Entry.getEndIndex()];
1391End = EndingEntry.isDbgValue()
1397// If the last range end is our begin, just extend the last range. 1398// Otherwise make a new range. 1401if (!
R.empty() &&
R.back().second == Begin)
1402R.back().second =
End;
1404R.emplace_back(Begin,
End);
1406// FIXME: Do more range combining. 1410void CodeViewDebug::collectVariableInfo(
constDISubprogram *SP) {
1412// Grab the variable info that was squirreled away in the MMI side-table. 1413 collectVariableInfoFromMFTable(Processed);
1416 InlinedEntity
IV =
I.first;
1422// Instruction ranges, specifying where IV is accessible. 1423constauto &Entries =
I.second;
1430// If variable scope is not found then skip this variable. 1437 calculateRanges(Var, Entries);
1438 recordLocalVariable(std::move(Var), Scope);
1447auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1448assert(Insertion.second &&
"function already has info");
1449 CurFn = Insertion.first->second.get();
1450 CurFn->FuncId = NextFuncId++;
1453// The S_FRAMEPROC record reports the stack size, and how many bytes of 1454// callee-saved registers were used. For targets that don't use a PUSH 1455// instruction (AArch64), this will be zero. 1459 CurFn->HasStackRealignment =
TRI->hasStackRealignment(*MF);
1461// For this function S_FRAMEPROC record, figure out which codeview register 1462// will be the frame pointer. 1463 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None;
// None. 1464 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None;
// None. 1465if (CurFn->FrameSize > 0) {
1467 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1468 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1470 CurFn->HasFramePointer =
true;
1471// If there is an FP, parameters are always relative to it. 1472 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1473if (CurFn->HasStackRealignment) {
1474// If the stack needs realignment, locals are relative to SP or VFRAME. 1475 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1477// Otherwise, locals are relative to EBP, and we probably have VLAs or 1478// other stack adjustments. 1479 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1484// Compute other frame procedure options. 1487 FPO |= FrameProcedureOptions::HasAlloca;
1489 FPO |= FrameProcedureOptions::HasSetJmp;
1490// FIXME: Set HasLongJmp if we ever track that info. 1492 FPO |= FrameProcedureOptions::HasInlineAssembly;
1496 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1498 FPO |= FrameProcedureOptions::HasExceptionHandling;
1501 FPO |= FrameProcedureOptions::MarkedInline;
1503 FPO |= FrameProcedureOptions::Naked;
1505 FPO |= FrameProcedureOptions::SecurityChecks;
1508 FPO |= FrameProcedureOptions::StrictSecurityChecks;
1511// __declspec(safebuffers) disables stack guards. 1512 FPO |= FrameProcedureOptions::SafeBuffers;
1518 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1520 FPO |= FrameProcedureOptions::ValidProfileCounts;
1521 FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
1523// FIXME: Set GuardCfg when it is implemented. 1524 CurFn->FrameProcOpts = FPO;
1528// Find the end of the function prolog. First known non-DBG_VALUE and 1529// non-frame setup location marks the beginning of the function body. 1530// FIXME: is there a simpler a way to do this? Can we just search 1531// for the first instruction of the function, not the last of the prolog? 1533bool EmptyPrologue =
true;
1534for (
constauto &
MBB : *MF) {
1535for (
constauto &
MI :
MBB) {
1540 }
elseif (!
MI.isMetaInstruction()) {
1541 EmptyPrologue =
false;
1546// Record beginning of function if we have a non-empty prologue. 1549 maybeRecordLocation(FnStartDL, MF);
1552// Find heap alloc sites and emit labels around them. 1553for (
constauto &
MBB : *MF) {
1554for (
constauto &
MI :
MBB) {
1555if (
MI.getHeapAllocMarker()) {
1562// Mark branches that may potentially be using jump tables with labels. 1565 discoverJumpTableBranches(MF,
isThumb);
1572// MSVC does not emit UDTs for typedefs that are scoped to classes. 1573if (
T->getTag() == dwarf::DW_TAG_typedef) {
1574if (
DIScope *Scope =
T->getScope()) {
1575switch (Scope->getTag()) {
1576case dwarf::DW_TAG_structure_type:
1577case dwarf::DW_TAG_class_type:
1578case dwarf::DW_TAG_union_type:
1588if (!
T ||
T->isForwardDecl())
1594T = DT->getBaseType();
1599void CodeViewDebug::addToUDTs(
constDIType *Ty) {
1600// Don't record empty UDTs. 1608 collectParentScopeNames(Ty->
getScope(), ParentScopeNames);
1610 std::string FullyQualifiedName =
1613if (ClosestSubprogram ==
nullptr) {
1614 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1615 }
elseif (ClosestSubprogram == CurrentSubprogram) {
1616 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1619// TODO: What if the ClosestSubprogram is neither null or the current 1620// subprogram? Currently, the UDT just gets dropped on the floor. 1622// The current behavior is not desirable. To get maximal fidelity, we would 1623// need to perform all type translation before beginning emission of .debug$S 1624// and then make LocalUDTs a member of FunctionInfo 1628// Generic dispatch for lowering an unknown type. 1630case dwarf::DW_TAG_array_type:
1631return lowerTypeArray(cast<DICompositeType>(Ty));
1632case dwarf::DW_TAG_typedef:
1633return lowerTypeAlias(cast<DIDerivedType>(Ty));
1634case dwarf::DW_TAG_base_type:
1635return lowerTypeBasic(cast<DIBasicType>(Ty));
1636case dwarf::DW_TAG_pointer_type:
1637if (cast<DIDerivedType>(Ty)->
getName() ==
"__vtbl_ptr_type")
1638return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1640case dwarf::DW_TAG_reference_type:
1641case dwarf::DW_TAG_rvalue_reference_type:
1642return lowerTypePointer(cast<DIDerivedType>(Ty));
1643case dwarf::DW_TAG_ptr_to_member_type:
1644return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1645case dwarf::DW_TAG_restrict_type:
1646case dwarf::DW_TAG_const_type:
1647case dwarf::DW_TAG_volatile_type:
1648// TODO: add support for DW_TAG_atomic_type here 1649return lowerTypeModifier(cast<DIDerivedType>(Ty));
1650case dwarf::DW_TAG_subroutine_type:
1652// The member function type of a member function pointer has no 1654return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1655/*ThisAdjustment=*/0,
1656/*IsStaticMethod=*/false);
1658return lowerTypeFunction(cast<DISubroutineType>(Ty));
1659case dwarf::DW_TAG_enumeration_type:
1660return lowerTypeEnum(cast<DICompositeType>(Ty));
1661case dwarf::DW_TAG_class_type:
1662case dwarf::DW_TAG_structure_type:
1663return lowerTypeClass(cast<DICompositeType>(Ty));
1664case dwarf::DW_TAG_union_type:
1665return lowerTypeUnion(cast<DICompositeType>(Ty));
1666case dwarf::DW_TAG_string_type:
1667return lowerTypeString(cast<DIStringType>(Ty));
1668case dwarf::DW_TAG_unspecified_type:
1669if (Ty->
getName() ==
"decltype(nullptr)")
1673// Use the null type index. 1679TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1684if (UnderlyingTypeIndex ==
TypeIndex(SimpleTypeKind::Int32Long) &&
1685 TypeName ==
"HRESULT")
1686returnTypeIndex(SimpleTypeKind::HResult);
1687if (UnderlyingTypeIndex ==
TypeIndex(SimpleTypeKind::UInt16Short) &&
1688 TypeName ==
"wchar_t")
1689returnTypeIndex(SimpleTypeKind::WideCharacter);
1691return UnderlyingTypeIndex;
1696TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1697// IndexType is size_t, which depends on the bitness of the target. 1698TypeIndex IndexType = getPointerSizeInBytes() == 8
1704// Add subranges to array type. 1706for (
int i =
Elements.size() - 1; i >= 0; --i) {
1708assert(Element->
getTag() == dwarf::DW_TAG_subrange_type);
1713// If Subrange has a Count field, use it. 1714// Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1), 1715// where lowerbound is from the LowerBound field of the Subrange, 1716// or the language default lowerbound if that field is unspecified. 1717if (
auto *CI = dyn_cast_if_present<ConstantInt *>(
Subrange->getCount()))
1718 Count = CI->getSExtValue();
1719elseif (
auto *UI = dyn_cast_if_present<ConstantInt *>(
1721// Fortran uses 1 as the default lowerbound; other languages use 0. 1723auto *LI = dyn_cast_if_present<ConstantInt *>(
Subrange->getLowerBound());
1724 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1725 Count = UI->getSExtValue() - Lowerbound + 1;
1728// Forward declarations of arrays without a size and VLAs use a count of -1. 1729// Emit a count of zero in these cases to match what MSVC does for arrays 1730// without a size. MSVC doesn't support VLAs, so it's not clear what we 1731// should do for them even if we could distinguish them. 1735// Update the element size and element type index for subsequent subranges. 1736 ElementSize *= Count;
1738// If this is the outermost array, use the size from the array. It will be 1739// more accurate if we had a VLA or an incomplete element type size. 1741 (i == 0 && ElementSize == 0) ? Ty->
getSizeInBits() / 8 : ElementSize;
1748return ElementTypeIndex;
1751// This function lowers a Fortran character type (DIStringType). 1752// Note that it handles only the character*n variant (using SizeInBits 1753// field in DIString to describe the type size) at the moment. 1754// Other variants (leveraging the StringLength and StringLengthExp 1755// fields in DIStringType) remain TBD. 1760// IndexType is size_t, which depends on the bitness of the target. 1761TypeIndex IndexType = getPointerSizeInBytes() == 8
1765// Create a type of character array of ArraySize. 1781case dwarf::DW_ATE_address:
1784case dwarf::DW_ATE_boolean:
1786case 1: STK = SimpleTypeKind::Boolean8;
break;
1787case 2: STK = SimpleTypeKind::Boolean16;
break;
1788case 4: STK = SimpleTypeKind::Boolean32;
break;
1789case 8: STK = SimpleTypeKind::Boolean64;
break;
1790case 16: STK = SimpleTypeKind::Boolean128;
break;
1793case dwarf::DW_ATE_complex_float:
1794// The CodeView size for a complex represents the size of 1795// an individual component. 1797case 4: STK = SimpleTypeKind::Complex16;
break;
1798case 8: STK = SimpleTypeKind::Complex32;
break;
1799case 16: STK = SimpleTypeKind::Complex64;
break;
1800case 20: STK = SimpleTypeKind::Complex80;
break;
1801case 32: STK = SimpleTypeKind::Complex128;
break;
1804case dwarf::DW_ATE_float:
1806case 2: STK = SimpleTypeKind::Float16;
break;
1807case 4: STK = SimpleTypeKind::Float32;
break;
1808case 6: STK = SimpleTypeKind::Float48;
break;
1809case 8: STK = SimpleTypeKind::Float64;
break;
1810case 10: STK = SimpleTypeKind::Float80;
break;
1811case 16: STK = SimpleTypeKind::Float128;
break;
1814case dwarf::DW_ATE_signed:
1816case 1: STK = SimpleTypeKind::SignedCharacter;
break;
1817case 2: STK = SimpleTypeKind::Int16Short;
break;
1818case 4: STK = SimpleTypeKind::Int32;
break;
1819case 8: STK = SimpleTypeKind::Int64Quad;
break;
1820case 16: STK = SimpleTypeKind::Int128Oct;
break;
1823case dwarf::DW_ATE_unsigned:
1825case 1: STK = SimpleTypeKind::UnsignedCharacter;
break;
1826case 2: STK = SimpleTypeKind::UInt16Short;
break;
1827case 4: STK = SimpleTypeKind::UInt32;
break;
1828case 8: STK = SimpleTypeKind::UInt64Quad;
break;
1829case 16: STK = SimpleTypeKind::UInt128Oct;
break;
1832case dwarf::DW_ATE_UTF:
1834case 1: STK = SimpleTypeKind::Character8;
break;
1835case 2: STK = SimpleTypeKind::Character16;
break;
1836case 4: STK = SimpleTypeKind::Character32;
break;
1839case dwarf::DW_ATE_signed_char:
1841 STK = SimpleTypeKind::SignedCharacter;
1843case dwarf::DW_ATE_unsigned_char:
1845 STK = SimpleTypeKind::UnsignedCharacter;
1851// Apply some fixups based on the source-level type name. 1852// Include some amount of canonicalization from an old naming scheme Clang 1853// used to use for integer types (in an outdated effort to be compatible with 1854// GCC's debug info/GDB's behavior, which has since been addressed). 1855if (STK == SimpleTypeKind::Int32 &&
1857 STK = SimpleTypeKind::Int32Long;
1858if (STK == SimpleTypeKind::UInt32 && (Ty->
getName() ==
"long unsigned int" ||
1859 Ty->
getName() ==
"unsigned long"))
1860 STK = SimpleTypeKind::UInt32Long;
1861if (STK == SimpleTypeKind::UInt16Short &&
1863 STK = SimpleTypeKind::WideCharacter;
1864if ((STK == SimpleTypeKind::SignedCharacter ||
1865 STK == SimpleTypeKind::UnsignedCharacter) &&
1867 STK = SimpleTypeKind::NarrowCharacter;
1874TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1876// Pointers to simple types without any options can use SimpleTypeMode, rather 1877// than having a dedicated pointer type record. 1878if (PointeeTI.
isSimple() && PO == PointerOptions::None &&
1880 Ty->
getTag() == dwarf::DW_TAG_pointer_type) {
1882 ? SimpleTypeMode::NearPointer64
1883 : SimpleTypeMode::NearPointer32;
1888 Ty->
getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1892case dwarf::DW_TAG_pointer_type:
1893 PM = PointerMode::Pointer;
1895case dwarf::DW_TAG_reference_type:
1896 PM = PointerMode::LValueReference;
1898case dwarf::DW_TAG_rvalue_reference_type:
1899 PM = PointerMode::RValueReference;
1904 PO |= PointerOptions::Const;
1912// SizeInBytes being zero generally implies that the member pointer type was 1913// incomplete, which can happen if it is part of a function prototype. In this 1914// case, use the unknown model instead of the general model. 1918return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1919 : PointerToMemberRepresentation::GeneralFunction;
1920case DINode::FlagSingleInheritance:
1921return PointerToMemberRepresentation::SingleInheritanceFunction;
1922case DINode::FlagMultipleInheritance:
1923return PointerToMemberRepresentation::MultipleInheritanceFunction;
1924case DINode::FlagVirtualInheritance:
1925return PointerToMemberRepresentation::VirtualInheritanceFunction;
1930return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1931 : PointerToMemberRepresentation::GeneralData;
1932case DINode::FlagSingleInheritance:
1933return PointerToMemberRepresentation::SingleInheritanceData;
1934case DINode::FlagMultipleInheritance:
1935return PointerToMemberRepresentation::MultipleInheritanceData;
1936case DINode::FlagVirtualInheritance:
1937return PointerToMemberRepresentation::VirtualInheritanceData;
1945assert(Ty->
getTag() == dwarf::DW_TAG_ptr_to_member_type);
1946bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1949 getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->
getClassType() :
nullptr);
1950PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1951 : PointerKind::Near32;
1952PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1953 : PointerMode::PointerToDataMember;
1963/// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1964/// have a translation, use the NearC convention. 1967case dwarf::DW_CC_normal:
return CallingConvention::NearC;
1968case dwarf::DW_CC_BORLAND_msfastcall:
return CallingConvention::NearFast;
1969case dwarf::DW_CC_BORLAND_thiscall:
return CallingConvention::ThisCall;
1970case dwarf::DW_CC_BORLAND_stdcall:
return CallingConvention::NearStdCall;
1971case dwarf::DW_CC_BORLAND_pascal:
return CallingConvention::NearPascal;
1972case dwarf::DW_CC_LLVM_vectorcall:
return CallingConvention::NearVector;
1974return CallingConvention::NearC;
1982while (IsModifier &&
BaseTy) {
1983// FIXME: Need to add DWARF tags for __unaligned and _Atomic 1984switch (
BaseTy->getTag()) {
1985case dwarf::DW_TAG_const_type:
1986 Mods |= ModifierOptions::Const;
1987 PO |= PointerOptions::Const;
1989case dwarf::DW_TAG_volatile_type:
1990 Mods |= ModifierOptions::Volatile;
1991 PO |= PointerOptions::Volatile;
1993case dwarf::DW_TAG_restrict_type:
1994// Only pointer types be marked with __restrict. There is no known flag 1995// for __restrict in LF_MODIFIER records. 1996 PO |= PointerOptions::Restrict;
2006// Check if the inner type will use an LF_POINTER record. If so, the 2007// qualifiers will go in the LF_POINTER record. This comes up for types like 2008// 'int *const' and 'int *__restrict', not the more common cases like 'const 2011switch (
BaseTy->getTag()) {
2012case dwarf::DW_TAG_pointer_type:
2013case dwarf::DW_TAG_reference_type:
2014case dwarf::DW_TAG_rvalue_reference_type:
2015return lowerTypePointer(cast<DIDerivedType>(
BaseTy), PO);
2016case dwarf::DW_TAG_ptr_to_member_type:
2017return lowerTypeMemberPointer(cast<DIDerivedType>(
BaseTy), PO);
2025// Return the base type index if there aren't any modifiers. For example, the 2026// metadata could contain restrict wrappers around non-pointer types. 2027if (Mods == ModifierOptions::None)
2037 ReturnAndArgTypeIndices.
push_back(getTypeIndex(ArgType));
2039// MSVC uses type none for variadic argument. 2040if (ReturnAndArgTypeIndices.
size() > 1 &&
2046if (!ReturnAndArgTypeIndices.
empty()) {
2047auto ReturnAndArgTypesRef =
ArrayRef(ReturnAndArgTypeIndices);
2048 ReturnTypeIndex = ReturnAndArgTypesRef.front();
2049 ArgTypeIndices = ReturnAndArgTypesRef.
drop_front();
2052ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2068// Lower the containing class type. 2069TypeIndex ClassType = getTypeIndex(ClassTy);
2076if (ReturnAndArgs.
size() > Index) {
2077 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
2080// If the first argument is a pointer type and this isn't a static method, 2081// treat it as the special 'this' parameter, which is encoded separately from 2084if (!IsStaticMethod && ReturnAndArgs.
size() > Index) {
2086 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
2087if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2088 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
2094while (Index < ReturnAndArgs.
size())
2095 ArgTypeIndices.
push_back(getTypeIndex(ReturnAndArgs[Index++]));
2097// MSVC uses type none for variadic argument. 2101ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2107 ArgTypeIndices.
size(), ArgListIndex, ThisAdjustment);
2112unsigned VSlotCount =
2122case DINode::FlagPrivate:
return MemberAccess::Private;
2123case DINode::FlagPublic:
return MemberAccess::Public;
2124case DINode::FlagProtected:
return MemberAccess::Protected;
2126// If there was no explicit access control, provide the default for the tag. 2127return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2128 : MemberAccess::Public;
2134if (SP->isArtificial())
2135return MethodOptions::CompilerGenerated;
2137// FIXME: Handle other MethodOptions. 2139return MethodOptions::None;
2144if (SP->getFlags() & DINode::FlagStaticMember)
2145return MethodKind::Static;
2147switch (SP->getVirtuality()) {
2148case dwarf::DW_VIRTUALITY_none:
2150case dwarf::DW_VIRTUALITY_virtual:
2151return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
2152case dwarf::DW_VIRTUALITY_pure_virtual:
2153return Introduced ? MethodKind::PureIntroducingVirtual
2154 : MethodKind::PureVirtual;
2159return MethodKind::Vanilla;
2164case dwarf::DW_TAG_class_type:
2165return TypeRecordKind::Class;
2166case dwarf::DW_TAG_structure_type:
2167return TypeRecordKind::Struct;
2173/// Return ClassOptions that should be present on both the forward declaration 2174/// and the defintion of a tag type. 2178// MSVC always sets this flag, even for local types. Clang doesn't always 2179// appear to give every type a linkage name, which may be problematic for us. 2180// FIXME: Investigate the consequences of not following them here. 2182 CO |= ClassOptions::HasUniqueName;
2184// Put the Nested flag on a type if it appears immediately inside a tag type. 2185// Do not walk the scope chain. Do not attempt to compute ContainsNestedClass 2186// here. That flag is only set on definitions, and not forward declarations. 2188if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2189 CO |= ClassOptions::Nested;
2191// Put the Scoped flag on function-local types. MSVC puts this flag for enum 2192// type only when it has an immediate function scope. Clang never puts enums 2193// inside DILexicalBlock scopes. Enum types, as generated by clang, are 2194// always in function, class, or file scopes. 2195if (Ty->
getTag() == dwarf::DW_TAG_enumeration_type) {
2196if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2197 CO |= ClassOptions::Scoped;
2199for (
constDIScope *Scope = ImmediateScope; Scope !=
nullptr;
2200 Scope = Scope->getScope()) {
2201if (isa<DISubprogram>(Scope)) {
2202 CO |= ClassOptions::Scoped;
2213case dwarf::DW_TAG_class_type:
2214case dwarf::DW_TAG_structure_type:
2215case dwarf::DW_TAG_union_type:
2216case dwarf::DW_TAG_enumeration_type:
2222if (
constauto *File = Ty->
getFile()) {
2234unsigned EnumeratorCount = 0;
2237 CO |= ClassOptions::ForwardReference;
2240 ContinuationBuilder.
begin(ContinuationRecordKind::FieldList);
2242// We assume that the frontend provides all members in source declaration 2243// order, which is what MSVC does. 2244if (
auto *
Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2245// FIXME: Is it correct to always emit these as unsigned here? 2256 std::string FullName = getFullyQualifiedName(Ty);
2262 addUDTSrcLine(Ty, EnumTI);
2267//===----------------------------------------------------------------------===// 2269//===----------------------------------------------------------------------===// 2280// MethodName -> MethodsList 2288// Direct overloaded methods gathered by name. 2296void CodeViewDebug::clear() {
2299 FnDebugInfo.clear();
2300 FileToFilepathMap.clear();
2303 TypeIndices.clear();
2304 CompleteTypeIndices.clear();
2305 ScopeGlobals.clear();
2306 CVGlobalVariableOffsets.clear();
2309void CodeViewDebug::collectMemberInfo(
ClassInfo &Info,
2312Info.Members.push_back({DDTy, 0});
2314// Collect static const data members with values. 2315if ((DDTy->
getFlags() & DINode::FlagStaticMember) ==
2316 DINode::FlagStaticMember) {
2319 StaticConstMembers.push_back(DDTy);
2325// An unnamed member may represent a nested struct or union. Attempt to 2326// interpret the unnamed member as a DICompositeType possibly wrapped in 2327// qualifier types. Add all the indirect fields to the current record if that 2328// succeeds, and drop the member if that fails. 2331constDIType *Ty = DDTy->getBaseType();
2332bool FullyResolved =
false;
2333while (!FullyResolved) {
2335case dwarf::DW_TAG_const_type:
2336case dwarf::DW_TAG_volatile_type:
2337// FIXME: we should apply the qualifier types to the indirect fields 2338// rather than dropping them. 2339 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2342 FullyResolved =
true;
2351ClassInfo NestedInfo = collectClassInfo(DCTy);
2353Info.Members.push_back(
2359// Add elements to structure type. 2361for (
auto *Element : Elements) {
2362// We assume that the frontend provides all members in source declaration 2363// order, which is what MSVC does. 2366if (
auto *SP = dyn_cast<DISubprogram>(Element)) {
2367Info.Methods[SP->getRawName()].push_back(SP);
2368 }
elseif (
auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2369if (DDTy->
getTag() == dwarf::DW_TAG_member) {
2370 collectMemberInfo(Info, DDTy);
2371 }
elseif (DDTy->
getTag() == dwarf::DW_TAG_inheritance) {
2372Info.Inheritance.push_back(DDTy);
2373 }
elseif (DDTy->
getTag() == dwarf::DW_TAG_pointer_type &&
2374 DDTy->
getName() ==
"__vtbl_ptr_type") {
2375Info.VShapeTI = getTypeIndex(DDTy);
2376 }
elseif (DDTy->
getTag() == dwarf::DW_TAG_typedef) {
2377Info.NestedTypes.push_back(DDTy);
2378 }
elseif (DDTy->
getTag() == dwarf::DW_TAG_friend) {
2379// Ignore friend members. It appears that MSVC emitted info about 2380// friends in the past, but modern versions do not. 2382 }
elseif (
auto *Composite = dyn_cast<DICompositeType>(Element)) {
2383Info.NestedTypes.push_back(Composite);
2385// Skip other unrecognized kinds of elements. 2391// This routine is used by lowerTypeClass and lowerTypeUnion to determine 2392// if a complete type should be emitted instead of a forward reference. 2398// Emit the complete type for unnamed structs. C++ classes with methods 2399// which have a circular reference back to the class type are expected to 2400// be named by the front-end and should not be "unnamed". C unnamed 2401// structs should not have circular references. 2403// If this unnamed complete type is already in the process of being defined 2404// then the description of the type is malformed and cannot be emitted 2405// into CodeView correctly so report a fatal error. 2406autoI = CompleteTypeIndices.find(Ty);
2407if (
I != CompleteTypeIndices.end() &&
I->second ==
TypeIndex())
2409return getCompleteTypeIndex(Ty);
2412// First, construct the forward decl. Don't look into Ty to compute the 2413// forward decl options, since it might not be available in all TUs. 2417 std::string FullName = getFullyQualifiedName(Ty);
2422 DeferredCompleteTypes.push_back(Ty);
2427// Construct the field list and complete type record. 2435 lowerRecordFieldList(Ty);
2438 CO |= ClassOptions::ContainsNestedClass;
2440// MSVC appears to set this flag by searching any destructor or method with 2441// FunctionOptions::Constructor among the emitted members. Clang AST has all 2442// the members, however special member functions are not yet emitted into 2443// debug information. For now checking a class's non-triviality seems enough. 2444// FIXME: not true for a nested unnamed struct. 2446 CO |= ClassOptions::HasConstructorOrDestructor;
2448 std::string FullName = getFullyQualifiedName(Ty);
2456 addUDTSrcLine(Ty, ClassTI);
2464// Emit the complete type for unnamed unions. 2466return getCompleteTypeIndex(Ty);
2470 std::string FullName = getFullyQualifiedName(Ty);
2474 DeferredCompleteTypes.push_back(Ty);
2484 lowerRecordFieldList(Ty);
2487 CO |= ClassOptions::ContainsNestedClass;
2490 std::string FullName = getFullyQualifiedName(Ty);
2492UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2496 addUDTSrcLine(Ty, UnionTI);
2503std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2505// Manually count members. MSVC appears to count everything that generates a 2506// field list record. Each individual overload in a method overload group 2507// contributes to this count, even though the overload group is a single field 2509unsigned MemberCount = 0;
2512 ContinuationBuilder.
begin(ContinuationRecordKind::FieldList);
2514// Create base classes. 2516if (
I->getFlags() & DINode::FlagVirtual) {
2518unsigned VBPtrOffset =
I->getVBPtrOffset();
2519// FIXME: Despite the accessor name, the offset is really in bytes. 2520unsigned VBTableIndex =
I->getOffsetInBits() / 4;
2521auto RecordKind = (
I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2522 ? TypeRecordKind::IndirectVirtualBaseClass
2523 : TypeRecordKind::VirtualBaseClass;
2526 getTypeIndex(
I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2532assert(
I->getOffsetInBits() % 8 == 0 &&
2533"bases must be on byte boundaries");
2535 getTypeIndex(
I->getBaseType()),
2536I->getOffsetInBits() / 8);
2550if (
Member->isStaticMember()) {
2557// Virtual function pointer member. 2558if ((
Member->getFlags() & DINode::FlagArtificial) &&
2559Member->getName().starts_with(
"_vptr$")) {
2569if (
Member->isBitField()) {
2570uint64_t StartBitOffset = MemberOffsetInBits;
2572 dyn_cast_or_null<ConstantInt>(
Member->getStorageOffsetInBits())) {
2573 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.
BaseOffset;
2575 StartBitOffset -= MemberOffsetInBits;
2580uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2588for (
auto &MethodItr :
Info.Methods) {
2591 std::vector<OneMethodRecord> Methods;
2593TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2594bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2596unsigned VFTableOffset = -1;
2598 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2606assert(!Methods.empty() &&
"Empty methods map entry");
2607if (Methods.size() == 1)
2610// FIXME: Make this use its own ContinuationBuilder so that 2611// MethodOverloadList can be split correctly. 2620// Create nested classes. 2628return std::make_tuple(FieldTI,
Info.VShapeTI, MemberCount,
2629 !
Info.NestedTypes.empty());
2632TypeIndex CodeViewDebug::getVBPTypeIndex() {
2634// Make a 'const int *' type. 2638PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2639 : PointerKind::Near32;
2642PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2650// The null DIType is the void type. Don't try to hash it. 2654// Check if we've already translated this type. Don't try to do a 2655// get-or-create style insertion that caches the hash lookup across the 2656// lowerType call. It will update the TypeIndices map. 2657autoI = TypeIndices.find({Ty, ClassTy});
2658if (
I != TypeIndices.end())
2661 TypeLoweringScope S(*
this);
2663return recordTypeIndexForDINode(Ty, TI, ClassTy);
2667CodeViewDebug::getTypeIndexForThisPtr(
constDIDerivedType *PtrTy,
2670"this type must be a pointer type");
2673if (SubroutineTy->
getFlags() & DINode::DIFlags::FlagLValueReference)
2674Options = PointerOptions::LValueRefThisPointer;
2675elseif (SubroutineTy->
getFlags() & DINode::DIFlags::FlagRValueReference)
2676Options = PointerOptions::RValueRefThisPointer;
2678// Check if we've already translated this type. If there is no ref qualifier 2679// on the function then we look up this pointer type with no associated class 2680// so that the TypeIndex for the this pointer can be shared with the type 2681// index for other pointers to this class type. If there is a ref qualifier 2682// then we lookup the pointer using the subroutine as the parent type. 2683autoI = TypeIndices.find({PtrTy, SubroutineTy});
2684if (
I != TypeIndices.end())
2687 TypeLoweringScope S(*
this);
2689return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2694 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2695 : PointerKind::Near32,
2696 PointerMode::LValueReference, PointerOptions::None,
2702// The null DIType is the void type. Don't try to hash it. 2706// Look through typedefs when getting the complete type index. Call 2707// getTypeIndex on the typdef to ensure that any UDTs are accumulated and are 2708// emitted only once. 2709if (Ty->
getTag() == dwarf::DW_TAG_typedef)
2710 (void)getTypeIndex(Ty);
2711while (Ty->
getTag() == dwarf::DW_TAG_typedef)
2712 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2714// If this is a non-record type, the complete type index is the same as the 2715// normal type index. Just call getTypeIndex. 2717case dwarf::DW_TAG_class_type:
2718case dwarf::DW_TAG_structure_type:
2719case dwarf::DW_TAG_union_type:
2722return getTypeIndex(Ty);
2725constauto *CTy = cast<DICompositeType>(Ty);
2727 TypeLoweringScope S(*
this);
2729// Make sure the forward declaration is emitted first. It's unclear if this 2730// is necessary, but MSVC does it, and we should follow suit until we can show 2732// We only emit a forward declaration for named types. 2733if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2736// Just use the forward decl if we don't have complete type info. This 2737// might happen if the frontend is using modules and expects the complete 2738// definition to be emitted elsewhere. 2739if (CTy->isForwardDecl())
2743// Check if we've already translated the complete record type. 2744// Insert the type with a null TypeIndex to signify that the type is currently 2746auto InsertResult = CompleteTypeIndices.insert({CTy,
TypeIndex()});
2747if (!InsertResult.second)
2748return InsertResult.first->second;
2751switch (CTy->getTag()) {
2752case dwarf::DW_TAG_class_type:
2753case dwarf::DW_TAG_structure_type:
2754 TI = lowerCompleteTypeClass(CTy);
2756case dwarf::DW_TAG_union_type:
2757 TI = lowerCompleteTypeUnion(CTy);
2763// Update the type index associated with this CompositeType. This cannot 2764// use the 'InsertResult' iterator above because it is potentially 2765// invalidated by map insertions which can occur while lowering the class 2767 CompleteTypeIndices[CTy] = TI;
2771/// Emit all the deferred complete record types. Try to do this in FIFO order, 2772/// and do this until fixpoint, as each complete record type typically 2774/// many other record types. 2775void CodeViewDebug::emitDeferredCompleteTypes() {
2777while (!DeferredCompleteTypes.empty()) {
2778std::swap(DeferredCompleteTypes, TypesToEmit);
2780 getCompleteTypeIndex(RecordTy);
2781 TypesToEmit.clear();
2785void CodeViewDebug::emitLocalVariableList(
const FunctionInfo &FI,
2787// Get the sorted list of parameters and emit them first. 2789for (
const LocalVariable &L : Locals)
2790if (
L.DIVar->isParameter())
2792llvm::sort(Params, [](
const LocalVariable *L,
const LocalVariable *R) {
2793returnL->DIVar->getArg() <
R->DIVar->getArg();
2795for (
const LocalVariable *L : Params)
2796 emitLocalVariable(FI, *L);
2798// Next emit all non-parameters in the order that we found them. 2799for (
const LocalVariable &L : Locals) {
2800if (!
L.DIVar->isParameter()) {
2801if (
L.ConstantValue) {
2802// If ConstantValue is set we will emit it as a S_CONSTANT instead of a 2803// S_LOCAL in order to be able to represent it at all. 2804constDIType *Ty =
L.DIVar->getType();
2806 emitConstantSymbolRecord(Ty, Val, std::string(
L.DIVar->getName()));
2808 emitLocalVariable(FI, L);
2814void CodeViewDebug::emitLocalVariable(
const FunctionInfo &FI,
2815const LocalVariable &Var) {
2816// LocalSym record, see SymbolRecord.h for more info. 2817MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2820if (Var.DIVar->isParameter())
2821Flags |= LocalSymFlags::IsParameter;
2822if (Var.DefRanges.empty())
2823Flags |= LocalSymFlags::IsOptimizedOut;
2827 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2828 : getCompleteTypeIndex(Var.DIVar->
getType());
2832// Truncate the name so we won't overflow the record length field. 2834 endSymbolRecord(LocalEnd);
2836// Calculate the on disk prefix of the appropriate def range record. The 2837// records and on disk formats are described in SymbolRecords.h. BytePrefix 2838// should be big enough to hold all forms without memory allocation. 2840for (
constauto &Pair : Var.DefRanges) {
2841 LocalVarDef DefRange = Pair.first;
2842constauto &
Ranges = Pair.second;
2844if (DefRange.InMemory) {
2845intOffset = DefRange.DataOffset;
2846unsignedReg = DefRange.CVRegister;
2848// 32-bit x86 call sequences often use PUSH instructions, which disrupt 2849// ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0, 2850// instead. In frames without stack realignment, $T0 will be the CFA. 2853Offset += FI.OffsetAdjustment;
2856// If we can use the chosen frame pointer for the frame and this isn't a 2857// sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record. 2858// Otherwise, use S_DEFRANGE_REGISTER_REL. 2860if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2861 (
bool(Flags & LocalSymFlags::IsParameter)
2862 ? (EncFP == FI.EncodedParamFramePtrReg)
2863 : (EncFP == FI.EncodedLocalFramePtrReg))) {
2869if (DefRange.IsSubfield) {
2871 (DefRange.StructOffset
2876 DRHdr.
Flags = RegRelFlags;
2881assert(DefRange.DataOffset == 0 &&
"unexpected offset into register");
2882if (DefRange.IsSubfield) {
2884 DRHdr.
Register = DefRange.CVRegister;
2890 DRHdr.
Register = DefRange.CVRegister;
2899const FunctionInfo& FI) {
2901 emitLexicalBlock(*
Block, FI);
2904/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a 2905/// lexical block scope. 2906void CodeViewDebug::emitLexicalBlock(
const LexicalBlock &
Block,
2907const FunctionInfo& FI) {
2908MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2915 OS.
AddComment(
"Function section relative address");
2921 endSymbolRecord(RecordEnd);
2923// Emit variables local to this lexical block. 2924 emitLocalVariableList(FI,
Block.Locals);
2925 emitGlobalVariableList(
Block.Globals);
2927// Emit lexical blocks contained within this block. 2928 emitLexicalBlockList(
Block.Children, FI);
2930// Close the lexical block scope. 2931 emitEndSymbolRecord(SymbolKind::S_END);
2934/// Convenience routine for collecting lexical block information for a list 2935/// of lexical scopes. 2936void CodeViewDebug::collectLexicalBlockInfo(
2942 collectLexicalBlockInfo(*Scope,
Blocks, Locals, Globals);
2945/// Populate the lexical blocks and local variable lists of the parent with 2946/// information about the specified lexical scope. 2947void CodeViewDebug::collectLexicalBlockInfo(
2952if (
Scope.isAbstractScope())
2955// Gather information about the lexical scope including local variables, 2956// global variables, and address ranges. 2957bool IgnoreScope =
false;
2958auto LI = ScopeVariables.find(&Scope);
2960 LI != ScopeVariables.end() ? &LI->second :
nullptr;
2961auto GI = ScopeGlobals.find(
Scope.getScopeNode());
2963 GI != ScopeGlobals.end() ? GI->second.get() :
nullptr;
2967// Ignore lexical scopes which do not contain variables. 2968if (!Locals && !Globals)
2971// Ignore lexical scopes which are not lexical blocks. 2975// Ignore scopes which have too many address ranges to represent in the 2976// current CodeView format or do not have a valid address range. 2978// For lexical scopes with multiple address ranges you may be tempted to 2979// construct a single range covering every instruction where the block is 2980// live and everything in between. Unfortunately, Visual Studio only 2981// displays variables from the first matching lexical block scope. If the 2982// first lexical block contains exception handling code or cold code which 2983// is moved to the bottom of the routine creating a single range covering 2984// nearly the entire routine, then it will hide all other lexical blocks 2985// and the variables they contain. 2990// This scope can be safely ignored and eliminating it will reduce the 2991// size of the debug information. Be sure to collect any variable and scope 2992// information from the this scope or any of its children and collapse them 2993// into the parent scope. 2998 collectLexicalBlockInfo(
Scope.getChildren(),
3005// Create a new CodeView lexical block for this lexical scope. If we've 3006// seen this DILexicalBlock before then the scope tree is malformed and 3007// we can handle this gracefully by not processing it a second time. 3008auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
3009if (!BlockInsertion.second)
3012// Create a lexical block containing the variables and collect the 3013// lexical block information for the children. 3016 LexicalBlock &
Block = BlockInsertion.first->second;
3019assert(
Block.Begin &&
"missing label for scope begin");
3023Block.Locals = std::move(*Locals);
3025Block.Globals = std::move(*Globals);
3027 collectLexicalBlockInfo(
Scope.getChildren(),
3035assert(FnDebugInfo.count(&GV));
3040// Build the lexical block structure to emit for this routine. 3042 collectLexicalBlockInfo(*CFS,
3047// Clear the scope and variable information from the map which will not be 3048// valid after we have finished processing this routine. This also prepares 3049// the map for the subsequent routine. 3050 ScopeVariables.clear();
3052// Don't emit anything if we don't have any line tables. 3053// Thunks are compiler-generated and probably won't have source correlation. 3054if (!CurFn->HaveLineInfo && !GV.
getSubprogram()->isThunk()) {
3055 FnDebugInfo.erase(&GV);
3060// Find heap alloc sites and add to list. 3061for (
constauto &
MBB : *MF) {
3062for (
constauto &
MI :
MBB) {
3063if (
MDNode *MD =
MI.getHeapAllocMarker()) {
3066 dyn_cast<DIType>(MD)));
3073 collectDebugInfoForJumpTables(MF,
isThumb);
3082// Usable locations are valid with non-zero line numbers. A line number of zero 3083// corresponds to optimized code that doesn't have a distinct source location. 3084// In this case, we try to use the previous or next source location depending on 3087returnDL &&
DL.getLine() != 0;
3093// Ignore DBG_VALUE and DBG_LABEL locations and function prologue. 3094if (!
Asm || !CurFn ||
MI->isDebugInstr() ||
3098// If the first instruction of a new MBB has no location, find the first 3099// instruction with a location and use that. 3102for (
constauto &NextMI : *
MI->getParent()) {
3103if (NextMI.isDebugInstr())
3105DL = NextMI.getDebugLoc();
3109// FIXME: Handle the case where the BB has no valid locations. This would 3110// probably require doing a real dataflow analysis. 3114// If we still don't have a debug location, don't record a location. 3118 maybeRecordLocation(
DL,
Asm->
MF);
3131void CodeViewDebug::endCVSubsection(
MCSymbol *EndLabel) {
3133// Every subsection must be aligned to a 4-byte boundary. 3139if (EE.Value == SymKind)
3156void CodeViewDebug::endSymbolRecord(
MCSymbol *SymEnd) {
3157// MSVC does not pad out symbol records to four bytes, but LLVM does to avoid 3158// an extra copy of every symbol record in LLD. This increases object file 3159// size by less than 1% in the clang build, and is compatible with the Visual 3165void CodeViewDebug::emitEndSymbolRecord(
SymbolKind EndKind) {
3173void CodeViewDebug::emitDebugInfoForUDTs(
3174const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3176size_t OriginalSize = UDTs.size();
3178for (
constauto &UDT : UDTs) {
3181MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3183 OS.
emitInt32(getCompleteTypeIndex(
T).getIndex());
3184assert(OriginalSize == UDTs.size() &&
3185"getCompleteTypeIndex found new UDTs!");
3187 endSymbolRecord(UDTRecordEnd);
3191void CodeViewDebug::collectGlobalVariableInfo() {
3196 GV.getDebugInfo(GVEs);
3197for (
constauto *GVE : GVEs)
3198 GlobalMap[GVE] = &GV;
3203constauto *
CU = cast<DICompileUnit>(
Node);
3204for (
constauto *GVE :
CU->getGlobalVariables()) {
3207// Don't emit string literals in CodeView, as the only useful parts are 3208// generally the filename and line number, which isn't possible to output 3209// in CodeView. String literals should be the only unnamed GlobalVariable 3213if ((
DIE->getNumElements() == 2) &&
3214 (
DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3215// Record the constant offset for the variable. 3217// A Fortran common block uses this idiom to encode the offset 3218// of a variable from the common block's starting address. 3219 CVGlobalVariableOffsets.insert(
3220 std::make_pair(DIGV,
DIE->getElement(1)));
3222// Emit constant global variables in a global symbol section. 3223if (GlobalMap.
count(GVE) == 0 &&
DIE->isConstant()) {
3224 CVGlobalVariable CVGV = {DIGV,
DIE};
3228constauto *GV = GlobalMap.
lookup(GVE);
3234if (Scope && isa<DILocalScope>(Scope)) {
3235// Locate a global variable list for this scope, creating one if 3237auto Insertion = ScopeGlobals.insert(
3238 {
Scope, std::unique_ptr<GlobalVariableList>()});
3239if (Insertion.second)
3240 Insertion.first->second = std::make_unique<GlobalVariableList>();
3241 VariableList = Insertion.first->second.get();
3243// Emit this global variable into a COMDAT section. 3244 VariableList = &ComdatVariables;
3246// Emit this global variable in a single global symbol section. 3247 VariableList = &GlobalVariables;
3248 CVGlobalVariable CVGV = {DIGV, GV};
3254void CodeViewDebug::collectDebugInfoForGlobals() {
3255for (
const CVGlobalVariable &CVGV : GlobalVariables) {
3258 getCompleteTypeIndex(DIGV->
getType());
3259 getFullyQualifiedName(Scope, DIGV->
getName());
3262for (
const CVGlobalVariable &CVGV : ComdatVariables) {
3265 getCompleteTypeIndex(DIGV->
getType());
3266 getFullyQualifiedName(Scope, DIGV->
getName());
3270void CodeViewDebug::emitDebugInfoForGlobals() {
3271// First, emit all globals that are not in a comdat in a single symbol 3272// substream. MSVC doesn't like it if the substream is empty, so only open 3273// it if we have at least one global to emit. 3274 switchToDebugSectionForSymbol(
nullptr);
3275if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3276 OS.
AddComment(
"Symbol subsection for globals");
3277MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3278 emitGlobalVariableList(GlobalVariables);
3279 emitStaticConstMemberList();
3280 endCVSubsection(EndLabel);
3283// Second, emit each global that is in a comdat into its own .debug$S 3284// section along with its own symbol substream. 3285for (
const CVGlobalVariable &CVGV : ComdatVariables) {
3286constGlobalVariable *GV = cast<const GlobalVariable *>(CVGV.GVInfo);
3290 switchToDebugSectionForSymbol(GVSym);
3291MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3292// FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3293 emitDebugInfoForGlobal(CVGV);
3294 endCVSubsection(EndLabel);
3298void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3301for (
auto *Ty : cast<DICompileUnit>(
Node)->getRetainedTypes()) {
3302if (
DIType *RT = dyn_cast<DIType>(Ty)) {
3304// FIXME: Add to global/local DTU list. 3310// Emit each global variable in the specified array. 3312for (
const CVGlobalVariable &CVGV : Globals) {
3313// FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3314 emitDebugInfoForGlobal(CVGV);
3320MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3322 OS.
emitInt32(getTypeIndex(DTy).getIndex());
3326// Encoded integers shouldn't need more than 10 bytes. 3336 endSymbolRecord(SConstantEnd);
3339void CodeViewDebug::emitStaticConstMemberList() {
3345 dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3349 dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3350Value =
APSInt(CFP->getValueAPF().bitcastToAPInt(),
true);
3354 emitConstantSymbolRecord(DTy->getBaseType(),
Value,
3355 getFullyQualifiedName(Scope, DTy->
getName()));
3360if (isa<DICompositeType>(Ty))
3363if (
auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3365if (
T == dwarf::DW_TAG_pointer_type ||
3366T == dwarf::DW_TAG_ptr_to_member_type ||
3367T == dwarf::DW_TAG_reference_type ||
3368T == dwarf::DW_TAG_rvalue_reference_type)
3370assert(DTy->getBaseType() &&
"Expected valid base type");
3374auto *BTy = cast<DIBasicType>(Ty);
3375return (BTy->getEncoding() == dwarf::DW_ATE_float);
3378void CodeViewDebug::emitDebugInfoForGlobal(
const CVGlobalVariable &CVGV) {
3382// For static data members, get the scope from the declaration. 3383if (
constauto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3385Scope = MemberDecl->getScope();
3386// For static local variables and Fortran, the scoping portion is elided 3387// in its name so that we can reference the variable in the command line 3388// of the VS debugger. 3391 ? std::string(DIGV->
getName())
3395 dyn_cast_if_present<const GlobalVariable *>(CVGV.GVInfo)) {
3396// DataSym record, see SymbolRecord.h for more info. Thread local data 3397// happens to have the same format as global data. 3401 : SymbolKind::S_GTHREAD32)
3403 : SymbolKind::S_GDATA32);
3409// Use the offset seen while collecting info on globals. 3416constunsigned LengthOfDataRecord = 12;
3418 endSymbolRecord(DataEnd);
3422"Global constant variables must contain a constant expression.");
3424// Use unsigned for floats. 3436 int64_t)> &Callback) {
3438if (JTI && !JTI->isEmpty()) {
3442for (
constauto &
MBB : *MF) {
3443// Search for indirect branches... 3445if (LastMI !=
MBB.
end() && LastMI->isIndirectBranch()) {
3447// ... that directly use jump table operands. 3448// NOTE: ARM uses pattern matching to lower its BR_JT SDNode to 3449// machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node 3450// interferes with this process *but* the resulting pseudo-instruction 3451// uses a Jump Table operand, so extract the jump table index directly 3453for (
constauto &MO : LastMI->operands()) {
3455unsigned Index = MO.getIndex();
3459 Callback(*JTI, *LastMI, Index);
3464// ... that have jump table debug info. 3465// NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node 3466// when lowering the BR_JT SDNode to an indirect branch. 3468if (
I->isJumpTableDebugInfo()) {
3469unsigned Index =
I->getOperand(0).getImm();
3473 Callback(*JTI, *LastMI, Index);
3482"Some of jump tables were not used in a debug info instruction");
3487void CodeViewDebug::discoverJumpTableBranches(
constMachineFunction *MF,
3495void CodeViewDebug::collectDebugInfoForJumpTables(
constMachineFunction *MF,
3500 int64_t JumpTableIndex) {
3501// For label-difference jump tables, find the base expression. 3502// Otherwise the jump table uses an absolute address (so no base 3513"EK_Custom32, EK_GPRel32BlockAddress, and " 3514"EK_GPRel64BlockAddress should never be emitted for COFF");
3516// Each entry is an absolute address. 3517 EntrySize = JumpTableEntrySize::Pointer;
3523// Ask the AsmPrinter. 3524 std::tie(
Base, BaseOffset, Branch, EntrySize) =
3529 CurFn->JumpTables.push_back(
3536void CodeViewDebug::emitDebugInfoForJumpTables(
const FunctionInfo &FI) {
3537for (
auto JumpTable : FI.JumpTables) {
3538MCSymbol *JumpTableEnd = beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE);
3562 endSymbolRecord(JumpTableEnd);
3566void CodeViewDebug::emitInlinees(
3568// Divide the list of inlinees into chunks such that each chunk fits within 3570constexprsize_t ChunkSize =
3577size_t CurrentIndex = 0;
3578while (CurrentIndex < SortedInlinees.size()) {
3579autoSymbol = beginSymbolRecord(SymbolKind::S_INLINEES);
3580auto CurrentChunkSize =
3581 std::min(ChunkSize, SortedInlinees.size() - CurrentIndex);
3585constsize_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize;
3586for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) {
3588 OS.
emitInt32(SortedInlinees[CurrentIndex].getIndex());
3590 endSymbolRecord(Symbol);
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static bool isThumb(const MCSubtargetInfo &STI)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
static bool canUseReferenceType(const DbgVariableLocation &Loc)
static SourceLanguage MapDWLangToCVLang(unsigned DWLang)
static MethodKind translateMethodKindFlags(const DISubprogram *SP, bool Introduced)
static bool isUsableDebugLoc(DebugLoc DL)
static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, StringRef S)
static CPUType mapArchToCVCPUType(Triple::ArchType Type)
static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, unsigned MaxFixedRecordLength=0xF00)
static Version parseVersion(StringRef Name)
static MethodOptions translateMethodOptionFlags(const DISubprogram *SP)
static bool isNonTrivial(const DICompositeType *DCTy)
static std::string formatNestedName(ArrayRef< StringRef > QualifiedNameComponents, StringRef TypeName)
static ClassOptions getCommonClassOptions(const DICompositeType *Ty)
Return ClassOptions that should be present on both the forward declaration and the defintion of a tag...
static PointerToMemberRepresentation translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags)
static FunctionOptions getFunctionOptions(const DISubroutineType *Ty, const DICompositeType *ClassTy=nullptr, StringRef SPName=StringRef(""))
static StringRef removeTemplateArgs(StringRef Name)
static TypeRecordKind getRecordKind(const DICompositeType *Ty)
void forEachJumpTableBranch(const MachineFunction *MF, bool isThumb, const std::function< void(const MachineJumpTableInfo &, const MachineInstr &, int64_t)> &Callback)
static CallingConvention dwarfCCToCodeView(unsigned DwarfCC)
Given a DWARF calling convention, get the CodeView equivalent.
static bool isFloatDIType(const DIType *Ty)
static void addLocIfNotPresent(SmallVectorImpl< const DILocation * > &Locs, const DILocation *Loc)
static bool shouldEmitUdt(const DIType *T)
static StringRef getPrettyScopeName(const DIScope *Scope)
static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty)
static bool needsReferenceType(const DbgVariableLocation &Loc)
static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file contains constants used for implementing Dwarf debug support.
DenseMap< Block *, BlockRelaxAux > Blocks
Module.h This file contains the declarations for the Module class.
unsigned const TargetRegisterInfo * TRI
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallString class.
static SymbolRef::Type getType(const Symbol *Sym)
This file describes how to lower LLVM code to machine code.
static const uint32_t IV[8]
Class for arbitrary precision integers.
An arbitrary precision integer that knows its signedness.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
size_t size() const
size - Get the array size.
This class is intended to be used as a driving class for all asm writers.
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
MCSymbol * getSymbol(const GlobalValue *GV) const
TargetMachine & TM
Target machine description.
MCSymbol * getFunctionBegin() const
const MCAsmInfo * MAI
Target Asm Printer information.
MachineFunction * MF
The current machine function.
bool hasDebugInfo() const
Returns true if valid debug info is present.
MCSymbol * getFunctionEnd() const
virtual std::tuple< const MCSymbol *, uint64_t, const MCSymbol *, codeview::JumpTableEntrySize > getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr, const MCSymbol *BranchLabel) const
Gets information required to create a CodeView debug symbol for a jump table.
Provides write only access to a subclass of WritableBinaryStream.
Collects and handles line tables information in a CodeView format.
CodeViewDebug(AsmPrinter *AP)
void beginModule(Module *M) override
bool moduleIsInFortran()
Check if the current module is in Fortran.
void endFunctionImpl(const MachineFunction *) override
Gather post-function debug information.
void endModule() override
Emit the COFF section that holds the line table information.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
ConstantFP - Floating Point Values [float, double].
This is the shared class of boolean and integer constants.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Basic type, like 'int' or 'float'.
unsigned getEncoding() const
StringRef getIdentifier() const
DINodeArray getElements() const
DIType * getBaseType() const
DIType * getClassType() const
Get casted version of extra data.
Constant * getConstant() const
A structured debug information entry.
bool isLocalToUnit() const
Metadata * getRawStaticDataMemberDeclaration() const
DILocalScope * getScope() const
Get the local scope for this variable.
Tagged DWARF-like metadata node.
dwarf::Tag getTag() const
Base class for scope-like contexts.
StringRef getFilename() const
StringRef getName() const
StringRef getDirectory() const
DIScope * getScope() const
String type, Fortran CHARACTER(n)
Type array for a subprogram.
DITypeRefArray getTypeArray() const
uint64_t getOffsetInBits() const
bool isObjectPointer() const
StringRef getName() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
DIScope * getScope() const
DIScope * getScope() const
StringRef getName() const
This class represents an Operation in the Expression.
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
static const EntryIndex NoEntry
Special value to indicate that an entry is valid until the end of the function.
Base class for debug information backends.
static bool isUnsignedDIType(const DIType *Ty)
Return true if type encoding is unsigned.
AsmPrinter * Asm
Target of debug info emission.
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const MachineBasicBlock * PrevInstBB
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
const MachineInstr * PrologEndLoc
This location indicates end of function prologue and beginning of function body.
static uint64_t getBaseTypeSize(const DIType *Ty)
If this type is derived from a base type then return base type size.
DILocation * get() const
Get the underlying DILocation.
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...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
bool hasOptNone() const
Do not optimize this function (-O0).
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool isDeclarationForLinker() const
LexicalScope - This class is used to track scope information.
LexicalScope * findLexicalScope(const DILocation *DL)
findLexicalScope - Find lexical scope, either regular or inlined, for the given DebugLoc.
LexicalScope * findInlinedScope(const DILocalScope *N, const DILocation *IA)
findInlinedScope - Find an inlined scope for the given scope/inlined-at.
LexicalScope * getCurrentFunctionScope() const
getCurrentFunctionScope - Return lexical scope for the current function.
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
void * allocate(unsigned Size, unsigned Align=8)
MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
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.
MCSection * getCOFFDebugSymbolsSection() const
MCSection * getCOFFDebugTypesSection() const
MCSection * getCOFFGlobalTypeHashesSection() const
This represents a section on Windows.
MCSymbol * getCOMDATSymbol() const
Streaming machine code generation interface.
virtual void addBlankLine()
Emit a blank line to a .s file to pretty it up.
virtual bool emitCVFuncIdDirective(unsigned FunctionId)
Introduces a function id for use with .cv_loc.
virtual void emitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
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...
virtual void emitCVStringTableDirective()
This implements the CodeView '.cv_stringtable' assembler directive.
virtual bool isVerboseAsm() const
Return true if this streamer supports verbose assembly and if it is enabled.
virtual void emitCVFileChecksumOffsetDirective(unsigned FileNo)
This implements the CodeView '.cv_filechecksumoffset' assembler directive.
MCContext & getContext() const
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
virtual void emitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc={})
This implements the CodeView '.cv_fpo_data' assembler directive.
virtual void emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset)
Emits a COFF section relative relocation.
virtual void emitCVFileChecksumsDirective()
This implements the CodeView '.cv_filechecksums' assembler directive.
virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size)
Emit the absolute difference between two symbols.
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
virtual void emitCOFFSectionIndex(MCSymbol const *Symbol)
Emits a COFF section index.
virtual void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart, const MCSymbol *FnEnd)
This implements the CodeView '.cv_linetable' assembler directive.
virtual void emitValueToAlignment(Align Alignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
virtual void emitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers.
void emitInt16(uint64_t Value)
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
virtual void emitCVDefRangeDirective(ArrayRef< std::pair< const MCSymbol *, const MCSymbol * > > Ranges, StringRef FixedSizePortion)
This implements the CodeView '.cv_def_range' assembler directive.
void emitInt32(uint64_t Value)
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.
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.
void emitInt8(uint64_t Value)
virtual void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym)
This implements the CodeView '.cv_inline_linetable' assembler directive.
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
std::string CommandlineArgs
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
reverse_instr_iterator instr_rbegin()
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
reverse_instr_iterator instr_rend()
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
unsigned getCVBytesOfCalleeSavedRegisters() const
Returns how many bytes of callee-saved registers the target pushed in the prologue.
bool hasStackProtectorIndex() const
Description of the location of a variable whose Address is valid and unchanging during function execu...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
auto getInStackSlotVariableDbgInfo()
Returns the collection of variables for which we have debug info and that have been assigned a stack ...
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
ArrayRef< std::pair< MCSymbol *, MDNode * > > getCodeViewAnnotations() const
Representation of each machine instruction.
bool isDebugValue() const
MachineOperand & getDebugOperand(unsigned Index)
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_LabelDifference64
EK_LabelDifference64 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
JTEntryKind getEntryKind() const
const std::vector< MachineJumpTableEntry > & getJumpTables() const
const MCContext & getContext() const
const Module * getModule() const
Root of the metadata hierarchy.
A Module instance is used to store all the information related to an LLVM module.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
iterator_range< global_iterator > globals()
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Metadata * getProfileSummary(bool IsCS) const
Returns profile summary metadata.
iterator_range< op_iterator > operands()
const RecordRecTy * getType() const
Wrapper class representing virtual and physical registers.
Represents a location in source code.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
const_iterator begin() const
const_iterator end() const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
static StackOffset getScalable(int64_t Scalable)
static StackOffset getFixed(int64_t Fixed)
StringRef - Represent a constant reference to a string, i.e.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - Check if the string is empty.
char back() const
back - Get the last character in the string.
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Information about stack frame layout on the target.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
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...
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
MCTargetOptions MCOptions
Machine level options.
std::string ObjectFilenameForDebug
Stores the filename/path of the final .o/.obj file, to be written in the debug information.
unsigned Hotpatch
Emit the hotpatch flag in CodeView debug.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetFrameLowering * getFrameLowering() const
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Triple - Helper class for working with autoconf configuration names.
ArchType getArch() const
Get the parsed architecture type of this triple.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
StringRef getName() const
Return a constant reference to the value's name.
@ CurrentDirectory
Absolute CWD path.
@ SourceFile
Path to main source file, relative or absolute.
@ BuildTool
Absolute compiler path.
@ CommandLine
Full canonical command line (maybe -cc1)
@ TypeServerPDB
Absolute path of type server PDB (/Fd)
virtual void emitBytes(StringRef Data)=0
virtual bool isVerboseAsm()=0
virtual void AddComment(const Twine &T)=0
virtual void emitIntValue(uint64_t Value, unsigned Size)=0
virtual void emitBinaryData(StringRef Data)=0
virtual void AddRawComment(const Twine &T)=0
void begin(ContinuationRecordKind RecordKind)
void writeMemberType(RecordType &Record)
ArrayRef< ArrayRef< uint8_t > > records() const
TypeIndex insertRecord(ContinuationRecordBuilder &Builder)
ArrayRef< GloballyHashedType > hashes() const
TypeIndex writeLeafType(T &Record)
For method overload sets. LF_METHOD.
SimpleTypeKind getSimpleKind() const
SimpleTypeMode getSimpleMode() const
static const uint32_t FirstNonSimpleIndex
static StringRef simpleTypeName(TypeIndex TI)
uint32_t getIndex() const
static TypeIndex NullptrT()
void addCallbackToPipeline(TypeVisitorCallbacks &Callbacks)
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
A raw_ostream that writes to an SmallVector or SmallString.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
@ DEBUG_HASHES_SECTION_MAGIC
@ C
The default llvm calling convention, compatible with C.
Reg
All possible values of the reg field in the ModR/M byte.
PointerMode
Equivalent to CV_ptrmode_e.
ProcSymFlags
Corresponds to the CV_PROCFLAGS bitfield.
PointerOptions
Equivalent to misc lfPointerAttr bitfields.
LocalSymFlags
Corresponds to CV_LVARFLAGS bitfield.
MethodKind
Part of member attribute flags. (CV_methodprop_e)
PointerKind
Equivalent to CV_ptrtype_e.
CPUType
These values correspond to the CV_CPU_TYPE_e enumeration, and are documented here: https://msdn....
PointerToMemberRepresentation
Equivalent to CV_pmtype_e.
CallingConvention
These values correspond to the CV_call_e enumeration, and are documented at the following locations: ...
MethodOptions
Equivalent to CV_fldattr_t bitfield.
ArrayRef< EnumEntry< SymbolKind > > getSymbolTypeNames()
MemberAccess
Source-level access specifier. (CV_access_e)
ThunkOrdinal
These values correspond to the THUNK_ORDINAL enumeration.
EncodedFramePtrReg
Two-bit value indicating which register is the designated frame pointer register.
TypeRecordKind
Distinguishes individual records in .debug$T or .debug$P section or PDB type stream.
SymbolKind
Duplicate copy of the above enum, but using the official CV names.
ModifierOptions
Equivalent to CV_modifier_t.
StringRef getSymbolName(CVSymbol Sym)
EncodedFramePtrReg encodeFramePtrReg(RegisterId Reg, CPUType CPU)
Error visitTypeRecord(CVType &Record, TypeIndex Index, TypeVisitorCallbacks &Callbacks, VisitorDataSource Source=VDS_BytesPresent)
SourceLanguage
These values correspond to the CV_CFL_LANG enumeration in the Microsoft Debug Interface Access SDK,...
ElementType
The element type of an SRV or UAV resource.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
This is an optimization pass for GlobalISel generic memory operations.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
std::tuple< uint64_t, uint32_t > InlineSite
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
InsnRange - This is used to track range of instructions with identical lexical scope.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
TypeLoweringScope(CodeViewDebug &CVD)
This struct is a compact representation of a valid (non-zero power of two) alignment.
const DIDerivedType * MemberTypeNode
std::vector< MemberInfo > MemberList
MemberList Members
Direct members.
std::vector< const DIType * > NestedTypes
std::vector< const DIDerivedType * > Inheritance
Base classes.
int InMemory
Indicates that variable data is stored in memory relative to the specified register.
Represents the location at which a variable is stored.
static std::optional< DbgVariableLocation > extractFromMachineInstruction(const MachineInstr &Instruction)
Extract a VariableLocation from a MachineInstr.
SmallVector< int64_t, 1 > LoadChain
Chain of offsetted loads necessary to load the value if it lives in memory.
ulittle16_t MayHaveNoName
little32_t BasePointerOffset
ulittle16_t MayHaveNoName
ulittle32_t OffsetInParent