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