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 //===----------------------------------------------------------------------===//
13 #include "CodeViewDebug.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallBitVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/TinyPtrVector.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/Dwarf.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/LexicalScopes.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/TargetFrameLowering.h"
30 #include "llvm/CodeGen/TargetLowering.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/TargetSubtargetInfo.h"
33 #include "llvm/Config/llvm-config.h"
34 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
35 #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
36 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
37 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
38 #include "llvm/DebugInfo/CodeView/EnumTables.h"
39 #include "llvm/DebugInfo/CodeView/Line.h"
40 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
41 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
42 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
43 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/MC/MCAsmInfo.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCSectionCOFF.h"
55 #include "llvm/MC/MCStreamer.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/Support/BinaryStreamWriter.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/Error.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/FormatVariadic.h"
62 #include "llvm/Support/Path.h"
63 #include "llvm/Support/SMLoc.h"
64 #include "llvm/Support/ScopedPrinter.h"
65 #include "llvm/Target/TargetLoweringObjectFile.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include "llvm/TargetParser/Triple.h"
75 using namespace llvm::codeview
;
78 class CVMCAdapter
: public CodeViewRecordStreamer
{
80 CVMCAdapter(MCStreamer
&OS
, TypeCollection
&TypeTable
)
81 : OS(&OS
), TypeTable(TypeTable
) {}
83 void emitBytes(StringRef Data
) override
{ OS
->emitBytes(Data
); }
85 void emitIntValue(uint64_t Value
, unsigned Size
) override
{
86 OS
->emitIntValueInHex(Value
, Size
);
89 void emitBinaryData(StringRef Data
) override
{ OS
->emitBinaryData(Data
); }
91 void AddComment(const Twine
&T
) override
{ OS
->AddComment(T
); }
93 void AddRawComment(const Twine
&T
) override
{ OS
->emitRawComment(T
); }
95 bool isVerboseAsm() override
{ return OS
->isVerboseAsm(); }
97 std::string
getTypeName(TypeIndex TI
) override
{
99 if (!TI
.isNoneType()) {
101 TypeName
= std::string(TypeIndex::simpleTypeName(TI
));
103 TypeName
= std::string(TypeTable
.getTypeName(TI
));
109 MCStreamer
*OS
= nullptr;
110 TypeCollection
&TypeTable
;
114 static CPUType
mapArchToCVCPUType(Triple::ArchType Type
) {
116 case Triple::ArchType::x86
:
117 return CPUType::Pentium3
;
118 case Triple::ArchType::x86_64
:
120 case Triple::ArchType::thumb
:
121 // LLVM currently doesn't support Windows CE and so thumb
122 // here is indiscriminately mapped to ARMNT specifically.
123 return CPUType::ARMNT
;
124 case Triple::ArchType::aarch64
:
125 return CPUType::ARM64
;
126 case Triple::ArchType::mipsel
:
127 return CPUType::MIPS
;
129 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
133 CodeViewDebug::CodeViewDebug(AsmPrinter
*AP
)
134 : DebugHandlerBase(AP
), OS(*Asm
->OutStreamer
), TypeTable(Allocator
) {}
136 StringRef
CodeViewDebug::getFullFilepath(const DIFile
*File
) {
137 std::string
&Filepath
= FileToFilepathMap
[File
];
138 if (!Filepath
.empty())
141 StringRef 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.
145 if (Dir
.starts_with("/") || Filename
.starts_with("/")) {
146 if (llvm::sys::path::is_absolute(Filename
, llvm::sys::path::Style::posix
))
148 Filepath
= std::string(Dir
);
149 if (Dir
.back() != '/')
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.
159 if (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 "\".
171 while ((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.
177 while ((Cursor
= Filepath
.find("\\..\\", Cursor
)) != std::string::npos
) {
178 // Something's wrong if the path starts with "\..\", abort.
182 size_t PrevSlash
= Filepath
.rfind('\\', Cursor
- 1);
183 if (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.
194 while ((Cursor
= Filepath
.find("\\\\", Cursor
)) != std::string::npos
)
195 Filepath
.erase(Cursor
, 1);
200 unsigned CodeViewDebug::maybeRecordFile(const DIFile
*F
) {
201 StringRef FullPath
= getFullFilepath(F
);
202 unsigned NextId
= FileIdMap
.size() + 1;
203 auto Insertion
= FileIdMap
.insert(std::make_pair(FullPath
, NextId
));
204 if (Insertion
.second
) {
205 // We have to compute the full filepath and emit a .cv_file directive.
206 ArrayRef
<uint8_t> ChecksumAsBytes
;
207 FileChecksumKind CSKind
= FileChecksumKind::None
;
208 if (F
->getChecksum()) {
209 std::string Checksum
= fromHex(F
->getChecksum()->Value
);
210 void *CKMem
= OS
.getContext().allocate(Checksum
.size(), 1);
211 memcpy(CKMem
, Checksum
.data(), Checksum
.size());
212 ChecksumAsBytes
= ArrayRef
<uint8_t>(
213 reinterpret_cast<const uint8_t *>(CKMem
), Checksum
.size());
214 switch (F
->getChecksum()->Kind
) {
215 case DIFile::CSK_MD5
:
216 CSKind
= FileChecksumKind::MD5
;
218 case DIFile::CSK_SHA1
:
219 CSKind
= FileChecksumKind::SHA1
;
221 case DIFile::CSK_SHA256
:
222 CSKind
= FileChecksumKind::SHA256
;
226 bool Success
= OS
.emitCVFileDirective(NextId
, FullPath
, ChecksumAsBytes
,
227 static_cast<unsigned>(CSKind
));
229 assert(Success
&& ".cv_file directive failed");
231 return Insertion
.first
->second
;
234 CodeViewDebug::InlineSite
&
235 CodeViewDebug::getInlineSite(const DILocation
*InlinedAt
,
236 const DISubprogram
*Inlinee
) {
237 auto SiteInsertion
= CurFn
->InlineSites
.insert({InlinedAt
, InlineSite()});
238 InlineSite
*Site
= &SiteInsertion
.first
->second
;
239 if (SiteInsertion
.second
) {
240 unsigned ParentFuncId
= CurFn
->FuncId
;
241 if (const DILocation
*OuterIA
= InlinedAt
->getInlinedAt())
243 getInlineSite(OuterIA
, InlinedAt
->getScope()->getSubprogram())
246 Site
->SiteFuncId
= NextFuncId
++;
247 OS
.emitCVInlineSiteIdDirective(
248 Site
->SiteFuncId
, ParentFuncId
, maybeRecordFile(InlinedAt
->getFile()),
249 InlinedAt
->getLine(), InlinedAt
->getColumn(), SMLoc());
250 Site
->Inlinee
= Inlinee
;
251 InlinedSubprograms
.insert(Inlinee
);
252 auto InlineeIdx
= getFuncIdForSubprogram(Inlinee
);
254 if (InlinedAt
->getInlinedAt() == nullptr)
255 CurFn
->Inlinees
.insert(InlineeIdx
);
260 static StringRef
getPrettyScopeName(const DIScope
*Scope
) {
261 StringRef ScopeName
= Scope
->getName();
262 if (!ScopeName
.empty())
265 switch (Scope
->getTag()) {
266 case dwarf::DW_TAG_enumeration_type
:
267 case dwarf::DW_TAG_class_type
:
268 case dwarf::DW_TAG_structure_type
:
269 case dwarf::DW_TAG_union_type
:
270 return "<unnamed-tag>";
271 case dwarf::DW_TAG_namespace
:
272 return "`anonymous namespace'";
278 const DISubprogram
*CodeViewDebug::collectParentScopeNames(
279 const DIScope
*Scope
, SmallVectorImpl
<StringRef
> &QualifiedNameComponents
) {
280 const DISubprogram
*ClosestSubprogram
= nullptr;
281 while (Scope
!= nullptr) {
282 if (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.
288 if (const auto *Ty
= dyn_cast
<DICompositeType
>(Scope
))
289 DeferredCompleteTypes
.push_back(Ty
);
291 StringRef ScopeName
= getPrettyScopeName(Scope
);
292 if (!ScopeName
.empty())
293 QualifiedNameComponents
.push_back(ScopeName
);
294 Scope
= Scope
->getScope();
296 return ClosestSubprogram
;
299 static std::string
formatNestedName(ArrayRef
<StringRef
> QualifiedNameComponents
,
300 StringRef TypeName
) {
301 std::string FullyQualifiedName
;
302 for (StringRef QualifiedNameComponent
:
303 llvm::reverse(QualifiedNameComponents
)) {
304 FullyQualifiedName
.append(std::string(QualifiedNameComponent
));
305 FullyQualifiedName
.append("::");
307 FullyQualifiedName
.append(std::string(TypeName
));
308 return FullyQualifiedName
;
311 struct CodeViewDebug::TypeLoweringScope
{
312 TypeLoweringScope(CodeViewDebug
&CVD
) : CVD(CVD
) { ++CVD
.TypeEmissionLevel
; }
313 ~TypeLoweringScope() {
314 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
315 // inner TypeLoweringScopes don't attempt to emit deferred types.
316 if (CVD
.TypeEmissionLevel
== 1)
317 CVD
.emitDeferredCompleteTypes();
318 --CVD
.TypeEmissionLevel
;
323 std::string
CodeViewDebug::getFullyQualifiedName(const DIScope
*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.
328 TypeLoweringScope
S(*this);
329 SmallVector
<StringRef
, 5> QualifiedNameComponents
;
330 collectParentScopeNames(Scope
, QualifiedNameComponents
);
331 return formatNestedName(QualifiedNameComponents
, Name
);
334 std::string
CodeViewDebug::getFullyQualifiedName(const DIScope
*Ty
) {
335 const DIScope
*Scope
= Ty
->getScope();
336 return getFullyQualifiedName(Scope
, getPrettyScopeName(Ty
));
339 TypeIndex
CodeViewDebug::getScopeIndex(const DIScope
*Scope
) {
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.
350 if (!Scope
|| isa
<DIFile
>(Scope
) || isa
<DISubprogram
>(Scope
))
353 assert(!isa
<DIType
>(Scope
) && "shouldn't make a namespace scope for a type");
355 // Check if we've already translated this scope.
356 auto I
= TypeIndices
.find({Scope
, nullptr});
357 if (I
!= TypeIndices
.end())
360 // Build the fully qualified name of the scope.
361 std::string ScopeName
= getFullyQualifiedName(Scope
);
362 StringIdRecord
SID(TypeIndex(), ScopeName
);
363 auto TI
= TypeTable
.writeLeafType(SID
);
364 return recordTypeIndexForDINode(Scope
, TI
);
367 static StringRef
removeTemplateArgs(StringRef Name
) {
368 // Remove template args from the display name. Assume that the template args
369 // are the last thing in the name.
370 if (Name
.empty() || Name
.back() != '>')
373 int OpenBrackets
= 0;
374 for (int i
= Name
.size() - 1; i
>= 0; --i
) {
377 else if (Name
[i
] == '<') {
379 if (OpenBrackets
== 0)
380 return Name
.substr(0, i
);
386 TypeIndex
CodeViewDebug::getFuncIdForSubprogram(const DISubprogram
*SP
) {
389 // Check if we've already translated this subprogram.
390 auto I
= TypeIndices
.find({SP
, nullptr});
391 if (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.
397 StringRef DisplayName
= removeTemplateArgs(SP
->getName());
399 const DIScope
*Scope
= SP
->getScope();
401 if (const auto *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
405 TypeIndex ClassType
= getTypeIndex(Class
);
406 MemberFuncIdRecord
MFuncId(ClassType
, getMemberFunctionType(SP
, Class
),
408 TI
= TypeTable
.writeLeafType(MFuncId
);
410 // Otherwise, this must be a free function.
411 TypeIndex ParentScope
= getScopeIndex(Scope
);
412 FuncIdRecord
FuncId(ParentScope
, getTypeIndex(SP
->getType()), DisplayName
);
413 TI
= TypeTable
.writeLeafType(FuncId
);
416 return recordTypeIndexForDINode(SP
, TI
);
419 static bool isNonTrivial(const DICompositeType
*DCTy
) {
420 return ((DCTy
->getFlags() & DINode::FlagNonTrivial
) == DINode::FlagNonTrivial
);
423 static FunctionOptions
424 getFunctionOptions(const DISubroutineType
*Ty
,
425 const DICompositeType
*ClassTy
= nullptr,
426 StringRef SPName
= StringRef("")) {
427 FunctionOptions FO
= FunctionOptions::None
;
428 const DIType
*ReturnTy
= nullptr;
429 if (auto TypeArray
= Ty
->getTypeArray()) {
430 if (TypeArray
.size())
431 ReturnTy
= TypeArray
[0];
434 // Add CxxReturnUdt option to functions that return nontrivial record types
435 // or methods that return record types.
436 if (auto *ReturnDCTy
= dyn_cast_or_null
<DICompositeType
>(ReturnTy
))
437 if (isNonTrivial(ReturnDCTy
) || ClassTy
)
438 FO
|= FunctionOptions::CxxReturnUdt
;
440 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
441 if (ClassTy
&& isNonTrivial(ClassTy
) && SPName
== ClassTy
->getName()) {
442 FO
|= FunctionOptions::Constructor
;
444 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
450 TypeIndex
CodeViewDebug::getMemberFunctionType(const DISubprogram
*SP
,
451 const DICompositeType
*Class
) {
452 // Always use the method declaration as the key for the function type. The
453 // method declaration contains the this adjustment.
454 if (SP
->getDeclaration())
455 SP
= SP
->getDeclaration();
456 assert(!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}.
460 auto I
= TypeIndices
.find({SP
, Class
});
461 if (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);
468 const bool IsStaticMethod
= (SP
->getFlags() & DINode::FlagStaticMember
) != 0;
470 FunctionOptions FO
= getFunctionOptions(SP
->getType(), Class
, SP
->getName());
471 TypeIndex TI
= lowerTypeMemberFunction(
472 SP
->getType(), Class
, SP
->getThisAdjustment(), IsStaticMethod
, FO
);
473 return recordTypeIndexForDINode(SP
, TI
, Class
);
476 TypeIndex
CodeViewDebug::recordTypeIndexForDINode(const DINode
*Node
,
478 const DIType
*ClassTy
) {
479 auto InsertResult
= TypeIndices
.insert({{Node
, ClassTy
}, TI
});
481 assert(InsertResult
.second
&& "DINode was already assigned a type index");
485 unsigned CodeViewDebug::getPointerSizeInBytes() {
486 return MMI
->getModule()->getDataLayout().getPointerSizeInBits() / 8;
489 void CodeViewDebug::recordLocalVariable(LocalVariable
&&Var
,
490 const LexicalScope
*LS
) {
491 if (const DILocation
*InlinedAt
= LS
->getInlinedAt()) {
492 // This variable was inlined. Associate it with the InlineSite.
493 const DISubprogram
*Inlinee
= Var
.DIVar
->getScope()->getSubprogram();
494 InlineSite
&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
));
502 static void addLocIfNotPresent(SmallVectorImpl
<const DILocation
*> &Locs
,
503 const DILocation
*Loc
) {
504 if (!llvm::is_contained(Locs
, Loc
))
508 void CodeViewDebug::maybeRecordLocation(const DebugLoc
&DL
,
509 const MachineFunction
*MF
) {
510 // Skip this instruction if it has the same location as the previous one.
511 if (!DL
|| DL
== PrevInstLoc
)
514 const DIScope
*Scope
= DL
->getScope();
518 // Skip this line if it is longer than the maximum we can record.
519 LineInfo
LI(DL
.getLine(), DL
.getLine(), /*IsStatement=*/true);
520 if (LI
.getStartLine() != DL
.getLine() || LI
.isAlwaysStepInto() ||
521 LI
.isNeverStepInto())
524 ColumnInfo
CI(DL
.getCol(), /*EndColumn=*/0);
525 if (CI
.getStartColumn() != DL
.getCol())
528 if (!CurFn
->HaveLineInfo
)
529 CurFn
->HaveLineInfo
= true;
531 if (PrevInstLoc
.get() && PrevInstLoc
->getFile() == DL
->getFile())
532 FileId
= CurFn
->LastFileId
;
534 FileId
= CurFn
->LastFileId
= maybeRecordFile(DL
->getFile());
537 unsigned FuncId
= CurFn
->FuncId
;
538 if (const DILocation
*SiteLoc
= DL
->getInlinedAt()) {
539 const DILocation
*Loc
= DL
.get();
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.
547 bool FirstLoc
= true;
548 while ((SiteLoc
= Loc
->getInlinedAt())) {
550 getInlineSite(SiteLoc
, Loc
->getScope()->getSubprogram());
552 addLocIfNotPresent(Site
.ChildSites
, Loc
);
556 addLocIfNotPresent(CurFn
->ChildSites
, Loc
);
559 OS
.emitCVLocDirective(FuncId
, FileId
, DL
.getLine(), DL
.getCol(),
560 /*PrologueEnd=*/false, /*IsStmt=*/false,
561 DL
->getFilename(), SMLoc());
564 void CodeViewDebug::emitCodeViewMagicVersion() {
565 OS
.emitValueToAlignment(Align(4));
566 OS
.AddComment("Debug section magic");
567 OS
.emitInt32(COFF::DEBUG_SECTION_MAGIC
);
570 static SourceLanguage
MapDWLangToCVLang(unsigned DWLang
) {
572 case dwarf::DW_LANG_C
:
573 case dwarf::DW_LANG_C89
:
574 case dwarf::DW_LANG_C99
:
575 case dwarf::DW_LANG_C11
:
576 return SourceLanguage::C
;
577 case dwarf::DW_LANG_C_plus_plus
:
578 case dwarf::DW_LANG_C_plus_plus_03
:
579 case dwarf::DW_LANG_C_plus_plus_11
:
580 case dwarf::DW_LANG_C_plus_plus_14
:
581 return SourceLanguage::Cpp
;
582 case dwarf::DW_LANG_Fortran77
:
583 case dwarf::DW_LANG_Fortran90
:
584 case dwarf::DW_LANG_Fortran95
:
585 case dwarf::DW_LANG_Fortran03
:
586 case dwarf::DW_LANG_Fortran08
:
587 return SourceLanguage::Fortran
;
588 case dwarf::DW_LANG_Pascal83
:
589 return SourceLanguage::Pascal
;
590 case dwarf::DW_LANG_Cobol74
:
591 case dwarf::DW_LANG_Cobol85
:
592 return SourceLanguage::Cobol
;
593 case dwarf::DW_LANG_Java
:
594 return SourceLanguage::Java
;
595 case dwarf::DW_LANG_D
:
596 return SourceLanguage::D
;
597 case dwarf::DW_LANG_Swift
:
598 return SourceLanguage::Swift
;
599 case dwarf::DW_LANG_Rust
:
600 return SourceLanguage::Rust
;
601 case dwarf::DW_LANG_ObjC
:
602 return SourceLanguage::ObjC
;
603 case dwarf::DW_LANG_ObjC_plus_plus
:
604 return 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.
609 return SourceLanguage::Masm
;
613 void CodeViewDebug::beginModule(Module
*M
) {
614 // If module doesn't have named metadata anchors or COFF debug section
615 // is not available, skip any debug info related stuff.
616 if (!Asm
->hasDebugInfo() ||
617 !Asm
->getObjFileLowering().getCOFFDebugSymbolsSection()) {
622 TheCPU
= mapArchToCVCPUType(Triple(M
->getTargetTriple()).getArch());
624 // Get the current source language.
625 const MDNode
*Node
= *M
->debug_compile_units_begin();
626 const auto *CU
= cast
<DICompileUnit
>(Node
);
628 CurrentSourceLanguage
= MapDWLangToCVLang(CU
->getSourceLanguage());
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();
638 void CodeViewDebug::endModule() {
639 if (!Asm
|| !Asm
->hasDebugInfo())
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);
651 MCSymbol
*CompilerInfo
= beginCVSubsection(DebugSubsectionKind::Symbols
);
653 emitCompilerInformation();
654 endCVSubsection(CompilerInfo
);
656 emitInlineeLinesSubsection();
658 // Emit per-function debug information.
659 for (auto &P
: FnDebugInfo
)
660 if (!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.
680 if (!GlobalUDTs
.empty()) {
681 MCSymbol
*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");
688 OS
.emitCVFileChecksumsDirective();
690 // This subsection holds the string table.
691 OS
.AddComment("String table");
692 OS
.emitCVStringTableDirective();
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();
703 if (EmitDebugGlobalHashes
)
704 emitTypeGlobalHashes();
710 emitNullTerminatedSymbolName(MCStreamer
&OS
, StringRef S
,
711 unsigned 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.
716 SmallString
<32> NullTerminatedString(
717 S
.take_front(MaxRecordLength
- MaxFixedRecordLength
- 1));
718 NullTerminatedString
.push_back('\0');
719 OS
.emitBytes(NullTerminatedString
);
722 void CodeViewDebug::emitTypeInformation() {
723 if (TypeTable
.empty())
726 // Start the .debug$T or .debug$P section with 0x4.
727 OS
.switchSection(Asm
->getObjFileLowering().getCOFFDebugTypesSection());
728 emitCodeViewMagicVersion();
730 TypeTableCollection
Table(TypeTable
.records());
731 TypeVisitorCallbackPipeline Pipeline
;
733 // To emit type record using Codeview MCStreamer adapter
734 CVMCAdapter
CVMCOS(OS
, Table
);
735 TypeRecordMapping
typeMapping(CVMCOS
);
736 Pipeline
.addCallbackToPipeline(typeMapping
);
738 std::optional
<TypeIndex
> B
= Table
.getFirst();
740 // This will fail if the record data is invalid.
741 CVType Record
= Table
.getType(*B
);
743 Error E
= codeview::visitTypeRecord(Record
, *B
, Pipeline
);
746 logAllUnhandledErrors(std::move(E
), errs(), "error: ");
747 llvm_unreachable("produced malformed type record");
750 B
= Table
.getNext(*B
);
754 void CodeViewDebug::emitTypeGlobalHashes() {
755 if (TypeTable
.empty())
758 // Start the .debug$H section with the version and hash algorithm, currently
759 // hardcoded to version 0, SHA1.
760 OS
.switchSection(Asm
->getObjFileLowering().getCOFFGlobalTypeHashesSection());
762 OS
.emitValueToAlignment(Align(4));
763 OS
.AddComment("Magic");
764 OS
.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC
);
765 OS
.AddComment("Section Version");
767 OS
.AddComment("Hash Algorithm");
768 OS
.emitInt16(uint16_t(GlobalTypeHashAlg::BLAKE3
));
770 TypeIndex
TI(TypeIndex::FirstNonSimpleIndex
);
771 for (const auto &GHR
: TypeTable
.hashes()) {
772 if (OS
.isVerboseAsm()) {
773 // Emit an EOL-comment describing which TypeIndex this hash corresponds
774 // to, as well as the stringified SHA1 hash.
775 SmallString
<32> Comment
;
776 raw_svector_ostream
CommentOS(Comment
);
777 CommentOS
<< formatv("{0:X+} [{1}]", TI
.getIndex(), GHR
);
778 OS
.AddComment(Comment
);
781 assert(GHR
.Hash
.size() == 8);
782 StringRef
S(reinterpret_cast<const char *>(GHR
.Hash
.data()),
784 OS
.emitBinaryData(S
);
788 void CodeViewDebug::emitObjName() {
789 MCSymbol
*CompilerEnd
= beginSymbolRecord(SymbolKind::S_OBJNAME
);
791 StringRef
PathRef(Asm
->TM
.Options
.ObjectFilenameForDebug
);
792 llvm::SmallString
<256> PathStore(PathRef
);
794 if (PathRef
.empty() || PathRef
== "-") {
795 // Don't emit the filename if we're writing to stdout or to /dev/null.
801 OS
.AddComment("Signature");
802 OS
.emitIntValue(0, 4);
804 OS
.AddComment("Object name");
805 emitNullTerminatedSymbolName(OS
, PathRef
);
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.
818 static Version
parseVersion(StringRef Name
) {
821 for (const char C
: Name
) {
824 V
.Part
[N
] += C
- '0';
826 std::min
<int>(V
.Part
[N
], std::numeric_limits
<uint16_t>::max());
827 } else if (C
== '.') {
837 void CodeViewDebug::emitCompilerInformation() {
838 MCSymbol
*CompilerEnd
= beginSymbolRecord(SymbolKind::S_COMPILE3
);
841 // The low byte of the flags indicates the source language.
842 Flags
= CurrentSourceLanguage
;
843 // TODO: Figure out which other flags need to be set.
844 if (MMI
->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
845 Flags
|= static_cast<uint32_t>(CompileSym3Flags::PGO
);
847 using ArchType
= llvm::Triple::ArchType
;
848 ArchType Arch
= Triple(MMI
->getModule()->getTargetTriple()).getArch();
849 if (Asm
->TM
.Options
.Hotpatch
|| Arch
== ArchType::thumb
||
850 Arch
== ArchType::aarch64
) {
851 Flags
|= static_cast<uint32_t>(CompileSym3Flags::HotPatch
);
854 OS
.AddComment("Flags and language");
857 OS
.AddComment("CPUType");
858 OS
.emitInt16(static_cast<uint64_t>(TheCPU
));
860 NamedMDNode
*CUs
= MMI
->getModule()->getNamedMetadata("llvm.dbg.cu");
861 const MDNode
*Node
= *CUs
->operands().begin();
862 const auto *CU
= cast
<DICompileUnit
>(Node
);
864 StringRef CompilerVersion
= CU
->getProducer();
865 Version FrontVer
= parseVersion(CompilerVersion
);
866 OS
.AddComment("Frontend version");
867 for (int N
: 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.
874 int 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());
879 Version BackVer
= {{ Major
, 0, 0, 0 }};
880 OS
.AddComment("Backend version");
881 for (int N
: BackVer
.Part
)
884 OS
.AddComment("Null-terminated compiler version string");
885 emitNullTerminatedSymbolName(OS
, CompilerVersion
);
887 endSymbolRecord(CompilerEnd
);
890 static TypeIndex
getStringIdTypeIdx(GlobalTypeTableBuilder
&TypeTable
,
892 StringIdRecord
SIR(TypeIndex(0x0), S
);
893 return TypeTable
.writeLeafType(SIR
);
896 void 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.
907 TypeIndex BuildInfoArgs
[BuildInfoRecord::MaxArgs
] = {};
908 NamedMDNode
*CUs
= MMI
->getModule()->getNamedMetadata("llvm.dbg.cu");
909 const MDNode
*Node
= *CUs
->operands().begin(); // FIXME: Multiple CUs.
910 const auto *CU
= cast
<DICompileUnit
>(Node
);
911 const DIFile
*MainSourceFile
= CU
->getFile();
912 BuildInfoArgs
[BuildInfoRecord::CurrentDirectory
] =
913 getStringIdTypeIdx(TypeTable
, MainSourceFile
->getDirectory());
914 BuildInfoArgs
[BuildInfoRecord::SourceFile
] =
915 getStringIdTypeIdx(TypeTable
, MainSourceFile
->getFilename());
916 // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
917 BuildInfoArgs
[BuildInfoRecord::TypeServerPDB
] =
918 getStringIdTypeIdx(TypeTable
, "");
919 BuildInfoArgs
[BuildInfoRecord::BuildTool
] =
920 getStringIdTypeIdx(TypeTable
, Asm
->TM
.Options
.MCOptions
.Argv0
);
921 BuildInfoArgs
[BuildInfoRecord::CommandLine
] = getStringIdTypeIdx(
922 TypeTable
, Asm
->TM
.Options
.MCOptions
.CommandlineArgs
);
924 BuildInfoRecord
BIR(BuildInfoArgs
);
925 TypeIndex BuildInfoIndex
= TypeTable
.writeLeafType(BIR
);
927 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
928 // from the module symbols into the type stream.
929 MCSymbol
*BISubsecEnd
= beginCVSubsection(DebugSubsectionKind::Symbols
);
930 MCSymbol
*BIEnd
= beginSymbolRecord(SymbolKind::S_BUILDINFO
);
931 OS
.AddComment("LF_BUILDINFO index");
932 OS
.emitInt32(BuildInfoIndex
.getIndex());
933 endSymbolRecord(BIEnd
);
934 endCVSubsection(BISubsecEnd
);
937 void CodeViewDebug::emitInlineeLinesSubsection() {
938 if (InlinedSubprograms
.empty())
941 OS
.AddComment("Inlinee lines subsection");
942 MCSymbol
*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.
948 OS
.AddComment("Inlinee lines signature");
949 OS
.emitInt32(unsigned(InlineeLinesSignature::Normal
));
951 for (const DISubprogram
*SP
: InlinedSubprograms
) {
952 assert(TypeIndices
.count({SP
, nullptr}));
953 TypeIndex InlineeIdx
= TypeIndices
[{SP
, nullptr}];
956 unsigned FileId
= maybeRecordFile(SP
->getFile());
957 OS
.AddComment("Inlined function " + SP
->getName() + " starts at " +
958 SP
->getFilename() + Twine(':') + Twine(SP
->getLine()));
960 OS
.AddComment("Type index of inlined function");
961 OS
.emitInt32(InlineeIdx
.getIndex());
962 OS
.AddComment("Offset into filechecksum table");
963 OS
.emitCVFileChecksumOffsetDirective(FileId
);
964 OS
.AddComment("Starting line number");
965 OS
.emitInt32(SP
->getLine());
968 endCVSubsection(InlineEnd
);
971 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo
&FI
,
972 const DILocation
*InlinedAt
,
973 const InlineSite
&Site
) {
974 assert(TypeIndices
.count({Site
.Inlinee
, nullptr}));
975 TypeIndex InlineeIdx
= TypeIndices
[{Site
.Inlinee
, nullptr}];
978 MCSymbol
*InlineEnd
= beginSymbolRecord(SymbolKind::S_INLINESITE
);
980 OS
.AddComment("PtrParent");
982 OS
.AddComment("PtrEnd");
984 OS
.AddComment("Inlinee type index");
985 OS
.emitInt32(InlineeIdx
.getIndex());
987 unsigned FileId
= maybeRecordFile(Site
.Inlinee
->getFile());
988 unsigned StartLineNum
= Site
.Inlinee
->getLine();
990 OS
.emitCVInlineLinetableDirective(Site
.SiteFuncId
, FileId
, StartLineNum
,
993 endSymbolRecord(InlineEnd
);
995 emitLocalVariableList(FI
, Site
.InlinedLocals
);
997 // Recurse on child inlined call sites before closing the scope.
998 for (const DILocation
*ChildSite
: Site
.ChildSites
) {
999 auto I
= FI
.InlineSites
.find(ChildSite
);
1000 assert(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
);
1009 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol
*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.
1013 MCSectionCOFF
*GVSec
=
1014 GVSym
? dyn_cast
<MCSectionCOFF
>(&GVSym
->getSection()) : nullptr;
1015 const MCSymbol
*KeySym
= GVSec
? GVSec
->getCOMDATSymbol() : nullptr;
1017 MCSectionCOFF
*DebugSec
= cast
<MCSectionCOFF
>(
1018 Asm
->getObjFileLowering().getCOFFDebugSymbolsSection());
1019 DebugSec
= OS
.getContext().getAssociativeCOFFSection(DebugSec
, KeySym
);
1021 OS
.switchSection(DebugSec
);
1023 // Emit the magic version number if this is the first time we've switched to
1025 if (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.
1031 void CodeViewDebug::emitDebugInfoForThunk(const Function
*GV
,
1033 const MCSymbol
*Fn
) {
1034 std::string FuncName
=
1035 std::string(GlobalValue::dropLLVMManglingEscape(GV
->getName()));
1036 const ThunkOrdinal ordinal
= ThunkOrdinal::Standard
; // Only supported kind.
1038 OS
.AddComment("Symbol subsection for " + Twine(FuncName
));
1039 MCSymbol
*SymbolsEnd
= beginCVSubsection(DebugSubsectionKind::Symbols
);
1042 MCSymbol
*ThunkRecordEnd
= beginSymbolRecord(SymbolKind::S_THUNK32
);
1043 OS
.AddComment("PtrParent");
1045 OS
.AddComment("PtrEnd");
1047 OS
.AddComment("PtrNext");
1049 OS
.AddComment("Thunk section relative address");
1050 OS
.emitCOFFSecRel32(Fn
, /*Offset=*/0);
1051 OS
.AddComment("Thunk section index");
1052 OS
.emitCOFFSectionIndex(Fn
);
1053 OS
.AddComment("Code size");
1054 OS
.emitAbsoluteSymbolDiff(FI
.End
, Fn
, 2);
1055 OS
.AddComment("Ordinal");
1056 OS
.emitInt8(unsigned(ordinal
));
1057 OS
.AddComment("Function name");
1058 emitNullTerminatedSymbolName(OS
, FuncName
);
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
);
1071 void CodeViewDebug::emitDebugInfoForFunction(const Function
*GV
,
1073 // For each function there is a separate subsection which holds the PC to
1075 const MCSymbol
*Fn
= Asm
->getSymbol(GV
);
1078 // Switch to the to a comdat section, if appropriate.
1079 switchToDebugSectionForSymbol(Fn
);
1081 std::string FuncName
;
1082 auto *SP
= GV
->getSubprogram();
1084 setCurrentSubprogram(SP
);
1086 if (SP
->isThunk()) {
1087 emitDebugInfoForThunk(GV
, FI
, Fn
);
1091 // If we have a display name, build the fully qualified name by walking the
1093 if (!SP
->getName().empty())
1094 FuncName
= getFullyQualifiedName(SP
->getScope(), SP
->getName());
1096 // If our DISubprogram name is empty, use the mangled name.
1097 if (FuncName
.empty())
1098 FuncName
= std::string(GlobalValue::dropLLVMManglingEscape(GV
->getName()));
1100 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1101 if (Triple(MMI
->getModule()->getTargetTriple()).getArch() == Triple::x86
)
1102 OS
.emitCVFPOData(Fn
);
1104 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1105 OS
.AddComment("Symbol subsection for " + Twine(FuncName
));
1106 MCSymbol
*SymbolsEnd
= beginCVSubsection(DebugSubsectionKind::Symbols
);
1108 SymbolKind ProcKind
= GV
->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1109 : SymbolKind::S_GPROC32_ID
;
1110 MCSymbol
*ProcRecordEnd
= beginSymbolRecord(ProcKind
);
1112 // These fields are filled in by tools like CVPACK which run after the fact.
1113 OS
.AddComment("PtrParent");
1115 OS
.AddComment("PtrEnd");
1117 OS
.AddComment("PtrNext");
1119 // This is the important bit that tells the debugger where the function
1120 // code is located and what's its size:
1121 OS
.AddComment("Code size");
1122 OS
.emitAbsoluteSymbolDiff(FI
.End
, Fn
, 4);
1123 OS
.AddComment("Offset after prologue");
1125 OS
.AddComment("Offset before epilogue");
1127 OS
.AddComment("Function type index");
1128 OS
.emitInt32(getFuncIdForSubprogram(GV
->getSubprogram()).getIndex());
1129 OS
.AddComment("Function section relative address");
1130 OS
.emitCOFFSecRel32(Fn
, /*Offset=*/0);
1131 OS
.AddComment("Function section index");
1132 OS
.emitCOFFSectionIndex(Fn
);
1133 OS
.AddComment("Flags");
1134 ProcSymFlags ProcFlags
= ProcSymFlags::HasOptimizedDebugInfo
;
1135 if (FI
.HasFramePointer
)
1136 ProcFlags
|= ProcSymFlags::HasFP
;
1137 if (GV
->hasFnAttribute(Attribute::NoReturn
))
1138 ProcFlags
|= ProcSymFlags::IsNoReturn
;
1139 if (GV
->hasFnAttribute(Attribute::NoInline
))
1140 ProcFlags
|= ProcSymFlags::IsNoInline
;
1141 OS
.emitInt8(static_cast<uint8_t>(ProcFlags
));
1142 // Emit the function display name as a null-terminated string.
1143 OS
.AddComment("Function name");
1144 // Truncate the name so we won't overflow the record length field.
1145 emitNullTerminatedSymbolName(OS
, FuncName
);
1146 endSymbolRecord(ProcRecordEnd
);
1148 MCSymbol
*FrameProcEnd
= beginSymbolRecord(SymbolKind::S_FRAMEPROC
);
1149 // Subtract out the CSR size since MSVC excludes that and we include it.
1150 OS
.AddComment("FrameSize");
1151 OS
.emitInt32(FI
.FrameSize
- FI
.CSRSize
);
1152 OS
.AddComment("Padding");
1154 OS
.AddComment("Offset of padding");
1156 OS
.AddComment("Bytes of callee saved registers");
1157 OS
.emitInt32(FI
.CSRSize
);
1158 OS
.AddComment("Exception handler offset");
1160 OS
.AddComment("Exception handler section");
1162 OS
.AddComment("Flags (defines frame register)");
1163 OS
.emitInt32(uint32_t(FI
.FrameProcOpts
));
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.
1174 for (const DILocation
*InlinedAt
: FI
.ChildSites
) {
1175 auto I
= FI
.InlineSites
.find(InlinedAt
);
1176 assert(I
!= FI
.InlineSites
.end() &&
1177 "child site not in function inline site map");
1178 emitInlinedCallSite(FI
, InlinedAt
, I
->second
);
1181 for (auto Annot
: FI
.Annotations
) {
1182 MCSymbol
*Label
= Annot
.first
;
1183 MDTuple
*Strs
= cast
<MDTuple
>(Annot
.second
);
1184 MCSymbol
*AnnotEnd
= beginSymbolRecord(SymbolKind::S_ANNOTATION
);
1185 OS
.emitCOFFSecRel32(Label
, /*Offset=*/0);
1186 // FIXME: Make sure we don't overflow the max record size.
1187 OS
.emitCOFFSectionIndex(Label
);
1188 OS
.emitInt16(Strs
->getNumOperands());
1189 for (Metadata
*MD
: Strs
->operands()) {
1190 // MDStrings are null terminated, so we can do EmitBytes and get the
1191 // nice .asciz directive.
1192 StringRef Str
= cast
<MDString
>(MD
)->getString();
1193 assert(Str
.data()[Str
.size()] == '\0' && "non-nullterminated MDString");
1194 OS
.emitBytes(StringRef(Str
.data(), Str
.size() + 1));
1196 endSymbolRecord(AnnotEnd
);
1199 for (auto HeapAllocSite
: FI
.HeapAllocSites
) {
1200 const MCSymbol
*BeginLabel
= std::get
<0>(HeapAllocSite
);
1201 const MCSymbol
*EndLabel
= std::get
<1>(HeapAllocSite
);
1202 const DIType
*DITy
= std::get
<2>(HeapAllocSite
);
1203 MCSymbol
*HeapAllocEnd
= beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE
);
1204 OS
.AddComment("Call site offset");
1205 OS
.emitCOFFSecRel32(BeginLabel
, /*Offset=*/0);
1206 OS
.AddComment("Call site section index");
1207 OS
.emitCOFFSectionIndex(BeginLabel
);
1208 OS
.AddComment("Call instruction length");
1209 OS
.emitAbsoluteSymbolDiff(EndLabel
, BeginLabel
, 2);
1210 OS
.AddComment("Type index");
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.
1226 OS
.emitCVLinetableDirective(FI
.FuncId
, Fn
, FI
.End
);
1229 CodeViewDebug::LocalVarDef
1230 CodeViewDebug::createDefRangeMem(uint16_t CVRegister
, int Offset
) {
1233 DR
.DataOffset
= Offset
;
1234 assert(DR
.DataOffset
== Offset
&& "truncation");
1236 DR
.StructOffset
= 0;
1237 DR
.CVRegister
= CVRegister
;
1241 void CodeViewDebug::collectVariableInfoFromMFTable(
1242 DenseSet
<InlinedEntity
> &Processed
) {
1243 const MachineFunction
&MF
= *Asm
->MF
;
1244 const TargetSubtargetInfo
&TSI
= MF
.getSubtarget();
1245 const TargetFrameLowering
*TFI
= TSI
.getFrameLowering();
1246 const TargetRegisterInfo
*TRI
= TSI
.getRegisterInfo();
1248 for (const MachineFunction::VariableDbgInfo
&VI
:
1249 MF
.getInStackSlotVariableDbgInfo()) {
1252 assert(VI
.Var
->isValidLocationForIntrinsic(VI
.Loc
) &&
1253 "Expected inlined-at fields to agree");
1255 Processed
.insert(InlinedEntity(VI
.Var
, VI
.Loc
->getInlinedAt()));
1256 LexicalScope
*Scope
= LScopes
.findLexicalScope(VI
.Loc
);
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.
1268 if (VI
.Expr
->getNumElements() == 1 &&
1269 VI
.Expr
->getElement(0) == llvm::dwarf::DW_OP_deref
)
1271 else if (!VI
.Expr
->extractIfOffset(ExprOffset
))
1275 // Get the frame register used and the offset.
1277 StackOffset FrameOffset
=
1278 TFI
->getFrameIndexReference(*Asm
->MF
, VI
.getStackSlot(), FrameReg
);
1279 uint16_t CVReg
= TRI
->getCodeViewRegNum(FrameReg
);
1281 assert(!FrameOffset
.getScalable() &&
1282 "Frame offsets with a scalable component are not supported");
1284 // Calculate the label ranges.
1285 LocalVarDef DefRange
=
1286 createDefRangeMem(CVReg
, FrameOffset
.getFixed() + ExprOffset
);
1291 for (const InsnRange
&Range
: Scope
->getRanges()) {
1292 const MCSymbol
*Begin
= getLabelBeforeInsn(Range
.first
);
1293 const MCSymbol
*End
= getLabelAfterInsn(Range
.second
);
1294 End
= End
? End
: Asm
->getFunctionEnd();
1295 Var
.DefRanges
[DefRange
].emplace_back(Begin
, End
);
1299 Var
.UseReferenceType
= true;
1301 recordLocalVariable(std::move(Var
), Scope
);
1305 static bool canUseReferenceType(const DbgVariableLocation
&Loc
) {
1306 return !Loc
.LoadChain
.empty() && Loc
.LoadChain
.back() == 0;
1309 static bool needsReferenceType(const DbgVariableLocation
&Loc
) {
1310 return Loc
.LoadChain
.size() == 2 && Loc
.LoadChain
.back() == 0;
1313 void CodeViewDebug::calculateRanges(
1314 LocalVariable
&Var
, const DbgValueHistoryMap::Entries
&Entries
) {
1315 const TargetRegisterInfo
*TRI
= Asm
->MF
->getSubtarget().getRegisterInfo();
1317 // Calculate the definition ranges.
1318 for (auto I
= Entries
.begin(), E
= Entries
.end(); I
!= E
; ++I
) {
1319 const auto &Entry
= *I
;
1320 if (!Entry
.isDbgValue())
1322 const MachineInstr
*DVInst
= Entry
.getInstr();
1323 assert(DVInst
->isDebugValue() && "Invalid History entry");
1324 // FIXME: Find a way to represent constant variables, since they are
1325 // relatively common.
1326 std::optional
<DbgVariableLocation
> Location
=
1327 DbgVariableLocation::extractFromMachineInstruction(*DVInst
);
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.
1335 auto Op
= DVInst
->getDebugOperand(0);
1337 Var
.ConstantValue
= APSInt(APInt(64, Op
.getImm()), false);
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.
1348 if (Var
.UseReferenceType
) {
1349 // We're using a reference type. Drop the last zero offset load.
1350 if (canUseReferenceType(*Location
))
1351 Location
->LoadChain
.pop_back();
1354 } else if (needsReferenceType(*Location
)) {
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.
1364 if (Location
->Register
== 0 || Location
->LoadChain
.size() > 1)
1367 // Codeview can only express byte-aligned offsets, ensure that we have a
1368 // byte-boundaried location.
1369 if (Location
->FragmentInfo
)
1370 if (Location
->FragmentInfo
->OffsetInBits
% 8)
1374 DR
.CVRegister
= TRI
->getCodeViewRegNum(Location
->Register
);
1375 DR
.InMemory
= !Location
->LoadChain
.empty();
1377 !Location
->LoadChain
.empty() ? Location
->LoadChain
.back() : 0;
1378 if (Location
->FragmentInfo
) {
1379 DR
.IsSubfield
= true;
1380 DR
.StructOffset
= Location
->FragmentInfo
->OffsetInBits
/ 8;
1382 DR
.IsSubfield
= false;
1383 DR
.StructOffset
= 0;
1386 // Compute the label range.
1387 const MCSymbol
*Begin
= getLabelBeforeInsn(Entry
.getInstr());
1388 const MCSymbol
*End
;
1389 if (Entry
.getEndIndex() != DbgValueHistoryMap::NoEntry
) {
1390 auto &EndingEntry
= Entries
[Entry
.getEndIndex()];
1391 End
= EndingEntry
.isDbgValue()
1392 ? getLabelBeforeInsn(EndingEntry
.getInstr())
1393 : getLabelAfterInsn(EndingEntry
.getInstr());
1395 End
= Asm
->getFunctionEnd();
1397 // If the last range end is our begin, just extend the last range.
1398 // Otherwise make a new range.
1399 SmallVectorImpl
<std::pair
<const MCSymbol
*, const MCSymbol
*>> &R
=
1401 if (!R
.empty() && R
.back().second
== Begin
)
1402 R
.back().second
= End
;
1404 R
.emplace_back(Begin
, End
);
1406 // FIXME: Do more range combining.
1410 void CodeViewDebug::collectVariableInfo(const DISubprogram
*SP
) {
1411 DenseSet
<InlinedEntity
> Processed
;
1412 // Grab the variable info that was squirreled away in the MMI side-table.
1413 collectVariableInfoFromMFTable(Processed
);
1415 for (const auto &I
: DbgValues
) {
1416 InlinedEntity IV
= I
.first
;
1417 if (Processed
.count(IV
))
1419 const DILocalVariable
*DIVar
= cast
<DILocalVariable
>(IV
.first
);
1420 const DILocation
*InlinedAt
= IV
.second
;
1422 // Instruction ranges, specifying where IV is accessible.
1423 const auto &Entries
= I
.second
;
1425 LexicalScope
*Scope
= nullptr;
1427 Scope
= LScopes
.findInlinedScope(DIVar
->getScope(), InlinedAt
);
1429 Scope
= LScopes
.findLexicalScope(DIVar
->getScope());
1430 // If variable scope is not found then skip this variable.
1437 calculateRanges(Var
, Entries
);
1438 recordLocalVariable(std::move(Var
), Scope
);
1442 void CodeViewDebug::beginFunctionImpl(const MachineFunction
*MF
) {
1443 const TargetSubtargetInfo
&TSI
= MF
->getSubtarget();
1444 const TargetRegisterInfo
*TRI
= TSI
.getRegisterInfo();
1445 const MachineFrameInfo
&MFI
= MF
->getFrameInfo();
1446 const Function
&GV
= MF
->getFunction();
1447 auto Insertion
= FnDebugInfo
.insert({&GV
, std::make_unique
<FunctionInfo
>()});
1448 assert(Insertion
.second
&& "function already has info");
1449 CurFn
= Insertion
.first
->second
.get();
1450 CurFn
->FuncId
= NextFuncId
++;
1451 CurFn
->Begin
= Asm
->getFunctionBegin();
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.
1456 CurFn
->CSRSize
= MFI
.getCVBytesOfCalleeSavedRegisters();
1457 CurFn
->FrameSize
= MFI
.getStackSize();
1458 CurFn
->OffsetAdjustment
= MFI
.getOffsetAdjustment();
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.
1465 if (CurFn
->FrameSize
> 0) {
1466 if (!TSI
.getFrameLowering()->hasFP(*MF
)) {
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
;
1473 if (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.
1485 FrameProcedureOptions FPO
= FrameProcedureOptions::None
;
1486 if (MFI
.hasVarSizedObjects())
1487 FPO
|= FrameProcedureOptions::HasAlloca
;
1488 if (MF
->exposesReturnsTwice())
1489 FPO
|= FrameProcedureOptions::HasSetJmp
;
1490 // FIXME: Set HasLongJmp if we ever track that info.
1491 if (MF
->hasInlineAsm())
1492 FPO
|= FrameProcedureOptions::HasInlineAssembly
;
1493 if (GV
.hasPersonalityFn()) {
1494 if (isAsynchronousEHPersonality(
1495 classifyEHPersonality(GV
.getPersonalityFn())))
1496 FPO
|= FrameProcedureOptions::HasStructuredExceptionHandling
;
1498 FPO
|= FrameProcedureOptions::HasExceptionHandling
;
1500 if (GV
.hasFnAttribute(Attribute::InlineHint
))
1501 FPO
|= FrameProcedureOptions::MarkedInline
;
1502 if (GV
.hasFnAttribute(Attribute::Naked
))
1503 FPO
|= FrameProcedureOptions::Naked
;
1504 if (MFI
.hasStackProtectorIndex()) {
1505 FPO
|= FrameProcedureOptions::SecurityChecks
;
1506 if (GV
.hasFnAttribute(Attribute::StackProtectStrong
) ||
1507 GV
.hasFnAttribute(Attribute::StackProtectReq
)) {
1508 FPO
|= FrameProcedureOptions::StrictSecurityChecks
;
1510 } else if (!GV
.hasStackProtectorFnAttr()) {
1511 // __declspec(safebuffers) disables stack guards.
1512 FPO
|= FrameProcedureOptions::SafeBuffers
;
1514 FPO
|= FrameProcedureOptions(uint32_t(CurFn
->EncodedLocalFramePtrReg
) << 14U);
1515 FPO
|= FrameProcedureOptions(uint32_t(CurFn
->EncodedParamFramePtrReg
) << 16U);
1516 if (Asm
->TM
.getOptLevel() != CodeGenOptLevel::None
&& !GV
.hasOptSize() &&
1518 FPO
|= FrameProcedureOptions::OptimizedForSpeed
;
1519 if (GV
.hasProfileData()) {
1520 FPO
|= FrameProcedureOptions::ValidProfileCounts
;
1521 FPO
|= FrameProcedureOptions::ProfileGuidedOptimization
;
1523 // FIXME: Set GuardCfg when it is implemented.
1524 CurFn
->FrameProcOpts
= FPO
;
1526 OS
.emitCVFuncIdDirective(CurFn
->FuncId
);
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?
1532 DebugLoc PrologEndLoc
;
1533 bool EmptyPrologue
= true;
1534 for (const auto &MBB
: *MF
) {
1535 for (const auto &MI
: MBB
) {
1536 if (!MI
.isMetaInstruction() && !MI
.getFlag(MachineInstr::FrameSetup
) &&
1538 PrologEndLoc
= MI
.getDebugLoc();
1540 } else if (!MI
.isMetaInstruction()) {
1541 EmptyPrologue
= false;
1546 // Record beginning of function if we have a non-empty prologue.
1547 if (PrologEndLoc
&& !EmptyPrologue
) {
1548 DebugLoc FnStartDL
= PrologEndLoc
.getFnDebugLoc();
1549 maybeRecordLocation(FnStartDL
, MF
);
1552 // Find heap alloc sites and emit labels around them.
1553 for (const auto &MBB
: *MF
) {
1554 for (const auto &MI
: MBB
) {
1555 if (MI
.getHeapAllocMarker()) {
1556 requestLabelBeforeInsn(&MI
);
1557 requestLabelAfterInsn(&MI
);
1562 // Mark branches that may potentially be using jump tables with labels.
1563 bool isThumb
= Triple(MMI
->getModule()->getTargetTriple()).getArch() ==
1564 llvm::Triple::ArchType::thumb
;
1565 discoverJumpTableBranches(MF
, isThumb
);
1568 static bool shouldEmitUdt(const DIType
*T
) {
1572 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1573 if (T
->getTag() == dwarf::DW_TAG_typedef
) {
1574 if (DIScope
*Scope
= T
->getScope()) {
1575 switch (Scope
->getTag()) {
1576 case dwarf::DW_TAG_structure_type
:
1577 case dwarf::DW_TAG_class_type
:
1578 case dwarf::DW_TAG_union_type
:
1588 if (!T
|| T
->isForwardDecl())
1591 const DIDerivedType
*DT
= dyn_cast
<DIDerivedType
>(T
);
1594 T
= DT
->getBaseType();
1599 void CodeViewDebug::addToUDTs(const DIType
*Ty
) {
1600 // Don't record empty UDTs.
1601 if (Ty
->getName().empty())
1603 if (!shouldEmitUdt(Ty
))
1606 SmallVector
<StringRef
, 5> ParentScopeNames
;
1607 const DISubprogram
*ClosestSubprogram
=
1608 collectParentScopeNames(Ty
->getScope(), ParentScopeNames
);
1610 std::string FullyQualifiedName
=
1611 formatNestedName(ParentScopeNames
, getPrettyScopeName(Ty
));
1613 if (ClosestSubprogram
== nullptr) {
1614 GlobalUDTs
.emplace_back(std::move(FullyQualifiedName
), Ty
);
1615 } else if (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
1627 TypeIndex
CodeViewDebug::lowerType(const DIType
*Ty
, const DIType
*ClassTy
) {
1628 // Generic dispatch for lowering an unknown type.
1629 switch (Ty
->getTag()) {
1630 case dwarf::DW_TAG_array_type
:
1631 return lowerTypeArray(cast
<DICompositeType
>(Ty
));
1632 case dwarf::DW_TAG_typedef
:
1633 return lowerTypeAlias(cast
<DIDerivedType
>(Ty
));
1634 case dwarf::DW_TAG_base_type
:
1635 return lowerTypeBasic(cast
<DIBasicType
>(Ty
));
1636 case dwarf::DW_TAG_pointer_type
:
1637 if (cast
<DIDerivedType
>(Ty
)->getName() == "__vtbl_ptr_type")
1638 return lowerTypeVFTableShape(cast
<DIDerivedType
>(Ty
));
1640 case dwarf::DW_TAG_reference_type
:
1641 case dwarf::DW_TAG_rvalue_reference_type
:
1642 return lowerTypePointer(cast
<DIDerivedType
>(Ty
));
1643 case dwarf::DW_TAG_ptr_to_member_type
:
1644 return lowerTypeMemberPointer(cast
<DIDerivedType
>(Ty
));
1645 case dwarf::DW_TAG_restrict_type
:
1646 case dwarf::DW_TAG_const_type
:
1647 case dwarf::DW_TAG_volatile_type
:
1648 // TODO: add support for DW_TAG_atomic_type here
1649 return lowerTypeModifier(cast
<DIDerivedType
>(Ty
));
1650 case dwarf::DW_TAG_subroutine_type
:
1652 // The member function type of a member function pointer has no
1654 return lowerTypeMemberFunction(cast
<DISubroutineType
>(Ty
), ClassTy
,
1655 /*ThisAdjustment=*/0,
1656 /*IsStaticMethod=*/false);
1658 return lowerTypeFunction(cast
<DISubroutineType
>(Ty
));
1659 case dwarf::DW_TAG_enumeration_type
:
1660 return lowerTypeEnum(cast
<DICompositeType
>(Ty
));
1661 case dwarf::DW_TAG_class_type
:
1662 case dwarf::DW_TAG_structure_type
:
1663 return lowerTypeClass(cast
<DICompositeType
>(Ty
));
1664 case dwarf::DW_TAG_union_type
:
1665 return lowerTypeUnion(cast
<DICompositeType
>(Ty
));
1666 case dwarf::DW_TAG_string_type
:
1667 return lowerTypeString(cast
<DIStringType
>(Ty
));
1668 case dwarf::DW_TAG_unspecified_type
:
1669 if (Ty
->getName() == "decltype(nullptr)")
1670 return TypeIndex::NullptrT();
1671 return TypeIndex::None();
1673 // Use the null type index.
1678 TypeIndex
CodeViewDebug::lowerTypeAlias(const DIDerivedType
*Ty
) {
1679 TypeIndex UnderlyingTypeIndex
= getTypeIndex(Ty
->getBaseType());
1680 StringRef TypeName
= Ty
->getName();
1684 if (UnderlyingTypeIndex
== TypeIndex(SimpleTypeKind::Int32Long
) &&
1685 TypeName
== "HRESULT")
1686 return TypeIndex(SimpleTypeKind::HResult
);
1687 if (UnderlyingTypeIndex
== TypeIndex(SimpleTypeKind::UInt16Short
) &&
1688 TypeName
== "wchar_t")
1689 return TypeIndex(SimpleTypeKind::WideCharacter
);
1691 return UnderlyingTypeIndex
;
1694 TypeIndex
CodeViewDebug::lowerTypeArray(const DICompositeType
*Ty
) {
1695 const DIType
*ElementType
= Ty
->getBaseType();
1696 TypeIndex ElementTypeIndex
= getTypeIndex(ElementType
);
1697 // IndexType is size_t, which depends on the bitness of the target.
1698 TypeIndex IndexType
= getPointerSizeInBytes() == 8
1699 ? TypeIndex(SimpleTypeKind::UInt64Quad
)
1700 : TypeIndex(SimpleTypeKind::UInt32Long
);
1702 uint64_t ElementSize
= getBaseTypeSize(ElementType
) / 8;
1704 // Add subranges to array type.
1705 DINodeArray Elements
= Ty
->getElements();
1706 for (int i
= Elements
.size() - 1; i
>= 0; --i
) {
1707 const DINode
*Element
= Elements
[i
];
1708 assert(Element
->getTag() == dwarf::DW_TAG_subrange_type
);
1710 const DISubrange
*Subrange
= cast
<DISubrange
>(Element
);
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.
1717 if (auto *CI
= dyn_cast_if_present
<ConstantInt
*>(Subrange
->getCount()))
1718 Count
= CI
->getSExtValue();
1719 else if (auto *UI
= dyn_cast_if_present
<ConstantInt
*>(
1720 Subrange
->getUpperBound())) {
1721 // Fortran uses 1 as the default lowerbound; other languages use 0.
1722 int64_t Lowerbound
= (moduleIsInFortran()) ? 1 : 0;
1723 auto *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.
1740 uint64_t ArraySize
=
1741 (i
== 0 && ElementSize
== 0) ? Ty
->getSizeInBits() / 8 : ElementSize
;
1743 StringRef Name
= (i
== 0) ? Ty
->getName() : "";
1744 ArrayRecord
AR(ElementTypeIndex
, IndexType
, ArraySize
, Name
);
1745 ElementTypeIndex
= TypeTable
.writeLeafType(AR
);
1748 return 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.
1756 TypeIndex
CodeViewDebug::lowerTypeString(const DIStringType
*Ty
) {
1757 TypeIndex CharType
= TypeIndex(SimpleTypeKind::NarrowCharacter
);
1758 uint64_t ArraySize
= Ty
->getSizeInBits() >> 3;
1759 StringRef Name
= Ty
->getName();
1760 // IndexType is size_t, which depends on the bitness of the target.
1761 TypeIndex IndexType
= getPointerSizeInBytes() == 8
1762 ? TypeIndex(SimpleTypeKind::UInt64Quad
)
1763 : TypeIndex(SimpleTypeKind::UInt32Long
);
1765 // Create a type of character array of ArraySize.
1766 ArrayRecord
AR(CharType
, IndexType
, ArraySize
, Name
);
1768 return TypeTable
.writeLeafType(AR
);
1771 TypeIndex
CodeViewDebug::lowerTypeBasic(const DIBasicType
*Ty
) {
1773 dwarf::TypeKind Kind
;
1776 Kind
= static_cast<dwarf::TypeKind
>(Ty
->getEncoding());
1777 ByteSize
= Ty
->getSizeInBits() / 8;
1779 SimpleTypeKind STK
= SimpleTypeKind::None
;
1781 case dwarf::DW_ATE_address
:
1784 case dwarf::DW_ATE_boolean
:
1786 case 1: STK
= SimpleTypeKind::Boolean8
; break;
1787 case 2: STK
= SimpleTypeKind::Boolean16
; break;
1788 case 4: STK
= SimpleTypeKind::Boolean32
; break;
1789 case 8: STK
= SimpleTypeKind::Boolean64
; break;
1790 case 16: STK
= SimpleTypeKind::Boolean128
; break;
1793 case dwarf::DW_ATE_complex_float
:
1794 // The CodeView size for a complex represents the size of
1795 // an individual component.
1797 case 4: STK
= SimpleTypeKind::Complex16
; break;
1798 case 8: STK
= SimpleTypeKind::Complex32
; break;
1799 case 16: STK
= SimpleTypeKind::Complex64
; break;
1800 case 20: STK
= SimpleTypeKind::Complex80
; break;
1801 case 32: STK
= SimpleTypeKind::Complex128
; break;
1804 case dwarf::DW_ATE_float
:
1806 case 2: STK
= SimpleTypeKind::Float16
; break;
1807 case 4: STK
= SimpleTypeKind::Float32
; break;
1808 case 6: STK
= SimpleTypeKind::Float48
; break;
1809 case 8: STK
= SimpleTypeKind::Float64
; break;
1810 case 10: STK
= SimpleTypeKind::Float80
; break;
1811 case 16: STK
= SimpleTypeKind::Float128
; break;
1814 case dwarf::DW_ATE_signed
:
1816 case 1: STK
= SimpleTypeKind::SignedCharacter
; break;
1817 case 2: STK
= SimpleTypeKind::Int16Short
; break;
1818 case 4: STK
= SimpleTypeKind::Int32
; break;
1819 case 8: STK
= SimpleTypeKind::Int64Quad
; break;
1820 case 16: STK
= SimpleTypeKind::Int128Oct
; break;
1823 case dwarf::DW_ATE_unsigned
:
1825 case 1: STK
= SimpleTypeKind::UnsignedCharacter
; break;
1826 case 2: STK
= SimpleTypeKind::UInt16Short
; break;
1827 case 4: STK
= SimpleTypeKind::UInt32
; break;
1828 case 8: STK
= SimpleTypeKind::UInt64Quad
; break;
1829 case 16: STK
= SimpleTypeKind::UInt128Oct
; break;
1832 case dwarf::DW_ATE_UTF
:
1834 case 1: STK
= SimpleTypeKind::Character8
; break;
1835 case 2: STK
= SimpleTypeKind::Character16
; break;
1836 case 4: STK
= SimpleTypeKind::Character32
; break;
1839 case dwarf::DW_ATE_signed_char
:
1841 STK
= SimpleTypeKind::SignedCharacter
;
1843 case 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).
1855 if (STK
== SimpleTypeKind::Int32
&&
1856 (Ty
->getName() == "long int" || Ty
->getName() == "long"))
1857 STK
= SimpleTypeKind::Int32Long
;
1858 if (STK
== SimpleTypeKind::UInt32
&& (Ty
->getName() == "long unsigned int" ||
1859 Ty
->getName() == "unsigned long"))
1860 STK
= SimpleTypeKind::UInt32Long
;
1861 if (STK
== SimpleTypeKind::UInt16Short
&&
1862 (Ty
->getName() == "wchar_t" || Ty
->getName() == "__wchar_t"))
1863 STK
= SimpleTypeKind::WideCharacter
;
1864 if ((STK
== SimpleTypeKind::SignedCharacter
||
1865 STK
== SimpleTypeKind::UnsignedCharacter
) &&
1866 Ty
->getName() == "char")
1867 STK
= SimpleTypeKind::NarrowCharacter
;
1869 return TypeIndex(STK
);
1872 TypeIndex
CodeViewDebug::lowerTypePointer(const DIDerivedType
*Ty
,
1873 PointerOptions PO
) {
1874 TypeIndex PointeeTI
= getTypeIndex(Ty
->getBaseType());
1876 // Pointers to simple types without any options can use SimpleTypeMode, rather
1877 // than having a dedicated pointer type record.
1878 if (PointeeTI
.isSimple() && PO
== PointerOptions::None
&&
1879 PointeeTI
.getSimpleMode() == SimpleTypeMode::Direct
&&
1880 Ty
->getTag() == dwarf::DW_TAG_pointer_type
) {
1881 SimpleTypeMode Mode
= Ty
->getSizeInBits() == 64
1882 ? SimpleTypeMode::NearPointer64
1883 : SimpleTypeMode::NearPointer32
;
1884 return TypeIndex(PointeeTI
.getSimpleKind(), Mode
);
1888 Ty
->getSizeInBits() == 64 ? PointerKind::Near64
: PointerKind::Near32
;
1889 PointerMode PM
= PointerMode::Pointer
;
1890 switch (Ty
->getTag()) {
1891 default: llvm_unreachable("not a pointer tag type");
1892 case dwarf::DW_TAG_pointer_type
:
1893 PM
= PointerMode::Pointer
;
1895 case dwarf::DW_TAG_reference_type
:
1896 PM
= PointerMode::LValueReference
;
1898 case dwarf::DW_TAG_rvalue_reference_type
:
1899 PM
= PointerMode::RValueReference
;
1903 if (Ty
->isObjectPointer())
1904 PO
|= PointerOptions::Const
;
1906 PointerRecord
PR(PointeeTI
, PK
, PM
, PO
, Ty
->getSizeInBits() / 8);
1907 return TypeTable
.writeLeafType(PR
);
1910 static PointerToMemberRepresentation
1911 translatePtrToMemberRep(unsigned SizeInBytes
, bool IsPMF
, unsigned Flags
) {
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.
1916 switch (Flags
& DINode::FlagPtrToMemberRep
) {
1918 return SizeInBytes
== 0 ? PointerToMemberRepresentation::Unknown
1919 : PointerToMemberRepresentation::GeneralFunction
;
1920 case DINode::FlagSingleInheritance
:
1921 return PointerToMemberRepresentation::SingleInheritanceFunction
;
1922 case DINode::FlagMultipleInheritance
:
1923 return PointerToMemberRepresentation::MultipleInheritanceFunction
;
1924 case DINode::FlagVirtualInheritance
:
1925 return PointerToMemberRepresentation::VirtualInheritanceFunction
;
1928 switch (Flags
& DINode::FlagPtrToMemberRep
) {
1930 return SizeInBytes
== 0 ? PointerToMemberRepresentation::Unknown
1931 : PointerToMemberRepresentation::GeneralData
;
1932 case DINode::FlagSingleInheritance
:
1933 return PointerToMemberRepresentation::SingleInheritanceData
;
1934 case DINode::FlagMultipleInheritance
:
1935 return PointerToMemberRepresentation::MultipleInheritanceData
;
1936 case DINode::FlagVirtualInheritance
:
1937 return PointerToMemberRepresentation::VirtualInheritanceData
;
1940 llvm_unreachable("invalid ptr to member representation");
1943 TypeIndex
CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType
*Ty
,
1944 PointerOptions PO
) {
1945 assert(Ty
->getTag() == dwarf::DW_TAG_ptr_to_member_type
);
1946 bool IsPMF
= isa
<DISubroutineType
>(Ty
->getBaseType());
1947 TypeIndex ClassTI
= getTypeIndex(Ty
->getClassType());
1948 TypeIndex PointeeTI
=
1949 getTypeIndex(Ty
->getBaseType(), IsPMF
? Ty
->getClassType() : nullptr);
1950 PointerKind PK
= getPointerSizeInBytes() == 8 ? PointerKind::Near64
1951 : PointerKind::Near32
;
1952 PointerMode PM
= IsPMF
? PointerMode::PointerToMemberFunction
1953 : PointerMode::PointerToDataMember
;
1955 assert(Ty
->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1956 uint8_t SizeInBytes
= Ty
->getSizeInBits() / 8;
1957 MemberPointerInfo
MPI(
1958 ClassTI
, translatePtrToMemberRep(SizeInBytes
, IsPMF
, Ty
->getFlags()));
1959 PointerRecord
PR(PointeeTI
, PK
, PM
, PO
, SizeInBytes
, MPI
);
1960 return TypeTable
.writeLeafType(PR
);
1963 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1964 /// have a translation, use the NearC convention.
1965 static CallingConvention
dwarfCCToCodeView(unsigned DwarfCC
) {
1967 case dwarf::DW_CC_normal
: return CallingConvention::NearC
;
1968 case dwarf::DW_CC_BORLAND_msfastcall
: return CallingConvention::NearFast
;
1969 case dwarf::DW_CC_BORLAND_thiscall
: return CallingConvention::ThisCall
;
1970 case dwarf::DW_CC_BORLAND_stdcall
: return CallingConvention::NearStdCall
;
1971 case dwarf::DW_CC_BORLAND_pascal
: return CallingConvention::NearPascal
;
1972 case dwarf::DW_CC_LLVM_vectorcall
: return CallingConvention::NearVector
;
1974 return CallingConvention::NearC
;
1977 TypeIndex
CodeViewDebug::lowerTypeModifier(const DIDerivedType
*Ty
) {
1978 ModifierOptions Mods
= ModifierOptions::None
;
1979 PointerOptions PO
= PointerOptions::None
;
1980 bool IsModifier
= true;
1981 const DIType
*BaseTy
= Ty
;
1982 while (IsModifier
&& BaseTy
) {
1983 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1984 switch (BaseTy
->getTag()) {
1985 case dwarf::DW_TAG_const_type
:
1986 Mods
|= ModifierOptions::Const
;
1987 PO
|= PointerOptions::Const
;
1989 case dwarf::DW_TAG_volatile_type
:
1990 Mods
|= ModifierOptions::Volatile
;
1991 PO
|= PointerOptions::Volatile
;
1993 case 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
;
2003 BaseTy
= cast
<DIDerivedType
>(BaseTy
)->getBaseType();
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
2011 switch (BaseTy
->getTag()) {
2012 case dwarf::DW_TAG_pointer_type
:
2013 case dwarf::DW_TAG_reference_type
:
2014 case dwarf::DW_TAG_rvalue_reference_type
:
2015 return lowerTypePointer(cast
<DIDerivedType
>(BaseTy
), PO
);
2016 case dwarf::DW_TAG_ptr_to_member_type
:
2017 return lowerTypeMemberPointer(cast
<DIDerivedType
>(BaseTy
), PO
);
2023 TypeIndex ModifiedTI
= getTypeIndex(BaseTy
);
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.
2027 if (Mods
== ModifierOptions::None
)
2030 ModifierRecord
MR(ModifiedTI
, Mods
);
2031 return TypeTable
.writeLeafType(MR
);
2034 TypeIndex
CodeViewDebug::lowerTypeFunction(const DISubroutineType
*Ty
) {
2035 SmallVector
<TypeIndex
, 8> ReturnAndArgTypeIndices
;
2036 for (const DIType
*ArgType
: Ty
->getTypeArray())
2037 ReturnAndArgTypeIndices
.push_back(getTypeIndex(ArgType
));
2039 // MSVC uses type none for variadic argument.
2040 if (ReturnAndArgTypeIndices
.size() > 1 &&
2041 ReturnAndArgTypeIndices
.back() == TypeIndex::Void()) {
2042 ReturnAndArgTypeIndices
.back() = TypeIndex::None();
2044 TypeIndex ReturnTypeIndex
= TypeIndex::Void();
2045 ArrayRef
<TypeIndex
> ArgTypeIndices
= {};
2046 if (!ReturnAndArgTypeIndices
.empty()) {
2047 auto ReturnAndArgTypesRef
= ArrayRef(ReturnAndArgTypeIndices
);
2048 ReturnTypeIndex
= ReturnAndArgTypesRef
.front();
2049 ArgTypeIndices
= ReturnAndArgTypesRef
.drop_front();
2052 ArgListRecord
ArgListRec(TypeRecordKind::ArgList
, ArgTypeIndices
);
2053 TypeIndex ArgListIndex
= TypeTable
.writeLeafType(ArgListRec
);
2055 CallingConvention CC
= dwarfCCToCodeView(Ty
->getCC());
2057 FunctionOptions FO
= getFunctionOptions(Ty
);
2058 ProcedureRecord
Procedure(ReturnTypeIndex
, CC
, FO
, ArgTypeIndices
.size(),
2060 return TypeTable
.writeLeafType(Procedure
);
2063 TypeIndex
CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType
*Ty
,
2064 const DIType
*ClassTy
,
2066 bool IsStaticMethod
,
2067 FunctionOptions FO
) {
2068 // Lower the containing class type.
2069 TypeIndex ClassType
= getTypeIndex(ClassTy
);
2071 DITypeRefArray ReturnAndArgs
= Ty
->getTypeArray();
2074 SmallVector
<TypeIndex
, 8> ArgTypeIndices
;
2075 TypeIndex ReturnTypeIndex
= TypeIndex::Void();
2076 if (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
2083 TypeIndex ThisTypeIndex
;
2084 if (!IsStaticMethod
&& ReturnAndArgs
.size() > Index
) {
2085 if (const DIDerivedType
*PtrTy
=
2086 dyn_cast_or_null
<DIDerivedType
>(ReturnAndArgs
[Index
])) {
2087 if (PtrTy
->getTag() == dwarf::DW_TAG_pointer_type
) {
2088 ThisTypeIndex
= getTypeIndexForThisPtr(PtrTy
, Ty
);
2094 while (Index
< ReturnAndArgs
.size())
2095 ArgTypeIndices
.push_back(getTypeIndex(ReturnAndArgs
[Index
++]));
2097 // MSVC uses type none for variadic argument.
2098 if (!ArgTypeIndices
.empty() && ArgTypeIndices
.back() == TypeIndex::Void())
2099 ArgTypeIndices
.back() = TypeIndex::None();
2101 ArgListRecord
ArgListRec(TypeRecordKind::ArgList
, ArgTypeIndices
);
2102 TypeIndex ArgListIndex
= TypeTable
.writeLeafType(ArgListRec
);
2104 CallingConvention CC
= dwarfCCToCodeView(Ty
->getCC());
2106 MemberFunctionRecord
MFR(ReturnTypeIndex
, ClassType
, ThisTypeIndex
, CC
, FO
,
2107 ArgTypeIndices
.size(), ArgListIndex
, ThisAdjustment
);
2108 return TypeTable
.writeLeafType(MFR
);
2111 TypeIndex
CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType
*Ty
) {
2112 unsigned VSlotCount
=
2113 Ty
->getSizeInBits() / (8 * Asm
->MAI
->getCodePointerSize());
2114 SmallVector
<VFTableSlotKind
, 4> Slots(VSlotCount
, VFTableSlotKind::Near
);
2116 VFTableShapeRecord
VFTSR(Slots
);
2117 return TypeTable
.writeLeafType(VFTSR
);
2120 static MemberAccess
translateAccessFlags(unsigned RecordTag
, unsigned Flags
) {
2121 switch (Flags
& DINode::FlagAccessibility
) {
2122 case DINode::FlagPrivate
: return MemberAccess::Private
;
2123 case DINode::FlagPublic
: return MemberAccess::Public
;
2124 case DINode::FlagProtected
: return MemberAccess::Protected
;
2126 // If there was no explicit access control, provide the default for the tag.
2127 return RecordTag
== dwarf::DW_TAG_class_type
? MemberAccess::Private
2128 : MemberAccess::Public
;
2130 llvm_unreachable("access flags are exclusive");
2133 static MethodOptions
translateMethodOptionFlags(const DISubprogram
*SP
) {
2134 if (SP
->isArtificial())
2135 return MethodOptions::CompilerGenerated
;
2137 // FIXME: Handle other MethodOptions.
2139 return MethodOptions::None
;
2142 static MethodKind
translateMethodKindFlags(const DISubprogram
*SP
,
2144 if (SP
->getFlags() & DINode::FlagStaticMember
)
2145 return MethodKind::Static
;
2147 switch (SP
->getVirtuality()) {
2148 case dwarf::DW_VIRTUALITY_none
:
2150 case dwarf::DW_VIRTUALITY_virtual
:
2151 return Introduced
? MethodKind::IntroducingVirtual
: MethodKind::Virtual
;
2152 case dwarf::DW_VIRTUALITY_pure_virtual
:
2153 return Introduced
? MethodKind::PureIntroducingVirtual
2154 : MethodKind::PureVirtual
;
2156 llvm_unreachable("unhandled virtuality case");
2159 return MethodKind::Vanilla
;
2162 static TypeRecordKind
getRecordKind(const DICompositeType
*Ty
) {
2163 switch (Ty
->getTag()) {
2164 case dwarf::DW_TAG_class_type
:
2165 return TypeRecordKind::Class
;
2166 case dwarf::DW_TAG_structure_type
:
2167 return TypeRecordKind::Struct
;
2169 llvm_unreachable("unexpected tag");
2173 /// Return ClassOptions that should be present on both the forward declaration
2174 /// and the defintion of a tag type.
2175 static ClassOptions
getCommonClassOptions(const DICompositeType
*Ty
) {
2176 ClassOptions CO
= ClassOptions::None
;
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.
2181 if (!Ty
->getIdentifier().empty())
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.
2187 const DIScope
*ImmediateScope
= Ty
->getScope();
2188 if (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.
2195 if (Ty
->getTag() == dwarf::DW_TAG_enumeration_type
) {
2196 if (ImmediateScope
&& isa
<DISubprogram
>(ImmediateScope
))
2197 CO
|= ClassOptions::Scoped
;
2199 for (const DIScope
*Scope
= ImmediateScope
; Scope
!= nullptr;
2200 Scope
= Scope
->getScope()) {
2201 if (isa
<DISubprogram
>(Scope
)) {
2202 CO
|= ClassOptions::Scoped
;
2211 void CodeViewDebug::addUDTSrcLine(const DIType
*Ty
, TypeIndex TI
) {
2212 switch (Ty
->getTag()) {
2213 case dwarf::DW_TAG_class_type
:
2214 case dwarf::DW_TAG_structure_type
:
2215 case dwarf::DW_TAG_union_type
:
2216 case dwarf::DW_TAG_enumeration_type
:
2222 if (const auto *File
= Ty
->getFile()) {
2223 StringIdRecord
SIDR(TypeIndex(0x0), getFullFilepath(File
));
2224 TypeIndex SIDI
= TypeTable
.writeLeafType(SIDR
);
2226 UdtSourceLineRecord
USLR(TI
, SIDI
, Ty
->getLine());
2227 TypeTable
.writeLeafType(USLR
);
2231 TypeIndex
CodeViewDebug::lowerTypeEnum(const DICompositeType
*Ty
) {
2232 ClassOptions CO
= getCommonClassOptions(Ty
);
2234 unsigned EnumeratorCount
= 0;
2236 if (Ty
->isForwardDecl()) {
2237 CO
|= ClassOptions::ForwardReference
;
2239 ContinuationRecordBuilder ContinuationBuilder
;
2240 ContinuationBuilder
.begin(ContinuationRecordKind::FieldList
);
2241 for (const DINode
*Element
: Ty
->getElements()) {
2242 // We assume that the frontend provides all members in source declaration
2243 // order, which is what MSVC does.
2244 if (auto *Enumerator
= dyn_cast_or_null
<DIEnumerator
>(Element
)) {
2245 // FIXME: Is it correct to always emit these as unsigned here?
2246 EnumeratorRecord
ER(MemberAccess::Public
,
2247 APSInt(Enumerator
->getValue(), true),
2248 Enumerator
->getName());
2249 ContinuationBuilder
.writeMemberType(ER
);
2253 FTI
= TypeTable
.insertRecord(ContinuationBuilder
);
2256 std::string FullName
= getFullyQualifiedName(Ty
);
2258 EnumRecord
ER(EnumeratorCount
, CO
, FTI
, FullName
, Ty
->getIdentifier(),
2259 getTypeIndex(Ty
->getBaseType()));
2260 TypeIndex EnumTI
= TypeTable
.writeLeafType(ER
);
2262 addUDTSrcLine(Ty
, EnumTI
);
2267 //===----------------------------------------------------------------------===//
2269 //===----------------------------------------------------------------------===//
2271 struct llvm::ClassInfo
{
2273 const DIDerivedType
*MemberTypeNode
;
2274 uint64_t BaseOffset
;
2277 using MemberList
= std::vector
<MemberInfo
>;
2279 using MethodsList
= TinyPtrVector
<const DISubprogram
*>;
2280 // MethodName -> MethodsList
2281 using MethodsMap
= MapVector
<MDString
*, MethodsList
>;
2284 std::vector
<const DIDerivedType
*> Inheritance
;
2288 // Direct overloaded methods gathered by name.
2293 std::vector
<const DIType
*> NestedTypes
;
2296 void CodeViewDebug::clear() {
2297 assert(CurFn
== nullptr);
2299 FnDebugInfo
.clear();
2300 FileToFilepathMap
.clear();
2303 TypeIndices
.clear();
2304 CompleteTypeIndices
.clear();
2305 ScopeGlobals
.clear();
2306 CVGlobalVariableOffsets
.clear();
2309 void CodeViewDebug::collectMemberInfo(ClassInfo
&Info
,
2310 const DIDerivedType
*DDTy
) {
2311 if (!DDTy
->getName().empty()) {
2312 Info
.Members
.push_back({DDTy
, 0});
2314 // Collect static const data members with values.
2315 if ((DDTy
->getFlags() & DINode::FlagStaticMember
) ==
2316 DINode::FlagStaticMember
) {
2317 if (DDTy
->getConstant() && (isa
<ConstantInt
>(DDTy
->getConstant()) ||
2318 isa
<ConstantFP
>(DDTy
->getConstant())))
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.
2329 assert((DDTy
->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2330 uint64_t Offset
= DDTy
->getOffsetInBits();
2331 const DIType
*Ty
= DDTy
->getBaseType();
2332 bool FullyResolved
= false;
2333 while (!FullyResolved
) {
2334 switch (Ty
->getTag()) {
2335 case dwarf::DW_TAG_const_type
:
2336 case 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;
2347 const DICompositeType
*DCTy
= dyn_cast
<DICompositeType
>(Ty
);
2351 ClassInfo NestedInfo
= collectClassInfo(DCTy
);
2352 for (const ClassInfo::MemberInfo
&IndirectField
: NestedInfo
.Members
)
2353 Info
.Members
.push_back(
2354 {IndirectField
.MemberTypeNode
, IndirectField
.BaseOffset
+ Offset
});
2357 ClassInfo
CodeViewDebug::collectClassInfo(const DICompositeType
*Ty
) {
2359 // Add elements to structure type.
2360 DINodeArray Elements
= Ty
->getElements();
2361 for (auto *Element
: Elements
) {
2362 // We assume that the frontend provides all members in source declaration
2363 // order, which is what MSVC does.
2366 if (auto *SP
= dyn_cast
<DISubprogram
>(Element
)) {
2367 Info
.Methods
[SP
->getRawName()].push_back(SP
);
2368 } else if (auto *DDTy
= dyn_cast
<DIDerivedType
>(Element
)) {
2369 if (DDTy
->getTag() == dwarf::DW_TAG_member
) {
2370 collectMemberInfo(Info
, DDTy
);
2371 } else if (DDTy
->getTag() == dwarf::DW_TAG_inheritance
) {
2372 Info
.Inheritance
.push_back(DDTy
);
2373 } else if (DDTy
->getTag() == dwarf::DW_TAG_pointer_type
&&
2374 DDTy
->getName() == "__vtbl_ptr_type") {
2375 Info
.VShapeTI
= getTypeIndex(DDTy
);
2376 } else if (DDTy
->getTag() == dwarf::DW_TAG_typedef
) {
2377 Info
.NestedTypes
.push_back(DDTy
);
2378 } else if (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 } else if (auto *Composite
= dyn_cast
<DICompositeType
>(Element
)) {
2383 Info
.NestedTypes
.push_back(Composite
);
2385 // Skip other unrecognized kinds of elements.
2390 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType
*Ty
) {
2391 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2392 // if a complete type should be emitted instead of a forward reference.
2393 return Ty
->getName().empty() && Ty
->getIdentifier().empty() &&
2394 !Ty
->isForwardDecl();
2397 TypeIndex
CodeViewDebug::lowerTypeClass(const DICompositeType
*Ty
) {
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.
2402 if (shouldAlwaysEmitCompleteClassType(Ty
)) {
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.
2406 auto I
= CompleteTypeIndices
.find(Ty
);
2407 if (I
!= CompleteTypeIndices
.end() && I
->second
== TypeIndex())
2408 report_fatal_error("cannot debug circular reference to unnamed type");
2409 return 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.
2414 TypeRecordKind Kind
= getRecordKind(Ty
);
2416 ClassOptions::ForwardReference
| getCommonClassOptions(Ty
);
2417 std::string FullName
= getFullyQualifiedName(Ty
);
2418 ClassRecord
CR(Kind
, 0, CO
, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2419 FullName
, Ty
->getIdentifier());
2420 TypeIndex FwdDeclTI
= TypeTable
.writeLeafType(CR
);
2421 if (!Ty
->isForwardDecl())
2422 DeferredCompleteTypes
.push_back(Ty
);
2426 TypeIndex
CodeViewDebug::lowerCompleteTypeClass(const DICompositeType
*Ty
) {
2427 // Construct the field list and complete type record.
2428 TypeRecordKind Kind
= getRecordKind(Ty
);
2429 ClassOptions CO
= getCommonClassOptions(Ty
);
2432 unsigned FieldCount
;
2433 bool ContainsNestedClass
;
2434 std::tie(FieldTI
, VShapeTI
, FieldCount
, ContainsNestedClass
) =
2435 lowerRecordFieldList(Ty
);
2437 if (ContainsNestedClass
)
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.
2445 if (isNonTrivial(Ty
))
2446 CO
|= ClassOptions::HasConstructorOrDestructor
;
2448 std::string FullName
= getFullyQualifiedName(Ty
);
2450 uint64_t SizeInBytes
= Ty
->getSizeInBits() / 8;
2452 ClassRecord
CR(Kind
, FieldCount
, CO
, FieldTI
, TypeIndex(), VShapeTI
,
2453 SizeInBytes
, FullName
, Ty
->getIdentifier());
2454 TypeIndex ClassTI
= TypeTable
.writeLeafType(CR
);
2456 addUDTSrcLine(Ty
, ClassTI
);
2463 TypeIndex
CodeViewDebug::lowerTypeUnion(const DICompositeType
*Ty
) {
2464 // Emit the complete type for unnamed unions.
2465 if (shouldAlwaysEmitCompleteClassType(Ty
))
2466 return getCompleteTypeIndex(Ty
);
2469 ClassOptions::ForwardReference
| getCommonClassOptions(Ty
);
2470 std::string FullName
= getFullyQualifiedName(Ty
);
2471 UnionRecord
UR(0, CO
, TypeIndex(), 0, FullName
, Ty
->getIdentifier());
2472 TypeIndex FwdDeclTI
= TypeTable
.writeLeafType(UR
);
2473 if (!Ty
->isForwardDecl())
2474 DeferredCompleteTypes
.push_back(Ty
);
2478 TypeIndex
CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType
*Ty
) {
2479 ClassOptions CO
= ClassOptions::Sealed
| getCommonClassOptions(Ty
);
2481 unsigned FieldCount
;
2482 bool ContainsNestedClass
;
2483 std::tie(FieldTI
, std::ignore
, FieldCount
, ContainsNestedClass
) =
2484 lowerRecordFieldList(Ty
);
2486 if (ContainsNestedClass
)
2487 CO
|= ClassOptions::ContainsNestedClass
;
2489 uint64_t SizeInBytes
= Ty
->getSizeInBits() / 8;
2490 std::string FullName
= getFullyQualifiedName(Ty
);
2492 UnionRecord
UR(FieldCount
, CO
, FieldTI
, SizeInBytes
, FullName
,
2493 Ty
->getIdentifier());
2494 TypeIndex UnionTI
= TypeTable
.writeLeafType(UR
);
2496 addUDTSrcLine(Ty
, UnionTI
);
2503 std::tuple
<TypeIndex
, TypeIndex
, unsigned, bool>
2504 CodeViewDebug::lowerRecordFieldList(const DICompositeType
*Ty
) {
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
2509 unsigned MemberCount
= 0;
2510 ClassInfo Info
= collectClassInfo(Ty
);
2511 ContinuationRecordBuilder ContinuationBuilder
;
2512 ContinuationBuilder
.begin(ContinuationRecordKind::FieldList
);
2514 // Create base classes.
2515 for (const DIDerivedType
*I
: Info
.Inheritance
) {
2516 if (I
->getFlags() & DINode::FlagVirtual
) {
2518 unsigned VBPtrOffset
= I
->getVBPtrOffset();
2519 // FIXME: Despite the accessor name, the offset is really in bytes.
2520 unsigned VBTableIndex
= I
->getOffsetInBits() / 4;
2521 auto RecordKind
= (I
->getFlags() & DINode::FlagIndirectVirtualBase
) == DINode::FlagIndirectVirtualBase
2522 ? TypeRecordKind::IndirectVirtualBaseClass
2523 : TypeRecordKind::VirtualBaseClass
;
2524 VirtualBaseClassRecord
VBCR(
2525 RecordKind
, translateAccessFlags(Ty
->getTag(), I
->getFlags()),
2526 getTypeIndex(I
->getBaseType()), getVBPTypeIndex(), VBPtrOffset
,
2529 ContinuationBuilder
.writeMemberType(VBCR
);
2532 assert(I
->getOffsetInBits() % 8 == 0 &&
2533 "bases must be on byte boundaries");
2534 BaseClassRecord
BCR(translateAccessFlags(Ty
->getTag(), I
->getFlags()),
2535 getTypeIndex(I
->getBaseType()),
2536 I
->getOffsetInBits() / 8);
2537 ContinuationBuilder
.writeMemberType(BCR
);
2543 for (ClassInfo::MemberInfo
&MemberInfo
: Info
.Members
) {
2544 const DIDerivedType
*Member
= MemberInfo
.MemberTypeNode
;
2545 TypeIndex MemberBaseType
= getTypeIndex(Member
->getBaseType());
2546 StringRef MemberName
= Member
->getName();
2547 MemberAccess Access
=
2548 translateAccessFlags(Ty
->getTag(), Member
->getFlags());
2550 if (Member
->isStaticMember()) {
2551 StaticDataMemberRecord
SDMR(Access
, MemberBaseType
, MemberName
);
2552 ContinuationBuilder
.writeMemberType(SDMR
);
2557 // Virtual function pointer member.
2558 if ((Member
->getFlags() & DINode::FlagArtificial
) &&
2559 Member
->getName().starts_with("_vptr$")) {
2560 VFPtrRecord
VFPR(getTypeIndex(Member
->getBaseType()));
2561 ContinuationBuilder
.writeMemberType(VFPR
);
2567 uint64_t MemberOffsetInBits
=
2568 Member
->getOffsetInBits() + MemberInfo
.BaseOffset
;
2569 if (Member
->isBitField()) {
2570 uint64_t StartBitOffset
= MemberOffsetInBits
;
2571 if (const auto *CI
=
2572 dyn_cast_or_null
<ConstantInt
>(Member
->getStorageOffsetInBits())) {
2573 MemberOffsetInBits
= CI
->getZExtValue() + MemberInfo
.BaseOffset
;
2575 StartBitOffset
-= MemberOffsetInBits
;
2576 BitFieldRecord
BFR(MemberBaseType
, Member
->getSizeInBits(),
2578 MemberBaseType
= TypeTable
.writeLeafType(BFR
);
2580 uint64_t MemberOffsetInBytes
= MemberOffsetInBits
/ 8;
2581 DataMemberRecord
DMR(Access
, MemberBaseType
, MemberOffsetInBytes
,
2583 ContinuationBuilder
.writeMemberType(DMR
);
2588 for (auto &MethodItr
: Info
.Methods
) {
2589 StringRef Name
= MethodItr
.first
->getString();
2591 std::vector
<OneMethodRecord
> Methods
;
2592 for (const DISubprogram
*SP
: MethodItr
.second
) {
2593 TypeIndex MethodType
= getMemberFunctionType(SP
, Ty
);
2594 bool Introduced
= SP
->getFlags() & DINode::FlagIntroducedVirtual
;
2596 unsigned VFTableOffset
= -1;
2598 VFTableOffset
= SP
->getVirtualIndex() * getPointerSizeInBytes();
2600 Methods
.push_back(OneMethodRecord(
2601 MethodType
, translateAccessFlags(Ty
->getTag(), SP
->getFlags()),
2602 translateMethodKindFlags(SP
, Introduced
),
2603 translateMethodOptionFlags(SP
), VFTableOffset
, Name
));
2606 assert(!Methods
.empty() && "Empty methods map entry");
2607 if (Methods
.size() == 1)
2608 ContinuationBuilder
.writeMemberType(Methods
[0]);
2610 // FIXME: Make this use its own ContinuationBuilder so that
2611 // MethodOverloadList can be split correctly.
2612 MethodOverloadListRecord
MOLR(Methods
);
2613 TypeIndex MethodList
= TypeTable
.writeLeafType(MOLR
);
2615 OverloadedMethodRecord
OMR(Methods
.size(), MethodList
, Name
);
2616 ContinuationBuilder
.writeMemberType(OMR
);
2620 // Create nested classes.
2621 for (const DIType
*Nested
: Info
.NestedTypes
) {
2622 NestedTypeRecord
R(getTypeIndex(Nested
), Nested
->getName());
2623 ContinuationBuilder
.writeMemberType(R
);
2627 TypeIndex FieldTI
= TypeTable
.insertRecord(ContinuationBuilder
);
2628 return std::make_tuple(FieldTI
, Info
.VShapeTI
, MemberCount
,
2629 !Info
.NestedTypes
.empty());
2632 TypeIndex
CodeViewDebug::getVBPTypeIndex() {
2633 if (!VBPType
.getIndex()) {
2634 // Make a 'const int *' type.
2635 ModifierRecord
MR(TypeIndex::Int32(), ModifierOptions::Const
);
2636 TypeIndex ModifiedTI
= TypeTable
.writeLeafType(MR
);
2638 PointerKind PK
= getPointerSizeInBytes() == 8 ? PointerKind::Near64
2639 : PointerKind::Near32
;
2640 PointerMode PM
= PointerMode::Pointer
;
2641 PointerOptions PO
= PointerOptions::None
;
2642 PointerRecord
PR(ModifiedTI
, PK
, PM
, PO
, getPointerSizeInBytes());
2643 VBPType
= TypeTable
.writeLeafType(PR
);
2649 TypeIndex
CodeViewDebug::getTypeIndex(const DIType
*Ty
, const DIType
*ClassTy
) {
2650 // The null DIType is the void type. Don't try to hash it.
2652 return TypeIndex::Void();
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.
2657 auto I
= TypeIndices
.find({Ty
, ClassTy
});
2658 if (I
!= TypeIndices
.end())
2661 TypeLoweringScope
S(*this);
2662 TypeIndex TI
= lowerType(Ty
, ClassTy
);
2663 return recordTypeIndexForDINode(Ty
, TI
, ClassTy
);
2667 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType
*PtrTy
,
2668 const DISubroutineType
*SubroutineTy
) {
2669 assert(PtrTy
->getTag() == dwarf::DW_TAG_pointer_type
&&
2670 "this type must be a pointer type");
2672 PointerOptions Options
= PointerOptions::None
;
2673 if (SubroutineTy
->getFlags() & DINode::DIFlags::FlagLValueReference
)
2674 Options
= PointerOptions::LValueRefThisPointer
;
2675 else if (SubroutineTy
->getFlags() & DINode::DIFlags::FlagRValueReference
)
2676 Options
= 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.
2683 auto I
= TypeIndices
.find({PtrTy
, SubroutineTy
});
2684 if (I
!= TypeIndices
.end())
2687 TypeLoweringScope
S(*this);
2688 TypeIndex TI
= lowerTypePointer(PtrTy
, Options
);
2689 return recordTypeIndexForDINode(PtrTy
, TI
, SubroutineTy
);
2692 TypeIndex
CodeViewDebug::getTypeIndexForReferenceTo(const DIType
*Ty
) {
2693 PointerRecord
PR(getTypeIndex(Ty
),
2694 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2695 : PointerKind::Near32
,
2696 PointerMode::LValueReference
, PointerOptions::None
,
2697 Ty
->getSizeInBits() / 8);
2698 return TypeTable
.writeLeafType(PR
);
2701 TypeIndex
CodeViewDebug::getCompleteTypeIndex(const DIType
*Ty
) {
2702 // The null DIType is the void type. Don't try to hash it.
2704 return TypeIndex::Void();
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.
2709 if (Ty
->getTag() == dwarf::DW_TAG_typedef
)
2710 (void)getTypeIndex(Ty
);
2711 while (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.
2716 switch (Ty
->getTag()) {
2717 case dwarf::DW_TAG_class_type
:
2718 case dwarf::DW_TAG_structure_type
:
2719 case dwarf::DW_TAG_union_type
:
2722 return getTypeIndex(Ty
);
2725 const auto *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.
2733 if (!CTy
->getName().empty() || !CTy
->getIdentifier().empty()) {
2734 TypeIndex FwdDeclTI
= getTypeIndex(CTy
);
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.
2739 if (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
2746 auto InsertResult
= CompleteTypeIndices
.insert({CTy
, TypeIndex()});
2747 if (!InsertResult
.second
)
2748 return InsertResult
.first
->second
;
2751 switch (CTy
->getTag()) {
2752 case dwarf::DW_TAG_class_type
:
2753 case dwarf::DW_TAG_structure_type
:
2754 TI
= lowerCompleteTypeClass(CTy
);
2756 case dwarf::DW_TAG_union_type
:
2757 TI
= lowerCompleteTypeUnion(CTy
);
2760 llvm_unreachable("not a record");
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.
2775 void CodeViewDebug::emitDeferredCompleteTypes() {
2776 SmallVector
<const DICompositeType
*, 4> TypesToEmit
;
2777 while (!DeferredCompleteTypes
.empty()) {
2778 std::swap(DeferredCompleteTypes
, TypesToEmit
);
2779 for (const DICompositeType
*RecordTy
: TypesToEmit
)
2780 getCompleteTypeIndex(RecordTy
);
2781 TypesToEmit
.clear();
2785 void CodeViewDebug::emitLocalVariableList(const FunctionInfo
&FI
,
2786 ArrayRef
<LocalVariable
> Locals
) {
2787 // Get the sorted list of parameters and emit them first.
2788 SmallVector
<const LocalVariable
*, 6> Params
;
2789 for (const LocalVariable
&L
: Locals
)
2790 if (L
.DIVar
->isParameter())
2791 Params
.push_back(&L
);
2792 llvm::sort(Params
, [](const LocalVariable
*L
, const LocalVariable
*R
) {
2793 return L
->DIVar
->getArg() < R
->DIVar
->getArg();
2795 for (const LocalVariable
*L
: Params
)
2796 emitLocalVariable(FI
, *L
);
2798 // Next emit all non-parameters in the order that we found them.
2799 for (const LocalVariable
&L
: Locals
) {
2800 if (!L
.DIVar
->isParameter()) {
2801 if (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.
2804 const DIType
*Ty
= L
.DIVar
->getType();
2805 APSInt
Val(*L
.ConstantValue
);
2806 emitConstantSymbolRecord(Ty
, Val
, std::string(L
.DIVar
->getName()));
2808 emitLocalVariable(FI
, L
);
2814 void CodeViewDebug::emitLocalVariable(const FunctionInfo
&FI
,
2815 const LocalVariable
&Var
) {
2816 // LocalSym record, see SymbolRecord.h for more info.
2817 MCSymbol
*LocalEnd
= beginSymbolRecord(SymbolKind::S_LOCAL
);
2819 LocalSymFlags Flags
= LocalSymFlags::None
;
2820 if (Var
.DIVar
->isParameter())
2821 Flags
|= LocalSymFlags::IsParameter
;
2822 if (Var
.DefRanges
.empty())
2823 Flags
|= LocalSymFlags::IsOptimizedOut
;
2825 OS
.AddComment("TypeIndex");
2826 TypeIndex TI
= Var
.UseReferenceType
2827 ? getTypeIndexForReferenceTo(Var
.DIVar
->getType())
2828 : getCompleteTypeIndex(Var
.DIVar
->getType());
2829 OS
.emitInt32(TI
.getIndex());
2830 OS
.AddComment("Flags");
2831 OS
.emitInt16(static_cast<uint16_t>(Flags
));
2832 // Truncate the name so we won't overflow the record length field.
2833 emitNullTerminatedSymbolName(OS
, Var
.DIVar
->getName());
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.
2839 SmallString
<20> BytePrefix
;
2840 for (const auto &Pair
: Var
.DefRanges
) {
2841 LocalVarDef DefRange
= Pair
.first
;
2842 const auto &Ranges
= Pair
.second
;
2844 if (DefRange
.InMemory
) {
2845 int Offset
= DefRange
.DataOffset
;
2846 unsigned Reg
= 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.
2851 if (RegisterId(Reg
) == RegisterId::ESP
) {
2852 Reg
= unsigned(RegisterId::VFRAME
);
2853 Offset
+= 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.
2859 EncodedFramePtrReg EncFP
= encodeFramePtrReg(RegisterId(Reg
), TheCPU
);
2860 if (!DefRange
.IsSubfield
&& EncFP
!= EncodedFramePtrReg::None
&&
2861 (bool(Flags
& LocalSymFlags::IsParameter
)
2862 ? (EncFP
== FI
.EncodedParamFramePtrReg
)
2863 : (EncFP
== FI
.EncodedLocalFramePtrReg
))) {
2864 DefRangeFramePointerRelHeader DRHdr
;
2865 DRHdr
.Offset
= Offset
;
2866 OS
.emitCVDefRangeDirective(Ranges
, DRHdr
);
2868 uint16_t RegRelFlags
= 0;
2869 if (DefRange
.IsSubfield
) {
2870 RegRelFlags
= DefRangeRegisterRelSym::IsSubfieldFlag
|
2871 (DefRange
.StructOffset
2872 << DefRangeRegisterRelSym::OffsetInParentShift
);
2874 DefRangeRegisterRelHeader DRHdr
;
2875 DRHdr
.Register
= Reg
;
2876 DRHdr
.Flags
= RegRelFlags
;
2877 DRHdr
.BasePointerOffset
= Offset
;
2878 OS
.emitCVDefRangeDirective(Ranges
, DRHdr
);
2881 assert(DefRange
.DataOffset
== 0 && "unexpected offset into register");
2882 if (DefRange
.IsSubfield
) {
2883 DefRangeSubfieldRegisterHeader DRHdr
;
2884 DRHdr
.Register
= DefRange
.CVRegister
;
2885 DRHdr
.MayHaveNoName
= 0;
2886 DRHdr
.OffsetInParent
= DefRange
.StructOffset
;
2887 OS
.emitCVDefRangeDirective(Ranges
, DRHdr
);
2889 DefRangeRegisterHeader DRHdr
;
2890 DRHdr
.Register
= DefRange
.CVRegister
;
2891 DRHdr
.MayHaveNoName
= 0;
2892 OS
.emitCVDefRangeDirective(Ranges
, DRHdr
);
2898 void CodeViewDebug::emitLexicalBlockList(ArrayRef
<LexicalBlock
*> Blocks
,
2899 const FunctionInfo
& FI
) {
2900 for (LexicalBlock
*Block
: Blocks
)
2901 emitLexicalBlock(*Block
, FI
);
2904 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2905 /// lexical block scope.
2906 void CodeViewDebug::emitLexicalBlock(const LexicalBlock
&Block
,
2907 const FunctionInfo
& FI
) {
2908 MCSymbol
*RecordEnd
= beginSymbolRecord(SymbolKind::S_BLOCK32
);
2909 OS
.AddComment("PtrParent");
2910 OS
.emitInt32(0); // PtrParent
2911 OS
.AddComment("PtrEnd");
2912 OS
.emitInt32(0); // PtrEnd
2913 OS
.AddComment("Code size");
2914 OS
.emitAbsoluteSymbolDiff(Block
.End
, Block
.Begin
, 4); // Code Size
2915 OS
.AddComment("Function section relative address");
2916 OS
.emitCOFFSecRel32(Block
.Begin
, /*Offset=*/0); // Func Offset
2917 OS
.AddComment("Function section index");
2918 OS
.emitCOFFSectionIndex(FI
.Begin
); // Func Symbol
2919 OS
.AddComment("Lexical block name");
2920 emitNullTerminatedSymbolName(OS
, Block
.Name
); // Name
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.
2936 void CodeViewDebug::collectLexicalBlockInfo(
2937 SmallVectorImpl
<LexicalScope
*> &Scopes
,
2938 SmallVectorImpl
<LexicalBlock
*> &Blocks
,
2939 SmallVectorImpl
<LocalVariable
> &Locals
,
2940 SmallVectorImpl
<CVGlobalVariable
> &Globals
) {
2941 for (LexicalScope
*Scope
: Scopes
)
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.
2947 void CodeViewDebug::collectLexicalBlockInfo(
2948 LexicalScope
&Scope
,
2949 SmallVectorImpl
<LexicalBlock
*> &ParentBlocks
,
2950 SmallVectorImpl
<LocalVariable
> &ParentLocals
,
2951 SmallVectorImpl
<CVGlobalVariable
> &ParentGlobals
) {
2952 if (Scope
.isAbstractScope())
2955 // Gather information about the lexical scope including local variables,
2956 // global variables, and address ranges.
2957 bool IgnoreScope
= false;
2958 auto LI
= ScopeVariables
.find(&Scope
);
2959 SmallVectorImpl
<LocalVariable
> *Locals
=
2960 LI
!= ScopeVariables
.end() ? &LI
->second
: nullptr;
2961 auto GI
= ScopeGlobals
.find(Scope
.getScopeNode());
2962 SmallVectorImpl
<CVGlobalVariable
> *Globals
=
2963 GI
!= ScopeGlobals
.end() ? GI
->second
.get() : nullptr;
2964 const DILexicalBlock
*DILB
= dyn_cast
<DILexicalBlock
>(Scope
.getScopeNode());
2965 const SmallVectorImpl
<InsnRange
> &Ranges
= Scope
.getRanges();
2967 // Ignore lexical scopes which do not contain variables.
2968 if (!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.
2986 if (Ranges
.size() != 1 || !getLabelAfterInsn(Ranges
.front().second
))
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.
2995 ParentLocals
.append(Locals
->begin(), Locals
->end());
2997 ParentGlobals
.append(Globals
->begin(), Globals
->end());
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.
3008 auto BlockInsertion
= CurFn
->LexicalBlocks
.insert({DILB
, LexicalBlock()});
3009 if (!BlockInsertion
.second
)
3012 // Create a lexical block containing the variables and collect the
3013 // lexical block information for the children.
3014 const InsnRange
&Range
= Ranges
.front();
3015 assert(Range
.first
&& Range
.second
);
3016 LexicalBlock
&Block
= BlockInsertion
.first
->second
;
3017 Block
.Begin
= getLabelBeforeInsn(Range
.first
);
3018 Block
.End
= getLabelAfterInsn(Range
.second
);
3019 assert(Block
.Begin
&& "missing label for scope begin");
3020 assert(Block
.End
&& "missing label for scope end");
3021 Block
.Name
= DILB
->getName();
3023 Block
.Locals
= std::move(*Locals
);
3025 Block
.Globals
= std::move(*Globals
);
3026 ParentBlocks
.push_back(&Block
);
3027 collectLexicalBlockInfo(Scope
.getChildren(),
3033 void CodeViewDebug::endFunctionImpl(const MachineFunction
*MF
) {
3034 const Function
&GV
= MF
->getFunction();
3035 assert(FnDebugInfo
.count(&GV
));
3036 assert(CurFn
== FnDebugInfo
[&GV
].get());
3038 collectVariableInfo(GV
.getSubprogram());
3040 // Build the lexical block structure to emit for this routine.
3041 if (LexicalScope
*CFS
= LScopes
.getCurrentFunctionScope())
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.
3054 if (!CurFn
->HaveLineInfo
&& !GV
.getSubprogram()->isThunk()) {
3055 FnDebugInfo
.erase(&GV
);
3060 // Find heap alloc sites and add to list.
3061 for (const auto &MBB
: *MF
) {
3062 for (const auto &MI
: MBB
) {
3063 if (MDNode
*MD
= MI
.getHeapAllocMarker()) {
3064 CurFn
->HeapAllocSites
.push_back(std::make_tuple(getLabelBeforeInsn(&MI
),
3065 getLabelAfterInsn(&MI
),
3066 dyn_cast
<DIType
>(MD
)));
3071 bool isThumb
= Triple(MMI
->getModule()->getTargetTriple()).getArch() ==
3072 llvm::Triple::ArchType::thumb
;
3073 collectDebugInfoForJumpTables(MF
, isThumb
);
3075 CurFn
->Annotations
= MF
->getCodeViewAnnotations();
3077 CurFn
->End
= Asm
->getFunctionEnd();
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
3086 static bool isUsableDebugLoc(DebugLoc DL
) {
3087 return DL
&& DL
.getLine() != 0;
3090 void CodeViewDebug::beginInstruction(const MachineInstr
*MI
) {
3091 DebugHandlerBase::beginInstruction(MI
);
3093 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3094 if (!Asm
|| !CurFn
|| MI
->isDebugInstr() ||
3095 MI
->getFlag(MachineInstr::FrameSetup
))
3098 // If the first instruction of a new MBB has no location, find the first
3099 // instruction with a location and use that.
3100 DebugLoc DL
= MI
->getDebugLoc();
3101 if (!isUsableDebugLoc(DL
) && MI
->getParent() != PrevInstBB
) {
3102 for (const auto &NextMI
: *MI
->getParent()) {
3103 if (NextMI
.isDebugInstr())
3105 DL
= NextMI
.getDebugLoc();
3106 if (isUsableDebugLoc(DL
))
3109 // FIXME: Handle the case where the BB has no valid locations. This would
3110 // probably require doing a real dataflow analysis.
3112 PrevInstBB
= MI
->getParent();
3114 // If we still don't have a debug location, don't record a location.
3115 if (!isUsableDebugLoc(DL
))
3118 maybeRecordLocation(DL
, Asm
->MF
);
3121 MCSymbol
*CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind
) {
3122 MCSymbol
*BeginLabel
= MMI
->getContext().createTempSymbol(),
3123 *EndLabel
= MMI
->getContext().createTempSymbol();
3124 OS
.emitInt32(unsigned(Kind
));
3125 OS
.AddComment("Subsection size");
3126 OS
.emitAbsoluteSymbolDiff(EndLabel
, BeginLabel
, 4);
3127 OS
.emitLabel(BeginLabel
);
3131 void CodeViewDebug::endCVSubsection(MCSymbol
*EndLabel
) {
3132 OS
.emitLabel(EndLabel
);
3133 // Every subsection must be aligned to a 4-byte boundary.
3134 OS
.emitValueToAlignment(Align(4));
3137 static StringRef
getSymbolName(SymbolKind SymKind
) {
3138 for (const EnumEntry
<SymbolKind
> &EE
: getSymbolTypeNames())
3139 if (EE
.Value
== SymKind
)
3144 MCSymbol
*CodeViewDebug::beginSymbolRecord(SymbolKind SymKind
) {
3145 MCSymbol
*BeginLabel
= MMI
->getContext().createTempSymbol(),
3146 *EndLabel
= MMI
->getContext().createTempSymbol();
3147 OS
.AddComment("Record length");
3148 OS
.emitAbsoluteSymbolDiff(EndLabel
, BeginLabel
, 2);
3149 OS
.emitLabel(BeginLabel
);
3150 if (OS
.isVerboseAsm())
3151 OS
.AddComment("Record kind: " + getSymbolName(SymKind
));
3152 OS
.emitInt16(unsigned(SymKind
));
3156 void 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
3161 OS
.emitValueToAlignment(Align(4));
3162 OS
.emitLabel(SymEnd
);
3165 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind
) {
3166 OS
.AddComment("Record length");
3168 if (OS
.isVerboseAsm())
3169 OS
.AddComment("Record kind: " + getSymbolName(EndKind
));
3170 OS
.emitInt16(uint16_t(EndKind
)); // Record Kind
3173 void CodeViewDebug::emitDebugInfoForUDTs(
3174 const std::vector
<std::pair
<std::string
, const DIType
*>> &UDTs
) {
3176 size_t OriginalSize
= UDTs
.size();
3178 for (const auto &UDT
: UDTs
) {
3179 const DIType
*T
= UDT
.second
;
3180 assert(shouldEmitUdt(T
));
3181 MCSymbol
*UDTRecordEnd
= beginSymbolRecord(SymbolKind::S_UDT
);
3182 OS
.AddComment("Type");
3183 OS
.emitInt32(getCompleteTypeIndex(T
).getIndex());
3184 assert(OriginalSize
== UDTs
.size() &&
3185 "getCompleteTypeIndex found new UDTs!");
3186 emitNullTerminatedSymbolName(OS
, UDT
.first
);
3187 endSymbolRecord(UDTRecordEnd
);
3191 void CodeViewDebug::collectGlobalVariableInfo() {
3192 DenseMap
<const DIGlobalVariableExpression
*, const GlobalVariable
*>
3194 for (const GlobalVariable
&GV
: MMI
->getModule()->globals()) {
3195 SmallVector
<DIGlobalVariableExpression
*, 1> GVEs
;
3196 GV
.getDebugInfo(GVEs
);
3197 for (const auto *GVE
: GVEs
)
3198 GlobalMap
[GVE
] = &GV
;
3201 NamedMDNode
*CUs
= MMI
->getModule()->getNamedMetadata("llvm.dbg.cu");
3202 for (const MDNode
*Node
: CUs
->operands()) {
3203 const auto *CU
= cast
<DICompileUnit
>(Node
);
3204 for (const auto *GVE
: CU
->getGlobalVariables()) {
3205 const DIGlobalVariable
*DIGV
= GVE
->getVariable();
3206 const DIExpression
*DIE
= GVE
->getExpression();
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
3211 if (DIGV
->getName().empty()) continue;
3213 if ((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.
3223 if (GlobalMap
.count(GVE
) == 0 && DIE
->isConstant()) {
3224 CVGlobalVariable CVGV
= {DIGV
, DIE
};
3225 GlobalVariables
.emplace_back(std::move(CVGV
));
3228 const auto *GV
= GlobalMap
.lookup(GVE
);
3229 if (!GV
|| GV
->isDeclarationForLinker())
3232 DIScope
*Scope
= DIGV
->getScope();
3233 SmallVector
<CVGlobalVariable
, 1> *VariableList
;
3234 if (Scope
&& isa
<DILocalScope
>(Scope
)) {
3235 // Locate a global variable list for this scope, creating one if
3237 auto Insertion
= ScopeGlobals
.insert(
3238 {Scope
, std::unique_ptr
<GlobalVariableList
>()});
3239 if (Insertion
.second
)
3240 Insertion
.first
->second
= std::make_unique
<GlobalVariableList
>();
3241 VariableList
= Insertion
.first
->second
.get();
3242 } else if (GV
->hasComdat())
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
};
3249 VariableList
->emplace_back(std::move(CVGV
));
3254 void CodeViewDebug::collectDebugInfoForGlobals() {
3255 for (const CVGlobalVariable
&CVGV
: GlobalVariables
) {
3256 const DIGlobalVariable
*DIGV
= CVGV
.DIGV
;
3257 const DIScope
*Scope
= DIGV
->getScope();
3258 getCompleteTypeIndex(DIGV
->getType());
3259 getFullyQualifiedName(Scope
, DIGV
->getName());
3262 for (const CVGlobalVariable
&CVGV
: ComdatVariables
) {
3263 const DIGlobalVariable
*DIGV
= CVGV
.DIGV
;
3264 const DIScope
*Scope
= DIGV
->getScope();
3265 getCompleteTypeIndex(DIGV
->getType());
3266 getFullyQualifiedName(Scope
, DIGV
->getName());
3270 void 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);
3275 if (!GlobalVariables
.empty() || !StaticConstMembers
.empty()) {
3276 OS
.AddComment("Symbol subsection for globals");
3277 MCSymbol
*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.
3285 for (const CVGlobalVariable
&CVGV
: ComdatVariables
) {
3286 const GlobalVariable
*GV
= cast
<const GlobalVariable
*>(CVGV
.GVInfo
);
3287 MCSymbol
*GVSym
= Asm
->getSymbol(GV
);
3288 OS
.AddComment("Symbol subsection for " +
3289 Twine(GlobalValue::dropLLVMManglingEscape(GV
->getName())));
3290 switchToDebugSectionForSymbol(GVSym
);
3291 MCSymbol
*EndLabel
= beginCVSubsection(DebugSubsectionKind::Symbols
);
3292 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3293 emitDebugInfoForGlobal(CVGV
);
3294 endCVSubsection(EndLabel
);
3298 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3299 NamedMDNode
*CUs
= MMI
->getModule()->getNamedMetadata("llvm.dbg.cu");
3300 for (const MDNode
*Node
: CUs
->operands()) {
3301 for (auto *Ty
: cast
<DICompileUnit
>(Node
)->getRetainedTypes()) {
3302 if (DIType
*RT
= dyn_cast
<DIType
>(Ty
)) {
3304 // FIXME: Add to global/local DTU list.
3310 // Emit each global variable in the specified array.
3311 void CodeViewDebug::emitGlobalVariableList(ArrayRef
<CVGlobalVariable
> Globals
) {
3312 for (const CVGlobalVariable
&CVGV
: Globals
) {
3313 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3314 emitDebugInfoForGlobal(CVGV
);
3318 void CodeViewDebug::emitConstantSymbolRecord(const DIType
*DTy
, APSInt
&Value
,
3319 const std::string
&QualifiedName
) {
3320 MCSymbol
*SConstantEnd
= beginSymbolRecord(SymbolKind::S_CONSTANT
);
3321 OS
.AddComment("Type");
3322 OS
.emitInt32(getTypeIndex(DTy
).getIndex());
3324 OS
.AddComment("Value");
3326 // Encoded integers shouldn't need more than 10 bytes.
3328 BinaryStreamWriter
Writer(Data
, llvm::endianness::little
);
3329 CodeViewRecordIO
IO(Writer
);
3330 cantFail(IO
.mapEncodedInteger(Value
));
3331 StringRef
SRef((char *)Data
, Writer
.getOffset());
3332 OS
.emitBinaryData(SRef
);
3334 OS
.AddComment("Name");
3335 emitNullTerminatedSymbolName(OS
, QualifiedName
);
3336 endSymbolRecord(SConstantEnd
);
3339 void CodeViewDebug::emitStaticConstMemberList() {
3340 for (const DIDerivedType
*DTy
: StaticConstMembers
) {
3341 const DIScope
*Scope
= DTy
->getScope();
3344 if (const ConstantInt
*CI
=
3345 dyn_cast_or_null
<ConstantInt
>(DTy
->getConstant()))
3346 Value
= APSInt(CI
->getValue(),
3347 DebugHandlerBase::isUnsignedDIType(DTy
->getBaseType()));
3348 else if (const ConstantFP
*CFP
=
3349 dyn_cast_or_null
<ConstantFP
>(DTy
->getConstant()))
3350 Value
= APSInt(CFP
->getValueAPF().bitcastToAPInt(), true);
3352 llvm_unreachable("cannot emit a constant without a value");
3354 emitConstantSymbolRecord(DTy
->getBaseType(), Value
,
3355 getFullyQualifiedName(Scope
, DTy
->getName()));
3359 static bool isFloatDIType(const DIType
*Ty
) {
3360 if (isa
<DICompositeType
>(Ty
))
3363 if (auto *DTy
= dyn_cast
<DIDerivedType
>(Ty
)) {
3364 dwarf::Tag T
= (dwarf::Tag
)Ty
->getTag();
3365 if (T
== dwarf::DW_TAG_pointer_type
||
3366 T
== dwarf::DW_TAG_ptr_to_member_type
||
3367 T
== dwarf::DW_TAG_reference_type
||
3368 T
== dwarf::DW_TAG_rvalue_reference_type
)
3370 assert(DTy
->getBaseType() && "Expected valid base type");
3371 return isFloatDIType(DTy
->getBaseType());
3374 auto *BTy
= cast
<DIBasicType
>(Ty
);
3375 return (BTy
->getEncoding() == dwarf::DW_ATE_float
);
3378 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable
&CVGV
) {
3379 const DIGlobalVariable
*DIGV
= CVGV
.DIGV
;
3381 const DIScope
*Scope
= DIGV
->getScope();
3382 // For static data members, get the scope from the declaration.
3383 if (const auto *MemberDecl
= dyn_cast_or_null
<DIDerivedType
>(
3384 DIGV
->getRawStaticDataMemberDeclaration()))
3385 Scope
= 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.
3389 std::string QualifiedName
=
3390 (moduleIsInFortran() || (Scope
&& isa
<DILocalScope
>(Scope
)))
3391 ? std::string(DIGV
->getName())
3392 : getFullyQualifiedName(Scope
, DIGV
->getName());
3394 if (const GlobalVariable
*GV
=
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.
3398 MCSymbol
*GVSym
= Asm
->getSymbol(GV
);
3399 SymbolKind DataSym
= GV
->isThreadLocal()
3400 ? (DIGV
->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3401 : SymbolKind::S_GTHREAD32
)
3402 : (DIGV
->isLocalToUnit() ? SymbolKind::S_LDATA32
3403 : SymbolKind::S_GDATA32
);
3404 MCSymbol
*DataEnd
= beginSymbolRecord(DataSym
);
3405 OS
.AddComment("Type");
3406 OS
.emitInt32(getCompleteTypeIndex(DIGV
->getType()).getIndex());
3407 OS
.AddComment("DataOffset");
3409 // Use the offset seen while collecting info on globals.
3410 uint64_t Offset
= CVGlobalVariableOffsets
.lookup(DIGV
);
3411 OS
.emitCOFFSecRel32(GVSym
, Offset
);
3413 OS
.AddComment("Segment");
3414 OS
.emitCOFFSectionIndex(GVSym
);
3415 OS
.AddComment("Name");
3416 const unsigned LengthOfDataRecord
= 12;
3417 emitNullTerminatedSymbolName(OS
, QualifiedName
, LengthOfDataRecord
);
3418 endSymbolRecord(DataEnd
);
3420 const DIExpression
*DIE
= cast
<const DIExpression
*>(CVGV
.GVInfo
);
3421 assert(DIE
->isConstant() &&
3422 "Global constant variables must contain a constant expression.");
3424 // Use unsigned for floats.
3425 bool isUnsigned
= isFloatDIType(DIGV
->getType())
3427 : DebugHandlerBase::isUnsignedDIType(DIGV
->getType());
3428 APSInt
Value(APInt(/*BitWidth=*/64, DIE
->getElement(1)), isUnsigned
);
3429 emitConstantSymbolRecord(DIGV
->getType(), Value
, QualifiedName
);
3433 void forEachJumpTableBranch(
3434 const MachineFunction
*MF
, bool isThumb
,
3435 const std::function
<void(const MachineJumpTableInfo
&, const MachineInstr
&,
3436 int64_t)> &Callback
) {
3437 auto JTI
= MF
->getJumpTableInfo();
3438 if (JTI
&& !JTI
->isEmpty()) {
3440 auto UsedJTs
= llvm::SmallBitVector(JTI
->getJumpTables().size());
3442 for (const auto &MBB
: *MF
) {
3443 // Search for indirect branches...
3444 const auto LastMI
= MBB
.getFirstTerminator();
3445 if (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
3453 for (const auto &MO
: LastMI
->operands()) {
3455 unsigned 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.
3467 for (auto I
= MBB
.instr_rbegin(), E
= MBB
.instr_rend(); I
!= E
; ++I
) {
3468 if (I
->isJumpTableDebugInfo()) {
3469 unsigned Index
= I
->getOperand(0).getImm();
3473 Callback(*JTI
, *LastMI
, Index
);
3481 assert(UsedJTs
.all() &&
3482 "Some of jump tables were not used in a debug info instruction");
3487 void CodeViewDebug::discoverJumpTableBranches(const MachineFunction
*MF
,
3489 forEachJumpTableBranch(
3491 [this](const MachineJumpTableInfo
&, const MachineInstr
&BranchMI
,
3492 int64_t) { requestLabelBeforeInsn(&BranchMI
); });
3495 void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction
*MF
,
3497 forEachJumpTableBranch(
3499 [this, MF
](const MachineJumpTableInfo
&JTI
, const MachineInstr
&BranchMI
,
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
3504 const MCSymbol
*Base
;
3505 uint64_t BaseOffset
= 0;
3506 const MCSymbol
*Branch
= getLabelBeforeInsn(&BranchMI
);
3507 JumpTableEntrySize EntrySize
;
3508 switch (JTI
.getEntryKind()) {
3509 case MachineJumpTableInfo::EK_Custom32
:
3510 case MachineJumpTableInfo::EK_GPRel32BlockAddress
:
3511 case MachineJumpTableInfo::EK_GPRel64BlockAddress
:
3513 "EK_Custom32, EK_GPRel32BlockAddress, and "
3514 "EK_GPRel64BlockAddress should never be emitted for COFF");
3515 case MachineJumpTableInfo::EK_BlockAddress
:
3516 // Each entry is an absolute address.
3517 EntrySize
= JumpTableEntrySize::Pointer
;
3520 case MachineJumpTableInfo::EK_Inline
:
3521 case MachineJumpTableInfo::EK_LabelDifference32
:
3522 case MachineJumpTableInfo::EK_LabelDifference64
:
3523 // Ask the AsmPrinter.
3524 std::tie(Base
, BaseOffset
, Branch
, EntrySize
) =
3525 Asm
->getCodeViewJumpTableInfo(JumpTableIndex
, &BranchMI
, Branch
);
3529 CurFn
->JumpTables
.push_back(
3530 {EntrySize
, Base
, BaseOffset
, Branch
,
3531 MF
->getJTISymbol(JumpTableIndex
, MMI
->getContext()),
3532 JTI
.getJumpTables()[JumpTableIndex
].MBBs
.size()});
3536 void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo
&FI
) {
3537 for (auto JumpTable
: FI
.JumpTables
) {
3538 MCSymbol
*JumpTableEnd
= beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE
);
3539 if (JumpTable
.Base
) {
3540 OS
.AddComment("Base offset");
3541 OS
.emitCOFFSecRel32(JumpTable
.Base
, JumpTable
.BaseOffset
);
3542 OS
.AddComment("Base section index");
3543 OS
.emitCOFFSectionIndex(JumpTable
.Base
);
3545 OS
.AddComment("Base offset");
3547 OS
.AddComment("Base section index");
3550 OS
.AddComment("Switch type");
3551 OS
.emitInt16(static_cast<uint16_t>(JumpTable
.EntrySize
));
3552 OS
.AddComment("Branch offset");
3553 OS
.emitCOFFSecRel32(JumpTable
.Branch
, /*Offset=*/0);
3554 OS
.AddComment("Table offset");
3555 OS
.emitCOFFSecRel32(JumpTable
.Table
, /*Offset=*/0);
3556 OS
.AddComment("Branch section index");
3557 OS
.emitCOFFSectionIndex(JumpTable
.Branch
);
3558 OS
.AddComment("Table section index");
3559 OS
.emitCOFFSectionIndex(JumpTable
.Table
);
3560 OS
.AddComment("Entries count");
3561 OS
.emitInt32(JumpTable
.TableSize
);
3562 endSymbolRecord(JumpTableEnd
);
3566 void CodeViewDebug::emitInlinees(
3567 const SmallSet
<codeview::TypeIndex
, 1> &Inlinees
) {
3568 // Divide the list of inlinees into chunks such that each chunk fits within
3570 constexpr size_t ChunkSize
=
3571 (MaxRecordLength
- sizeof(SymbolKind
) - sizeof(uint32_t)) /
3574 SmallVector
<TypeIndex
> SortedInlinees
{Inlinees
.begin(), Inlinees
.end()};
3575 llvm::sort(SortedInlinees
);
3577 size_t CurrentIndex
= 0;
3578 while (CurrentIndex
< SortedInlinees
.size()) {
3579 auto Symbol
= beginSymbolRecord(SymbolKind::S_INLINEES
);
3580 auto CurrentChunkSize
=
3581 std::min(ChunkSize
, SortedInlinees
.size() - CurrentIndex
);
3582 OS
.AddComment("Count");
3583 OS
.emitInt32(CurrentChunkSize
);
3585 const size_t CurrentChunkEnd
= CurrentIndex
+ CurrentChunkSize
;
3586 for (; CurrentIndex
< CurrentChunkEnd
; ++CurrentIndex
) {
3587 OS
.AddComment("Inlinee");
3588 OS
.emitInt32(SortedInlinees
[CurrentIndex
].getIndex());
3590 endSymbolRecord(Symbol
);