LLVM 23.0.0git
CodeViewDebug.cpp
Go to the documentation of this file.
1//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing Microsoft CodeView debug info.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeViewDebug.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
33#include "llvm/Config/llvm-config.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalValue.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"
55#include "llvm/MC/MCStreamer.h"
56#include "llvm/MC/MCSymbol.h"
59#include "llvm/Support/Error.h"
62#include "llvm/Support/Path.h"
63#include "llvm/Support/SMLoc.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(TI));
104 }
105 return TypeName;
106 }
107
108private:
109 MCStreamer *OS = nullptr;
110 TypeCollection &TypeTable;
111};
112} // namespace
113
115 switch (Type) {
117 return CPUType::Pentium3;
119 return CPUType::X64;
121 // LLVM currently doesn't support Windows CE and so thumb
122 // here is indiscriminately mapped to ARMNT specifically.
123 return CPUType::ARMNT;
125 return CPUType::ARM64;
127 return CPUType::MIPS;
129 return CPUType::Unknown;
130 default:
131 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
132 }
133}
134
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("/") || Filename.starts_with("/")) {
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(':') == 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(Filepath, '/', '\\');
170
171 // Remove all "\.\" with "\".
172 size_t Cursor = 0;
173 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
174 Filepath.erase(Cursor, 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("\\..\\", 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('\\', Cursor - 1);
185 if (PrevSlash == std::string::npos)
186 // Something's wrong, abort.
187 break;
188
189 Filepath.erase(PrevSlash, 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("\\\\", Cursor)) != std::string::npos)
197 Filepath.erase(Cursor, 1);
198
199 return Filepath;
200}
201
202unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
203 StringRef FullPath = getFullFilepath(F);
204 unsigned NextId = FileIdMap.size() + 1;
205 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, 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(F->getChecksum()->Value);
212 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
213 memcpy(CKMem, Checksum.data(), 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;
224 CSKind = FileChecksumKind::SHA256;
225 break;
226 }
227 }
228 bool Success = OS.emitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
229 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(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(OuterIA, InlinedAt->getScope()->getSubprogram())
246 .SiteFuncId;
247
248 Site->SiteFuncId = NextFuncId++;
249 OS.emitCVInlineSiteIdDirective(
250 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
251 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
252 Site->Inlinee = Inlinee;
253 InlinedSubprograms.insert(Inlinee);
254 auto InlineeIdx = getFuncIdForSubprogram(Inlinee);
255
256 if (InlinedAt->getInlinedAt() == nullptr)
257 CurFn->Inlinees.insert(InlineeIdx);
258 }
259 return *Site;
260}
261
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>(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>(Scope))
291 DeferredCompleteTypes.push_back(Ty);
292
293 StringRef ScopeName = getPrettyScopeName(Scope);
294 if (!ScopeName.empty())
295 QualifiedNameComponents.push_back(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(QualifiedNameComponents)) {
306 FullyQualifiedName.append(std::string(QualifiedNameComponent));
307 FullyQualifiedName.append("::");
308 }
309 FullyQualifiedName.append(std::string(TypeName));
310 return FullyQualifiedName;
311}
312
314 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
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 }
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, Name);
334}
335
336std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
337 const DIScope *Scope = Ty->getScope();
338 return getFullyQualifiedName(Scope, getPrettyScopeName(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>(Scope) || isa<DISubprogram>(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({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(Scope);
364 StringIdRecord SID(TypeIndex(), ScopeName);
365 auto TI = TypeTable.writeLeafType(SID);
366 return recordTypeIndexForDINode(Scope, TI);
367}
368
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(0, 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({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(SP->getName());
400
401 const DIScope *Scope = SP->getScope();
402 TypeIndex TI;
403 if (const auto *Class = dyn_cast_or_null<DICompositeType>(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(Class);
408 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
409 DisplayName);
410 TI = TypeTable.writeLeafType(MFuncId);
411 } else {
412 // Otherwise, this must be a free function.
413 TypeIndex ParentScope = getScopeIndex(Scope);
414 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
415 TI = TypeTable.writeLeafType(FuncId);
416 }
417
418 return recordTypeIndexForDINode(SP, TI);
419}
420
421static bool isNonTrivial(const DICompositeType *DCTy) {
422 return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
423}
424
425static FunctionOptions
427 const DICompositeType *ClassTy = nullptr,
428 StringRef SPName = StringRef("")) {
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>(ReturnTy))
439 if (isNonTrivial(ReturnDCTy) || ClassTy)
441
442 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
443 if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
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({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(SP->getType(), Class, SP->getName());
473 TypeIndex TI = lowerTypeMemberFunction(
474 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
475 return recordTypeIndexForDINode(SP, TI, Class);
476}
477
478TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
479 TypeIndex TI,
480 const DIType *ClassTy) {
481 auto InsertResult = TypeIndices.insert({{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(std::move(Var));
498 } else {
499 // This variable goes into the corresponding lexical scope.
500 ScopeVariables[LS].emplace_back(std::move(Var));
501 }
502}
503
505 const DILocation *Loc) {
506 if (!llvm::is_contained(Locs, Loc))
507 Locs.push_back(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(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(SiteLoc, 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(SiteLoc, Loc->getScope()->getSubprogram());
553 if (!FirstLoc)
554 addLocIfNotPresent(Site.ChildSites, Loc);
555 FirstLoc = false;
556 Loc = SiteLoc;
557 }
558 addLocIfNotPresent(CurFn->ChildSites, Loc);
559 }
560
561 OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
562 /*PrologueEnd=*/false, /*IsStmt=*/false,
563 DL->getFilename(), SMLoc());
564}
565
566void CodeViewDebug::emitCodeViewMagicVersion() {
567 OS.emitValueToAlignment(Align(4));
568 OS.AddComment("Debug section magic");
569 OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
570}
571
572static SourceLanguage
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
606 auto MaybeLName = dwarf::toDW_LNAME(DWLang);
607 if (!MaybeLName)
609
610 return MapDWARFLanguageToCVLang(MaybeLName->first);
611}
612
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(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("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>(Node);
639 DISourceLanguageName Lang = TheCU->getSourceLanguage();
640 CurrentSourceLanguage =
641 Lang.hasVersionedName()
643 static_cast<dwarf::SourceLanguageName>(Lang.getName()))
645 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>(M->getModuleFlag("CodeViewGHash"));
657 EmitDebugGlobalHashes = GH && !GH->isZero();
658}
659
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(nullptr);
672
673 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
674 emitObjName();
675 emitCompilerInformation();
676 endCVSubsection(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(P.first, *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(nullptr);
704
705 // Emit UDT records for any types used by global variables.
706 if (!GlobalUDTs.empty()) {
707 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
708 emitDebugInfoForUDTs(GlobalUDTs);
709 endCVSubsection(SymbolsEnd);
710 }
711
712 // This subsection holds a file index to offset in string table table.
713 OS.AddComment("File index to string table offset subsection");
714 OS.emitCVFileChecksumsDirective();
715
716 // This subsection holds the string table.
717 OS.AddComment("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
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(MaxRecordLength - MaxFixedRecordLength - 1));
744 NullTerminatedString.push_back('\0');
745 OS.emitBytes(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(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(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(*B);
768
769 Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
770
771 if (E) {
772 logAllUnhandledErrors(std::move(E), errs(), "error: ");
773 llvm_unreachable("produced malformed type record");
774 }
775
776 B = Table.getNext(*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(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
787
788 OS.emitValueToAlignment(Align(4));
789 OS.AddComment("Magic");
791 OS.AddComment("Section Version");
792 OS.emitInt16(0);
793 OS.AddComment("Hash Algorithm");
794 OS.emitInt16(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("{0:X+} [{1}]", TI.getIndex(), GHR);
804 OS.AddComment(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(S);
811 }
812}
813
814void CodeViewDebug::emitObjName() {
815 MCSymbol *CompilerEnd = beginSymbolRecord(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("Signature");
828 OS.emitIntValue(0, 4);
829
830 OS.AddComment("Object name");
831 emitNullTerminatedSymbolName(OS, PathRef);
832
833 endSymbolRecord(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("marked_for_windows_hot_patching")) {
842 if (hotPatchInfo == nullptr)
843 hotPatchInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
844 MCSymbol *HotPatchEnd = beginSymbolRecord(SymbolKind::S_HOTPATCHFUNC);
845 auto *SP = F.getSubprogram();
846 OS.AddComment("Function");
847 OS.emitInt32(getFuncIdForSubprogram(SP).getIndex());
848 OS.AddComment("Name");
849 emitNullTerminatedSymbolName(OS, F.getName());
850 endSymbolRecord(HotPatchEnd);
851 }
852 }
853
854 if (hotPatchInfo != nullptr)
855 endCVSubsection(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 = {{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>(V.Part[N], 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(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("Flags and language");
903 OS.emitInt32(Flags);
904
905 OS.AddComment("CPUType");
906 OS.emitInt16(static_cast<uint64_t>(TheCPU));
907
908 StringRef CompilerVersion = "0";
909 if (TheCU)
910 CompilerVersion = TheCU->getProducer();
911
912 Version FrontVer = parseVersion(CompilerVersion);
913 OS.AddComment("Frontend version");
914 for (int N : FrontVer.Part) {
915 OS.emitInt16(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>(Major, std::numeric_limits<uint16_t>::max());
926 Version BackVer = {{ Major, 0, 0, 0 }};
927 OS.AddComment("Backend version");
928 for (int N : BackVer.Part)
929 OS.emitInt16(N);
930
931 OS.AddComment("Null-terminated compiler version string");
932 emitNullTerminatedSymbolName(OS, CompilerVersion);
933
934 endSymbolRecord(CompilerEnd);
935}
936
938 StringRef S) {
939 StringIdRecord SIR(TypeIndex(0x0), S);
940 return TypeTable.writeLeafType(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("llvm.dbg.cu");
956 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
957 const auto *CU = cast<DICompileUnit>(Node);
958 const DIFile *MainSourceFile = CU->getFile();
959 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
960 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
961 BuildInfoArgs[BuildInfoRecord::SourceFile] =
962 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
963 // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
964 BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
965 getStringIdTypeIdx(TypeTable, "");
966 BuildInfoArgs[BuildInfoRecord::BuildTool] =
967 getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
969 TypeTable, Asm->TM.Options.MCOptions.CommandlineArgs);
970
971 BuildInfoRecord BIR(BuildInfoArgs);
972 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(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(DebugSubsectionKind::Symbols);
977 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
978 OS.AddComment("LF_BUILDINFO index");
979 OS.emitInt32(BuildInfoIndex.getIndex());
980 endSymbolRecord(BIEnd);
981 endCVSubsection(BISubsecEnd);
982}
983
984void CodeViewDebug::emitInlineeLinesSubsection() {
985 if (InlinedSubprograms.empty())
986 return;
987
988 OS.AddComment("Inlinee lines subsection");
989 MCSymbol *InlineEnd = beginCVSubsection(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("Inlinee lines signature");
996 OS.emitInt32(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(SP->getFile());
1004 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
1005 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
1006 OS.addBlankLine();
1007 OS.AddComment("Type index of inlined function");
1008 OS.emitInt32(InlineeIdx.getIndex());
1009 OS.AddComment("Offset into filechecksum table");
1010 OS.emitCVFileChecksumOffsetDirective(FileId);
1011 OS.AddComment("Starting line number");
1012 OS.emitInt32(SP->getLine());
1013 }
1014
1015 endCVSubsection(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(SymbolKind::S_INLINESITE);
1026
1027 OS.AddComment("PtrParent");
1028 OS.emitInt32(0);
1029 OS.AddComment("PtrEnd");
1030 OS.emitInt32(0);
1031 OS.AddComment("Inlinee type index");
1032 OS.emitInt32(InlineeIdx.getIndex());
1033
1034 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
1035 unsigned StartLineNum = Site.Inlinee->getLine();
1036
1037 OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
1038 FI.Begin, FI.End);
1039
1040 endSymbolRecord(InlineEnd);
1041
1042 emitLocalVariableList(FI, 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(ChildSite);
1047 assert(I != FI.InlineSites.end() &&
1048 "child site not in function inline site map");
1049 emitInlinedCallSite(FI, ChildSite, I->second);
1050 }
1051
1052 // Close the scope.
1053 emitEndSymbolRecord(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(DebugSec, KeySym);
1067
1068 OS.switchSection(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(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(GV->getName()));
1083 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
1084
1085 OS.AddComment("Symbol subsection for " + Twine(FuncName));
1086 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1087
1088 // Emit S_THUNK32
1089 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
1090 OS.AddComment("PtrParent");
1091 OS.emitInt32(0);
1092 OS.AddComment("PtrEnd");
1093 OS.emitInt32(0);
1094 OS.AddComment("PtrNext");
1095 OS.emitInt32(0);
1096 OS.AddComment("Thunk section relative address");
1097 OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
1098 OS.AddComment("Thunk section index");
1099 OS.emitCOFFSectionIndex(Fn);
1100 OS.AddComment("Code size");
1101 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
1102 OS.AddComment("Ordinal");
1103 OS.emitInt8(unsigned(ordinal));
1104 OS.AddComment("Function name");
1105 emitNullTerminatedSymbolName(OS, FuncName);
1106 // Additional fields specific to the thunk ordinal would go here.
1107 endSymbolRecord(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(SymbolKind::S_PROC_ID_END);
1114
1115 endCVSubsection(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(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(SP->getScope(), SP->getName());
1142
1143 // If our DISubprogram name is empty, use the mangled name.
1144 if (FuncName.empty())
1145 FuncName = std::string(GlobalValue::dropLLVMManglingEscape(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(Fn);
1150
1151 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1152 OS.AddComment("Symbol subsection for " + Twine(FuncName));
1153 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1154 {
1155 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1156 : SymbolKind::S_GPROC32_ID;
1157 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1158
1159 // These fields are filled in by tools like CVPACK which run after the fact.
1160 OS.AddComment("PtrParent");
1161 OS.emitInt32(0);
1162 OS.AddComment("PtrEnd");
1163 OS.emitInt32(0);
1164 OS.AddComment("PtrNext");
1165 OS.emitInt32(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("Code size");
1169 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1170 OS.AddComment("Offset after prologue");
1171 OS.emitInt32(0);
1172 OS.AddComment("Offset before epilogue");
1173 OS.emitInt32(0);
1174 OS.AddComment("Function type index");
1175 OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
1176 OS.AddComment("Function section relative address");
1177 OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
1178 OS.AddComment("Function section index");
1179 OS.emitCOFFSectionIndex(Fn);
1180 OS.AddComment("Flags");
1181 ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo;
1182 if (FI.HasFramePointer)
1183 ProcFlags |= ProcSymFlags::HasFP;
1184 if (GV->hasFnAttribute(Attribute::NoReturn))
1185 ProcFlags |= ProcSymFlags::IsNoReturn;
1186 if (GV->hasFnAttribute(Attribute::NoInline))
1187 ProcFlags |= ProcSymFlags::IsNoInline;
1188 OS.emitInt8(static_cast<uint8_t>(ProcFlags));
1189 // Emit the function display name as a null-terminated string.
1190 OS.AddComment("Function name");
1191 // Truncate the name so we won't overflow the record length field.
1192 emitNullTerminatedSymbolName(OS, FuncName);
1193 endSymbolRecord(ProcRecordEnd);
1194
1195 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1196 // Subtract out the CSR size since MSVC excludes that and we include it.
1197 OS.AddComment("FrameSize");
1198 OS.emitInt32(FI.FrameSize - FI.CSRSize);
1199 OS.AddComment("Padding");
1200 OS.emitInt32(0);
1201 OS.AddComment("Offset of padding");
1202 OS.emitInt32(0);
1203 OS.AddComment("Bytes of callee saved registers");
1204 OS.emitInt32(FI.CSRSize);
1205 OS.AddComment("Exception handler offset");
1206 OS.emitInt32(0);
1207 OS.AddComment("Exception handler section");
1208 OS.emitInt16(0);
1209 OS.AddComment("Flags (defines frame register)");
1210 OS.emitInt32(uint32_t(FI.FrameProcOpts));
1211 endSymbolRecord(FrameProcEnd);
1212
1213 emitInlinees(FI.Inlinees);
1214 emitLocalVariableList(FI, FI.Locals);
1215 emitGlobalVariableList(FI.Globals);
1216 emitLexicalBlockList(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(InlinedAt);
1223 assert(I != FI.InlineSites.end() &&
1224 "child site not in function inline site map");
1225 emitInlinedCallSite(FI, InlinedAt, I->second);
1226 }
1227
1228 for (auto Annot : FI.Annotations) {
1229 MCSymbol *Label = Annot.first;
1230 MDTuple *Strs = cast<MDTuple>(Annot.second);
1231 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1232 OS.emitCOFFSecRel32(Label, /*Offset=*/0);
1233 // FIXME: Make sure we don't overflow the max record size.
1234 OS.emitCOFFSectionIndex(Label);
1235 OS.emitInt16(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>(MD)->getString();
1240 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1241 OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
1242 }
1243 endSymbolRecord(AnnotEnd);
1244 }
1245
1246 for (auto HeapAllocSite : FI.HeapAllocSites) {
1247 const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1248 const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1249 const DIType *DITy = std::get<2>(HeapAllocSite);
1250 MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1251 OS.AddComment("Call site offset");
1252 OS.emitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1253 OS.AddComment("Call site section index");
1254 OS.emitCOFFSectionIndex(BeginLabel);
1255 OS.AddComment("Call instruction length");
1256 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1257 OS.AddComment("Type index");
1258 OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
1259 endSymbolRecord(HeapAllocEnd);
1260 }
1261
1262 if (SP != nullptr)
1263 emitDebugInfoForUDTs(LocalUDTs);
1264
1265 emitDebugInfoForJumpTables(FI);
1266
1267 // We're done with this function.
1268 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1269 }
1270 endCVSubsection(SymbolsEnd);
1271
1272 // We have an assembler directive that takes care of the whole line table.
1273 OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1274}
1275
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 :
1299 if (!VI.Var)
1300 continue;
1301 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1302 "Expected inlined-at fields to agree");
1303
1304 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1305 LexicalScope *Scope = LScopes.findLexicalScope(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(ExprOffset, FirstRemaining))
1317 continue;
1318 if (!FirstRemaining.empty()) {
1319 if (FirstRemaining.front() != dwarf::DW_OP_deref)
1320 continue;
1321 SmallVector<uint64_t, 1> LastRemaining;
1323 ArrayRef(FirstRemaining).drop_front(), DerefOffset,
1324 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(*Asm->MF, VI.getStackSlot(), FrameReg);
1335 uint16_t CVReg = TRI->getCodeViewRegNum(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(CVReg, FrameOffset.getFixed() + ExprOffset,
1347 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(Range.first);
1354 const MCSymbol *End = getLabelAfterInsn(Range.second);
1355 End = End ? End : Asm->getFunctionEnd();
1356 Var.DefRanges[DefRange].emplace_back(Begin, End);
1357 }
1358
1359 recordLocalVariable(std::move(Var), 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 =
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(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(Location->Register)) {
1403 // No encoding currently exists for this register; bail out.
1404 continue;
1405 }
1406
1407 LocalVarDef DR;
1408 DR.CVRegister = TRI->getCodeViewRegNum(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(Entry.getInstr());
1427 const MCSymbol *End;
1428 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1429 auto &EndingEntry = Entries[Entry.getEndIndex()];
1430 End = EndingEntry.isDbgValue()
1431 ? getLabelBeforeInsn(EndingEntry.getInstr())
1432 : getLabelAfterInsn(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(Begin, 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 MDNode *N : SP->getRetainedNodes())
1455 if (const auto *GVE = dyn_cast<DIGlobalVariableExpression>(N))
1456 collectGlobalOrStaticLocalVariableInfo(GVE);
1457
1458 for (const auto &I : DbgValues) {
1459 InlinedEntity IV = I.first;
1460 if (Processed.count(IV))
1461 continue;
1462 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1463 const DILocation *InlinedAt = IV.second;
1464
1465 // Instruction ranges, specifying where IV is accessible.
1466 const auto &Entries = I.second;
1467
1468 LexicalScope *Scope = nullptr;
1469 if (InlinedAt)
1470 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1471 else
1472 Scope = LScopes.findLexicalScope(DIVar->getScope());
1473 // If variable scope is not found then skip this variable.
1474 if (!Scope)
1475 continue;
1476
1477 LocalVariable Var;
1478 Var.DIVar = DIVar;
1479
1480 calculateRanges(Var, Entries);
1481 recordLocalVariable(std::move(Var), Scope);
1482 }
1483}
1484
1486 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1487 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1488 const MachineFrameInfo &MFI = MF->getFrameInfo();
1489 const Function &GV = MF->getFunction();
1490 auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1491 assert(Insertion.second && "function already has info");
1492 CurFn = Insertion.first->second.get();
1493 CurFn->FuncId = NextFuncId++;
1494 CurFn->Begin = Asm->getFunctionBegin();
1495
1496 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1497 // callee-saved registers were used. For targets that don't use a PUSH
1498 // instruction (AArch64), this will be zero.
1499 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1500 CurFn->FrameSize = MFI.getStackSize();
1501 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1502 CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
1503
1504 // For this function S_FRAMEPROC record, figure out which codeview register
1505 // will be the frame pointer.
1506 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1507 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1508 if (CurFn->FrameSize > 0) {
1509 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1510 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1511 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1512 } else {
1513 CurFn->HasFramePointer = true;
1514 // If there is an FP, parameters are always relative to it.
1515 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1516 if (CurFn->HasStackRealignment) {
1517 // If the stack needs realignment, locals are relative to SP or VFRAME.
1518 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1519 } else {
1520 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1521 // other stack adjustments.
1522 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1523 }
1524 }
1525 }
1526
1527 // Compute other frame procedure options.
1529 if (MFI.hasVarSizedObjects())
1531 if (MF->exposesReturnsTwice())
1533 // FIXME: Set HasLongJmp if we ever track that info.
1534 if (MF->hasInlineAsm())
1536 if (GV.hasPersonalityFn()) {
1540 else
1542 }
1543 if (GV.hasFnAttribute(Attribute::InlineHint))
1545 if (GV.hasFnAttribute(Attribute::Naked))
1547 if (MFI.hasStackProtectorIndex()) {
1549 if (GV.hasFnAttribute(Attribute::StackProtectStrong) ||
1550 GV.hasFnAttribute(Attribute::StackProtectReq)) {
1552 }
1553 } else if (!GV.hasStackProtectorFnAttr()) {
1554 // __declspec(safebuffers) disables stack guards.
1556 }
1557 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1558 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1559 if (Asm->TM.getOptLevel() != CodeGenOptLevel::None && !GV.hasOptSize() &&
1560 !GV.hasOptNone())
1562 if (GV.hasProfileData()) {
1565 }
1566 // FIXME: Set GuardCfg when it is implemented.
1567 CurFn->FrameProcOpts = FPO;
1568
1569 OS.emitCVFuncIdDirective(CurFn->FuncId);
1570
1571 // Find the end of the function prolog. First known non-DBG_VALUE and
1572 // non-frame setup location marks the beginning of the function body.
1573 // FIXME: is there a simpler a way to do this? Can we just search
1574 // for the first instruction of the function, not the last of the prolog?
1576 bool EmptyPrologue = true;
1577 for (const auto &MBB : *MF) {
1578 for (const auto &MI : MBB) {
1579 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1580 MI.getDebugLoc()) {
1581 PrologEndLoc = MI.getDebugLoc();
1582 break;
1583 } else if (!MI.isMetaInstruction()) {
1584 EmptyPrologue = false;
1585 }
1586 }
1587 }
1588
1589 // Record beginning of function if we have a non-empty prologue.
1590 if (PrologEndLoc && !EmptyPrologue) {
1591 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1592 maybeRecordLocation(FnStartDL, MF);
1593 }
1594
1595 // Find heap alloc sites and emit labels around them.
1596 for (const auto &MBB : *MF) {
1597 for (const auto &MI : MBB) {
1598 if (MI.getHeapAllocMarker()) {
1601 }
1602 }
1603 }
1604
1605 // Mark branches that may potentially be using jump tables with labels.
1606 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
1608 discoverJumpTableBranches(MF, isThumb);
1609}
1610
1611static bool shouldEmitUdt(const DIType *T) {
1612 if (!T)
1613 return false;
1614
1615 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1616 if (T->getTag() == dwarf::DW_TAG_typedef) {
1617 if (DIScope *Scope = T->getScope()) {
1618 switch (Scope->getTag()) {
1619 case dwarf::DW_TAG_structure_type:
1620 case dwarf::DW_TAG_class_type:
1621 case dwarf::DW_TAG_union_type:
1622 return false;
1623 default:
1624 // do nothing.
1625 ;
1626 }
1627 }
1628 }
1629
1630 while (true) {
1631 if (!T || T->isForwardDecl())
1632 return false;
1633
1635 if (!DT)
1636 return true;
1637 T = DT->getBaseType();
1638 }
1639 return true;
1640}
1641
1642void CodeViewDebug::addToUDTs(const DIType *Ty) {
1643 // Don't record empty UDTs.
1644 if (Ty->getName().empty())
1645 return;
1646 if (!shouldEmitUdt(Ty))
1647 return;
1648
1649 SmallVector<StringRef, 5> ParentScopeNames;
1650 const DISubprogram *ClosestSubprogram =
1651 collectParentScopeNames(Ty->getScope(), ParentScopeNames);
1652
1653 std::string FullyQualifiedName =
1654 formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
1655
1656 if (ClosestSubprogram == nullptr) {
1657 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1658 } else if (ClosestSubprogram == CurrentSubprogram) {
1659 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1660 }
1661
1662 // TODO: What if the ClosestSubprogram is neither null or the current
1663 // subprogram? Currently, the UDT just gets dropped on the floor.
1664 //
1665 // The current behavior is not desirable. To get maximal fidelity, we would
1666 // need to perform all type translation before beginning emission of .debug$S
1667 // and then make LocalUDTs a member of FunctionInfo
1668}
1669
1670TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1671 // Generic dispatch for lowering an unknown type.
1672 switch (Ty->getTag()) {
1673 case dwarf::DW_TAG_array_type:
1674 return lowerTypeArray(cast<DICompositeType>(Ty));
1675 case dwarf::DW_TAG_typedef:
1676 return lowerTypeAlias(cast<DIDerivedType>(Ty));
1677 case dwarf::DW_TAG_base_type:
1678 return lowerTypeBasic(cast<DIBasicType>(Ty));
1679 case dwarf::DW_TAG_pointer_type:
1680 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1681 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1682 [[fallthrough]];
1683 case dwarf::DW_TAG_reference_type:
1684 case dwarf::DW_TAG_rvalue_reference_type:
1685 return lowerTypePointer(cast<DIDerivedType>(Ty));
1686 case dwarf::DW_TAG_ptr_to_member_type:
1687 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1688 case dwarf::DW_TAG_restrict_type:
1689 case dwarf::DW_TAG_const_type:
1690 case dwarf::DW_TAG_volatile_type:
1691 // TODO: add support for DW_TAG_atomic_type here
1692 return lowerTypeModifier(cast<DIDerivedType>(Ty));
1693 case dwarf::DW_TAG_subroutine_type:
1694 if (ClassTy) {
1695 // The member function type of a member function pointer has no
1696 // ThisAdjustment.
1697 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1698 /*ThisAdjustment=*/0,
1699 /*IsStaticMethod=*/false);
1700 }
1701 return lowerTypeFunction(cast<DISubroutineType>(Ty));
1702 case dwarf::DW_TAG_enumeration_type:
1703 return lowerTypeEnum(cast<DICompositeType>(Ty));
1704 case dwarf::DW_TAG_class_type:
1705 case dwarf::DW_TAG_structure_type:
1706 return lowerTypeClass(cast<DICompositeType>(Ty));
1707 case dwarf::DW_TAG_union_type:
1708 return lowerTypeUnion(cast<DICompositeType>(Ty));
1709 case dwarf::DW_TAG_string_type:
1710 return lowerTypeString(cast<DIStringType>(Ty));
1711 case dwarf::DW_TAG_unspecified_type:
1712 if (Ty->getName() == "decltype(nullptr)")
1713 return TypeIndex::NullptrT();
1714 return TypeIndex::None();
1715 default:
1716 // Use the null type index.
1717 return TypeIndex();
1718 }
1719}
1720
1721TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1722 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1723 StringRef TypeName = Ty->getName();
1724
1725 addToUDTs(Ty);
1726
1727 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1728 TypeName == "HRESULT")
1729 return TypeIndex(SimpleTypeKind::HResult);
1730 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1731 TypeName == "wchar_t")
1732 return TypeIndex(SimpleTypeKind::WideCharacter);
1733
1734 return UnderlyingTypeIndex;
1735}
1736
1737TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1738 const DIType *ElementType = Ty->getBaseType();
1739 TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1740 // IndexType is size_t, which depends on the bitness of the target.
1741 TypeIndex IndexType = getPointerSizeInBytes() == 8
1742 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1743 : TypeIndex(SimpleTypeKind::UInt32Long);
1744
1745 uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1746
1747 // Add subranges to array type.
1748 DINodeArray Elements = Ty->getElements();
1749 for (int i = Elements.size() - 1; i >= 0; --i) {
1750 const DINode *Element = Elements[i];
1751 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1752
1753 const DISubrange *Subrange = cast<DISubrange>(Element);
1754 int64_t Count = -1;
1755
1756 // If Subrange has a Count field, use it.
1757 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1758 // where lowerbound is from the LowerBound field of the Subrange,
1759 // or the language default lowerbound if that field is unspecified.
1760 if (auto *CI = dyn_cast_if_present<ConstantInt *>(Subrange->getCount()))
1761 Count = CI->getSExtValue();
1762 else if (auto *UI = dyn_cast_if_present<ConstantInt *>(
1763 Subrange->getUpperBound())) {
1764 // Fortran uses 1 as the default lowerbound; other languages use 0.
1765 int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
1766 auto *LI = dyn_cast_if_present<ConstantInt *>(Subrange->getLowerBound());
1767 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1768 Count = UI->getSExtValue() - Lowerbound + 1;
1769 }
1770
1771 // Forward declarations of arrays without a size and VLAs use a count of -1.
1772 // Emit a count of zero in these cases to match what MSVC does for arrays
1773 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1774 // should do for them even if we could distinguish them.
1775 if (Count == -1)
1776 Count = 0;
1777
1778 // Update the element size and element type index for subsequent subranges.
1779 ElementSize *= Count;
1780
1781 // If this is the outermost array, use the size from the array. It will be
1782 // more accurate if we had a VLA or an incomplete element type size.
1783 uint64_t ArraySize =
1784 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1785
1786 StringRef Name = (i == 0) ? Ty->getName() : "";
1787 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1788 ElementTypeIndex = TypeTable.writeLeafType(AR);
1789 }
1790
1791 return ElementTypeIndex;
1792}
1793
1794// This function lowers a Fortran character type (DIStringType).
1795// Note that it handles only the character*n variant (using SizeInBits
1796// field in DIString to describe the type size) at the moment.
1797// Other variants (leveraging the StringLength and StringLengthExp
1798// fields in DIStringType) remain TBD.
1799TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1800 TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1801 uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1802 StringRef Name = Ty->getName();
1803 // IndexType is size_t, which depends on the bitness of the target.
1804 TypeIndex IndexType = getPointerSizeInBytes() == 8
1805 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1806 : TypeIndex(SimpleTypeKind::UInt32Long);
1807
1808 // Create a type of character array of ArraySize.
1809 ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1810
1811 return TypeTable.writeLeafType(AR);
1812}
1813
1814TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1815 TypeIndex Index;
1817 uint32_t ByteSize;
1818
1819 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1820 ByteSize = Ty->getSizeInBits() / 8;
1821
1822 SimpleTypeKind STK = SimpleTypeKind::None;
1823 switch (Kind) {
1824 case dwarf::DW_ATE_address:
1825 // FIXME: Translate
1826 break;
1827 case dwarf::DW_ATE_boolean:
1828 switch (ByteSize) {
1829 case 1: STK = SimpleTypeKind::Boolean8; break;
1830 case 2: STK = SimpleTypeKind::Boolean16; break;
1831 case 4: STK = SimpleTypeKind::Boolean32; break;
1832 case 8: STK = SimpleTypeKind::Boolean64; break;
1833 case 16: STK = SimpleTypeKind::Boolean128; break;
1834 }
1835 break;
1836 case dwarf::DW_ATE_complex_float:
1837 // The CodeView size for a complex represents the size of
1838 // an individual component.
1839 switch (ByteSize) {
1840 case 4: STK = SimpleTypeKind::Complex16; break;
1841 case 8: STK = SimpleTypeKind::Complex32; break;
1842 case 16: STK = SimpleTypeKind::Complex64; break;
1843 case 20: STK = SimpleTypeKind::Complex80; break;
1844 case 32: STK = SimpleTypeKind::Complex128; break;
1845 }
1846 break;
1847 case dwarf::DW_ATE_float:
1848 switch (ByteSize) {
1849 case 2: STK = SimpleTypeKind::Float16; break;
1850 case 4: STK = SimpleTypeKind::Float32; break;
1851 case 6: STK = SimpleTypeKind::Float48; break;
1852 case 8: STK = SimpleTypeKind::Float64; break;
1853 case 10: STK = SimpleTypeKind::Float80; break;
1854 case 16: STK = SimpleTypeKind::Float128; break;
1855 }
1856 break;
1857 case dwarf::DW_ATE_signed:
1858 switch (ByteSize) {
1859 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1860 case 2: STK = SimpleTypeKind::Int16Short; break;
1861 case 4: STK = SimpleTypeKind::Int32; break;
1862 case 8: STK = SimpleTypeKind::Int64Quad; break;
1863 case 16: STK = SimpleTypeKind::Int128Oct; break;
1864 }
1865 break;
1866 case dwarf::DW_ATE_unsigned:
1867 switch (ByteSize) {
1868 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1869 case 2: STK = SimpleTypeKind::UInt16Short; break;
1870 case 4: STK = SimpleTypeKind::UInt32; break;
1871 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1872 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1873 }
1874 break;
1875 case dwarf::DW_ATE_UTF:
1876 switch (ByteSize) {
1877 case 1: STK = SimpleTypeKind::Character8; break;
1878 case 2: STK = SimpleTypeKind::Character16; break;
1879 case 4: STK = SimpleTypeKind::Character32; break;
1880 }
1881 break;
1882 case dwarf::DW_ATE_signed_char:
1883 if (ByteSize == 1)
1884 STK = SimpleTypeKind::SignedCharacter;
1885 break;
1886 case dwarf::DW_ATE_unsigned_char:
1887 if (ByteSize == 1)
1888 STK = SimpleTypeKind::UnsignedCharacter;
1889 break;
1890 default:
1891 break;
1892 }
1893
1894 // Apply some fixups based on the source-level type name.
1895 // Include some amount of canonicalization from an old naming scheme Clang
1896 // used to use for integer types (in an outdated effort to be compatible with
1897 // GCC's debug info/GDB's behavior, which has since been addressed).
1898 if (STK == SimpleTypeKind::Int32 &&
1899 (Ty->getName() == "long int" || Ty->getName() == "long"))
1900 STK = SimpleTypeKind::Int32Long;
1901 if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1902 Ty->getName() == "unsigned long"))
1903 STK = SimpleTypeKind::UInt32Long;
1904 if (STK == SimpleTypeKind::UInt16Short &&
1905 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1906 STK = SimpleTypeKind::WideCharacter;
1907 if ((STK == SimpleTypeKind::SignedCharacter ||
1908 STK == SimpleTypeKind::UnsignedCharacter) &&
1909 Ty->getName() == "char")
1910 STK = SimpleTypeKind::NarrowCharacter;
1911
1912 return TypeIndex(STK);
1913}
1914
1915TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1916 PointerOptions PO) {
1917 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1918
1919 // Pointers to simple types without any options can use SimpleTypeMode, rather
1920 // than having a dedicated pointer type record.
1921 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1922 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1923 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1924 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1925 ? SimpleTypeMode::NearPointer64
1926 : SimpleTypeMode::NearPointer32;
1927 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1928 }
1929
1930 PointerKind PK =
1931 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1932 PointerMode PM = PointerMode::Pointer;
1933 switch (Ty->getTag()) {
1934 default: llvm_unreachable("not a pointer tag type");
1935 case dwarf::DW_TAG_pointer_type:
1936 PM = PointerMode::Pointer;
1937 break;
1938 case dwarf::DW_TAG_reference_type:
1939 PM = PointerMode::LValueReference;
1940 break;
1941 case dwarf::DW_TAG_rvalue_reference_type:
1942 PM = PointerMode::RValueReference;
1943 break;
1944 }
1945
1946 if (Ty->isObjectPointer())
1947 PO |= PointerOptions::Const;
1948
1949 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1950 return TypeTable.writeLeafType(PR);
1951}
1952
1954translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1955 // SizeInBytes being zero generally implies that the member pointer type was
1956 // incomplete, which can happen if it is part of a function prototype. In this
1957 // case, use the unknown model instead of the general model.
1958 if (IsPMF) {
1959 switch (Flags & DINode::FlagPtrToMemberRep) {
1960 case 0:
1961 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1963 case DINode::FlagSingleInheritance:
1965 case DINode::FlagMultipleInheritance:
1967 case DINode::FlagVirtualInheritance:
1969 }
1970 } else {
1971 switch (Flags & DINode::FlagPtrToMemberRep) {
1972 case 0:
1973 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1975 case DINode::FlagSingleInheritance:
1977 case DINode::FlagMultipleInheritance:
1979 case DINode::FlagVirtualInheritance:
1981 }
1982 }
1983 llvm_unreachable("invalid ptr to member representation");
1984}
1985
1986TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1987 PointerOptions PO) {
1988 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1989 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1990 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1991 TypeIndex PointeeTI =
1992 getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
1993 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1994 : PointerKind::Near32;
1995 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1996 : PointerMode::PointerToDataMember;
1997
1998 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1999 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
2000 MemberPointerInfo MPI(
2001 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
2002 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
2003 return TypeTable.writeLeafType(PR);
2004}
2005
2006/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
2007/// have a translation, use the NearC convention.
2008static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
2009 switch (DwarfCC) {
2010 case dwarf::DW_CC_normal: return CallingConvention::NearC;
2011 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
2012 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
2013 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
2014 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
2015 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
2016 }
2018}
2019
2020TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
2021 ModifierOptions Mods = ModifierOptions::None;
2022 PointerOptions PO = PointerOptions::None;
2023 bool IsModifier = true;
2024 const DIType *BaseTy = Ty;
2025 while (IsModifier && BaseTy) {
2026 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
2027 switch (BaseTy->getTag()) {
2028 case dwarf::DW_TAG_const_type:
2029 Mods |= ModifierOptions::Const;
2030 PO |= PointerOptions::Const;
2031 break;
2032 case dwarf::DW_TAG_volatile_type:
2033 Mods |= ModifierOptions::Volatile;
2034 PO |= PointerOptions::Volatile;
2035 break;
2036 case dwarf::DW_TAG_restrict_type:
2037 // Only pointer types be marked with __restrict. There is no known flag
2038 // for __restrict in LF_MODIFIER records.
2039 PO |= PointerOptions::Restrict;
2040 break;
2041 default:
2042 IsModifier = false;
2043 break;
2044 }
2045 if (IsModifier)
2046 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
2047 }
2048
2049 // Check if the inner type will use an LF_POINTER record. If so, the
2050 // qualifiers will go in the LF_POINTER record. This comes up for types like
2051 // 'int *const' and 'int *__restrict', not the more common cases like 'const
2052 // char *'.
2053 if (BaseTy) {
2054 switch (BaseTy->getTag()) {
2055 case dwarf::DW_TAG_pointer_type:
2056 case dwarf::DW_TAG_reference_type:
2057 case dwarf::DW_TAG_rvalue_reference_type:
2058 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
2059 case dwarf::DW_TAG_ptr_to_member_type:
2060 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
2061 default:
2062 break;
2063 }
2064 }
2065
2066 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
2067
2068 // Return the base type index if there aren't any modifiers. For example, the
2069 // metadata could contain restrict wrappers around non-pointer types.
2070 if (Mods == ModifierOptions::None)
2071 return ModifiedTI;
2072
2073 ModifierRecord MR(ModifiedTI, Mods);
2074 return TypeTable.writeLeafType(MR);
2075}
2076
2077TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
2078 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
2079 for (const DIType *ArgType : Ty->getTypeArray())
2080 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
2081
2082 // MSVC uses type none for variadic argument.
2083 if (ReturnAndArgTypeIndices.size() > 1 &&
2084 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
2085 ReturnAndArgTypeIndices.back() = TypeIndex::None();
2086 }
2087 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2088 ArrayRef<TypeIndex> ArgTypeIndices = {};
2089 if (!ReturnAndArgTypeIndices.empty()) {
2090 auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices);
2091 ReturnTypeIndex = ReturnAndArgTypesRef.consume_front();
2092 ArgTypeIndices = ReturnAndArgTypesRef;
2093 }
2094
2095 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2096 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2097
2099
2101 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
2102 ArgListIndex);
2103 return TypeTable.writeLeafType(Procedure);
2104}
2105
2106TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
2107 const DIType *ClassTy,
2108 int ThisAdjustment,
2109 bool IsStaticMethod,
2110 FunctionOptions FO) {
2111 // Lower the containing class type.
2112 TypeIndex ClassType = getTypeIndex(ClassTy);
2113
2114 DITypeArray ReturnAndArgs = Ty->getTypeArray();
2115
2116 unsigned Index = 0;
2117 SmallVector<TypeIndex, 8> ArgTypeIndices;
2118 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2119 if (ReturnAndArgs.size() > Index) {
2120 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
2121 }
2122
2123 // If the first argument is a pointer type and this isn't a static method,
2124 // treat it as the special 'this' parameter, which is encoded separately from
2125 // the arguments.
2126 TypeIndex ThisTypeIndex;
2127 if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
2128 if (const DIDerivedType *PtrTy =
2129 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
2130 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2131 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
2132 Index++;
2133 }
2134 }
2135 }
2136
2137 while (Index < ReturnAndArgs.size())
2138 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
2139
2140 // MSVC uses type none for variadic argument.
2141 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
2142 ArgTypeIndices.back() = TypeIndex::None();
2143
2144 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2145 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2146
2148
2149 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
2150 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
2151 return TypeTable.writeLeafType(MFR);
2152}
2153
2154TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
2155 unsigned VSlotCount =
2156 Ty->getSizeInBits() / (8 * Asm->MAI.getCodePointerSize());
2157 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
2158
2159 VFTableShapeRecord VFTSR(Slots);
2160 return TypeTable.writeLeafType(VFTSR);
2161}
2162
2163static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
2164 switch (Flags & DINode::FlagAccessibility) {
2165 case DINode::FlagPrivate: return MemberAccess::Private;
2166 case DINode::FlagPublic: return MemberAccess::Public;
2167 case DINode::FlagProtected: return MemberAccess::Protected;
2168 case 0:
2169 // If there was no explicit access control, provide the default for the tag.
2170 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2172 }
2173 llvm_unreachable("access flags are exclusive");
2174}
2175
2177 if (SP->isArtificial())
2179
2180 // FIXME: Handle other MethodOptions.
2181
2182 return MethodOptions::None;
2183}
2184
2186 bool Introduced) {
2187 if (SP->getFlags() & DINode::FlagStaticMember)
2188 return MethodKind::Static;
2189
2190 switch (SP->getVirtuality()) {
2191 case dwarf::DW_VIRTUALITY_none:
2192 break;
2193 case dwarf::DW_VIRTUALITY_virtual:
2195 case dwarf::DW_VIRTUALITY_pure_virtual:
2196 return Introduced ? MethodKind::PureIntroducingVirtual
2198 default:
2199 llvm_unreachable("unhandled virtuality case");
2200 }
2201
2202 return MethodKind::Vanilla;
2203}
2204
2206 switch (Ty->getTag()) {
2207 case dwarf::DW_TAG_class_type:
2208 return TypeRecordKind::Class;
2209 case dwarf::DW_TAG_structure_type:
2210 return TypeRecordKind::Struct;
2211 default:
2212 llvm_unreachable("unexpected tag");
2213 }
2214}
2215
2216/// Return ClassOptions that should be present on both the forward declaration
2217/// and the defintion of a tag type.
2220
2221 // MSVC always sets this flag, even for local types. Clang doesn't always
2222 // appear to give every type a linkage name, which may be problematic for us.
2223 // FIXME: Investigate the consequences of not following them here.
2224 if (!Ty->getIdentifier().empty())
2226
2227 // Put the Nested flag on a type if it appears immediately inside a tag type.
2228 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2229 // here. That flag is only set on definitions, and not forward declarations.
2230 const DIScope *ImmediateScope = Ty->getScope();
2231 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2233
2234 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2235 // type only when it has an immediate function scope. Clang never puts enums
2236 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2237 // always in function, class, or file scopes.
2238 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2239 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2241 } else {
2242 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2243 Scope = Scope->getScope()) {
2244 if (isa<DISubprogram>(Scope)) {
2246 break;
2247 }
2248 }
2249 }
2250
2251 return CO;
2252}
2253
2254void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2255 switch (Ty->getTag()) {
2256 case dwarf::DW_TAG_class_type:
2257 case dwarf::DW_TAG_structure_type:
2258 case dwarf::DW_TAG_union_type:
2259 case dwarf::DW_TAG_enumeration_type:
2260 break;
2261 default:
2262 return;
2263 }
2264
2265 if (const auto *File = Ty->getFile()) {
2266 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2267 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2268
2269 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2270 TypeTable.writeLeafType(USLR);
2271 }
2272}
2273
2274TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2276 TypeIndex FTI;
2277 unsigned EnumeratorCount = 0;
2278
2279 if (Ty->isForwardDecl()) {
2280 CO |= ClassOptions::ForwardReference;
2281 } else {
2282 ContinuationRecordBuilder ContinuationBuilder;
2283 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2284 for (const DINode *Element : Ty->getElements()) {
2285 // We assume that the frontend provides all members in source declaration
2286 // order, which is what MSVC does.
2287 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2288 // FIXME: Is it correct to always emit these as unsigned here?
2289 EnumeratorRecord ER(MemberAccess::Public,
2290 APSInt(Enumerator->getValue(), true),
2291 Enumerator->getName());
2292 ContinuationBuilder.writeMemberType(ER);
2293 EnumeratorCount++;
2294 }
2295 }
2296 FTI = TypeTable.insertRecord(ContinuationBuilder);
2297 }
2298
2299 std::string FullName = getFullyQualifiedName(Ty);
2300
2301 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2302 getTypeIndex(Ty->getBaseType()));
2303 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2304
2305 addUDTSrcLine(Ty, EnumTI);
2306
2307 return EnumTI;
2308}
2309
2310//===----------------------------------------------------------------------===//
2311// ClassInfo
2312//===----------------------------------------------------------------------===//
2313
2319 // [MemberInfo]
2320 using MemberList = std::vector<MemberInfo>;
2321
2323 // MethodName -> MethodsList
2325
2326 /// Base classes.
2327 std::vector<const DIDerivedType *> Inheritance;
2328
2329 /// Direct members.
2331 // Direct overloaded methods gathered by name.
2333
2335
2336 std::vector<const DIType *> NestedTypes;
2337};
2338
2339void CodeViewDebug::clear() {
2340 assert(CurFn == nullptr);
2341 FileIdMap.clear();
2342 FnDebugInfo.clear();
2343 FileToFilepathMap.clear();
2344 LocalUDTs.clear();
2345 GlobalUDTs.clear();
2346 TypeIndices.clear();
2347 CompleteTypeIndices.clear();
2348 ScopeGlobals.clear();
2349 CVGlobalVariableOffsets.clear();
2350}
2351
2352void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2353 const DIDerivedType *DDTy) {
2354 if (!DDTy->getName().empty()) {
2355 Info.Members.push_back({DDTy, 0});
2356
2357 // Collect static const data members with values.
2358 if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2359 DINode::FlagStaticMember) {
2360 if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2361 isa<ConstantFP>(DDTy->getConstant())))
2362 StaticConstMembers.push_back(DDTy);
2363 }
2364
2365 return;
2366 }
2367
2368 // An unnamed member may represent a nested struct or union. Attempt to
2369 // interpret the unnamed member as a DICompositeType possibly wrapped in
2370 // qualifier types. Add all the indirect fields to the current record if that
2371 // succeeds, and drop the member if that fails.
2372 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2373 uint64_t Offset = DDTy->getOffsetInBits();
2374 const DIType *Ty = DDTy->getBaseType();
2375 bool FullyResolved = false;
2376 while (!FullyResolved) {
2377 switch (Ty->getTag()) {
2378 case dwarf::DW_TAG_const_type:
2379 case dwarf::DW_TAG_volatile_type:
2380 // FIXME: we should apply the qualifier types to the indirect fields
2381 // rather than dropping them.
2382 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2383 break;
2384 default:
2385 FullyResolved = true;
2386 break;
2387 }
2388 }
2389
2390 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2391 if (!DCTy)
2392 return;
2393
2394 ClassInfo NestedInfo = collectClassInfo(DCTy);
2395 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2396 Info.Members.push_back(
2397 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2398}
2399
2400ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2401 ClassInfo Info;
2402 // Add elements to structure type.
2403 DINodeArray Elements = Ty->getElements();
2404 for (auto *Element : Elements) {
2405 // We assume that the frontend provides all members in source declaration
2406 // order, which is what MSVC does.
2407 if (!Element)
2408 continue;
2409 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2410 Info.Methods[SP->getRawName()].push_back(SP);
2411 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2412 if (DDTy->getTag() == dwarf::DW_TAG_member) {
2413 collectMemberInfo(Info, DDTy);
2414 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2415 Info.Inheritance.push_back(DDTy);
2416 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2417 DDTy->getName() == "__vtbl_ptr_type") {
2418 Info.VShapeTI = getTypeIndex(DDTy);
2419 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2420 Info.NestedTypes.push_back(DDTy);
2421 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2422 // Ignore friend members. It appears that MSVC emitted info about
2423 // friends in the past, but modern versions do not.
2424 }
2425 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2426 Info.NestedTypes.push_back(Composite);
2427 }
2428 // Skip other unrecognized kinds of elements.
2429 }
2430 return Info;
2431}
2432
2434 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2435 // if a complete type should be emitted instead of a forward reference.
2436 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2437 !Ty->isForwardDecl();
2438}
2439
2440TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2441 // Emit the complete type for unnamed structs. C++ classes with methods
2442 // which have a circular reference back to the class type are expected to
2443 // be named by the front-end and should not be "unnamed". C unnamed
2444 // structs should not have circular references.
2446 // If this unnamed complete type is already in the process of being defined
2447 // then the description of the type is malformed and cannot be emitted
2448 // into CodeView correctly so report a fatal error.
2449 auto I = CompleteTypeIndices.find(Ty);
2450 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2451 report_fatal_error("cannot debug circular reference to unnamed type");
2452 return getCompleteTypeIndex(Ty);
2453 }
2454
2455 // First, construct the forward decl. Don't look into Ty to compute the
2456 // forward decl options, since it might not be available in all TUs.
2458 ClassOptions CO =
2459 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2460 std::string FullName = getFullyQualifiedName(Ty);
2461 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2462 FullName, Ty->getIdentifier());
2463 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2464 if (!Ty->isForwardDecl())
2465 DeferredCompleteTypes.push_back(Ty);
2466 return FwdDeclTI;
2467}
2468
2469TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2470 // Construct the field list and complete type record.
2473 TypeIndex FieldTI;
2474 TypeIndex VShapeTI;
2475 unsigned FieldCount;
2477 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2478 lowerRecordFieldList(Ty);
2479
2481 CO |= ClassOptions::ContainsNestedClass;
2482
2483 // MSVC appears to set this flag by searching any destructor or method with
2484 // FunctionOptions::Constructor among the emitted members. Clang AST has all
2485 // the members, however special member functions are not yet emitted into
2486 // debug information. For now checking a class's non-triviality seems enough.
2487 // FIXME: not true for a nested unnamed struct.
2488 if (isNonTrivial(Ty))
2489 CO |= ClassOptions::HasConstructorOrDestructor;
2490
2491 std::string FullName = getFullyQualifiedName(Ty);
2492
2493 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2494
2495 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2496 SizeInBytes, FullName, Ty->getIdentifier());
2497 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2498
2499 addUDTSrcLine(Ty, ClassTI);
2500
2501 addToUDTs(Ty);
2502
2503 return ClassTI;
2504}
2505
2506TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2507 // Emit the complete type for unnamed unions.
2509 return getCompleteTypeIndex(Ty);
2510
2511 ClassOptions CO =
2512 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2513 std::string FullName = getFullyQualifiedName(Ty);
2514 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2515 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2516 if (!Ty->isForwardDecl())
2517 DeferredCompleteTypes.push_back(Ty);
2518 return FwdDeclTI;
2519}
2520
2521TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2522 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2523 TypeIndex FieldTI;
2524 unsigned FieldCount;
2526 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2527 lowerRecordFieldList(Ty);
2528
2530 CO |= ClassOptions::ContainsNestedClass;
2531
2532 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2533 std::string FullName = getFullyQualifiedName(Ty);
2534
2535 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2536 Ty->getIdentifier());
2537 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2538
2539 addUDTSrcLine(Ty, UnionTI);
2540
2541 addToUDTs(Ty);
2542
2543 return UnionTI;
2544}
2545
2546std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2547CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2548 // Manually count members. MSVC appears to count everything that generates a
2549 // field list record. Each individual overload in a method overload group
2550 // contributes to this count, even though the overload group is a single field
2551 // list record.
2552 unsigned MemberCount = 0;
2553 ClassInfo Info = collectClassInfo(Ty);
2554 ContinuationRecordBuilder ContinuationBuilder;
2555 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2556
2557 // Create base classes.
2558 for (const DIDerivedType *I : Info.Inheritance) {
2559 if (I->getFlags() & DINode::FlagVirtual) {
2560 // Virtual base.
2561 unsigned VBPtrOffset = I->getVBPtrOffset();
2562 // FIXME: Despite the accessor name, the offset is really in bytes.
2563 unsigned VBTableIndex = I->getOffsetInBits() / 4;
2564 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2565 ? TypeRecordKind::IndirectVirtualBaseClass
2566 : TypeRecordKind::VirtualBaseClass;
2567 VirtualBaseClassRecord VBCR(
2568 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2569 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2570 VBTableIndex);
2571
2572 ContinuationBuilder.writeMemberType(VBCR);
2573 MemberCount++;
2574 } else {
2575 assert(I->getOffsetInBits() % 8 == 0 &&
2576 "bases must be on byte boundaries");
2577 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2578 getTypeIndex(I->getBaseType()),
2579 I->getOffsetInBits() / 8);
2580 ContinuationBuilder.writeMemberType(BCR);
2581 MemberCount++;
2582 }
2583 }
2584
2585 // Create members.
2586 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2587 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2588 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2589 StringRef MemberName = Member->getName();
2591 translateAccessFlags(Ty->getTag(), Member->getFlags());
2592
2593 if (Member->isStaticMember()) {
2594 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2595 ContinuationBuilder.writeMemberType(SDMR);
2596 MemberCount++;
2597 continue;
2598 }
2599
2600 // Virtual function pointer member.
2601 if ((Member->getFlags() & DINode::FlagArtificial) &&
2602 Member->getName().starts_with("_vptr$")) {
2603 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2604 ContinuationBuilder.writeMemberType(VFPR);
2605 MemberCount++;
2606 continue;
2607 }
2608
2609 // Data member.
2610 uint64_t MemberOffsetInBits =
2611 Member->getOffsetInBits() + MemberInfo.BaseOffset;
2612 if (Member->isBitField()) {
2613 uint64_t StartBitOffset = MemberOffsetInBits;
2614 if (const auto *CI =
2615 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2616 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2617 }
2618 StartBitOffset -= MemberOffsetInBits;
2619 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2620 StartBitOffset);
2621 MemberBaseType = TypeTable.writeLeafType(BFR);
2622 }
2623 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2624 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2625 MemberName);
2626 ContinuationBuilder.writeMemberType(DMR);
2627 MemberCount++;
2628 }
2629
2630 // Create methods
2631 for (auto &MethodItr : Info.Methods) {
2632 StringRef Name = MethodItr.first->getString();
2633
2634 std::vector<OneMethodRecord> Methods;
2635 for (const DISubprogram *SP : MethodItr.second) {
2636 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2637 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2638
2639 unsigned VFTableOffset = -1;
2640 if (Introduced)
2641 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2642
2643 Methods.push_back(OneMethodRecord(
2644 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2645 translateMethodKindFlags(SP, Introduced),
2646 translateMethodOptionFlags(SP), VFTableOffset, Name));
2647 MemberCount++;
2648 }
2649 assert(!Methods.empty() && "Empty methods map entry");
2650 if (Methods.size() == 1)
2651 ContinuationBuilder.writeMemberType(Methods[0]);
2652 else {
2653 // FIXME: Make this use its own ContinuationBuilder so that
2654 // MethodOverloadList can be split correctly.
2655 MethodOverloadListRecord MOLR(Methods);
2656 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2657
2658 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2659 ContinuationBuilder.writeMemberType(OMR);
2660 }
2661 }
2662
2663 // Create nested classes.
2664 for (const DIType *Nested : Info.NestedTypes) {
2665 NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2666 ContinuationBuilder.writeMemberType(R);
2667 MemberCount++;
2668 }
2669
2670 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2671 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2672 !Info.NestedTypes.empty());
2673}
2674
2675TypeIndex CodeViewDebug::getVBPTypeIndex() {
2676 if (!VBPType.getIndex()) {
2677 // Make a 'const int *' type.
2678 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2679 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2680
2681 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2682 : PointerKind::Near32;
2683 PointerMode PM = PointerMode::Pointer;
2684 PointerOptions PO = PointerOptions::None;
2685 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2686 VBPType = TypeTable.writeLeafType(PR);
2687 }
2688
2689 return VBPType;
2690}
2691
2692TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2693 // The null DIType is the void type. Don't try to hash it.
2694 if (!Ty)
2695 return TypeIndex::Void();
2696
2697 // Check if we've already translated this type. Don't try to do a
2698 // get-or-create style insertion that caches the hash lookup across the
2699 // lowerType call. It will update the TypeIndices map.
2700 auto I = TypeIndices.find({Ty, ClassTy});
2701 if (I != TypeIndices.end())
2702 return I->second;
2703
2704 TypeLoweringScope S(*this);
2705 TypeIndex TI = lowerType(Ty, ClassTy);
2706 return recordTypeIndexForDINode(Ty, TI, ClassTy);
2707}
2708
2710CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2711 const DISubroutineType *SubroutineTy) {
2712 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2713 "this type must be a pointer type");
2714
2715 PointerOptions Options = PointerOptions::None;
2716 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2717 Options = PointerOptions::LValueRefThisPointer;
2718 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2719 Options = PointerOptions::RValueRefThisPointer;
2720
2721 // Check if we've already translated this type. If there is no ref qualifier
2722 // on the function then we look up this pointer type with no associated class
2723 // so that the TypeIndex for the this pointer can be shared with the type
2724 // index for other pointers to this class type. If there is a ref qualifier
2725 // then we lookup the pointer using the subroutine as the parent type.
2726 auto I = TypeIndices.find({PtrTy, SubroutineTy});
2727 if (I != TypeIndices.end())
2728 return I->second;
2729
2730 TypeLoweringScope S(*this);
2731 TypeIndex TI = lowerTypePointer(PtrTy, Options);
2732 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2733}
2734
2735TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2736 // The null DIType is the void type. Don't try to hash it.
2737 if (!Ty)
2738 return TypeIndex::Void();
2739
2740 // Look through typedefs when getting the complete type index. Call
2741 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2742 // emitted only once.
2743 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2744 (void)getTypeIndex(Ty);
2745 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2746 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2747
2748 // If this is a non-record type, the complete type index is the same as the
2749 // normal type index. Just call getTypeIndex.
2750 switch (Ty->getTag()) {
2751 case dwarf::DW_TAG_class_type:
2752 case dwarf::DW_TAG_structure_type:
2753 case dwarf::DW_TAG_union_type:
2754 break;
2755 default:
2756 return getTypeIndex(Ty);
2757 }
2758
2759 const auto *CTy = cast<DICompositeType>(Ty);
2760
2761 TypeLoweringScope S(*this);
2762
2763 // Make sure the forward declaration is emitted first. It's unclear if this
2764 // is necessary, but MSVC does it, and we should follow suit until we can show
2765 // otherwise.
2766 // We only emit a forward declaration for named types.
2767 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2768 TypeIndex FwdDeclTI = getTypeIndex(CTy);
2769
2770 // Just use the forward decl if we don't have complete type info. This
2771 // might happen if the frontend is using modules and expects the complete
2772 // definition to be emitted elsewhere.
2773 if (CTy->isForwardDecl())
2774 return FwdDeclTI;
2775 }
2776
2777 // Check if we've already translated the complete record type.
2778 // Insert the type with a null TypeIndex to signify that the type is currently
2779 // being lowered.
2780 auto InsertResult = CompleteTypeIndices.try_emplace(CTy);
2781 if (!InsertResult.second)
2782 return InsertResult.first->second;
2783
2784 TypeIndex TI;
2785 switch (CTy->getTag()) {
2786 case dwarf::DW_TAG_class_type:
2787 case dwarf::DW_TAG_structure_type:
2788 TI = lowerCompleteTypeClass(CTy);
2789 break;
2790 case dwarf::DW_TAG_union_type:
2791 TI = lowerCompleteTypeUnion(CTy);
2792 break;
2793 default:
2794 llvm_unreachable("not a record");
2795 }
2796
2797 // Update the type index associated with this CompositeType. This cannot
2798 // use the 'InsertResult' iterator above because it is potentially
2799 // invalidated by map insertions which can occur while lowering the class
2800 // type above.
2801 CompleteTypeIndices[CTy] = TI;
2802 return TI;
2803}
2804
2805/// Emit all the deferred complete record types. Try to do this in FIFO order,
2806/// and do this until fixpoint, as each complete record type typically
2807/// references
2808/// many other record types.
2809void CodeViewDebug::emitDeferredCompleteTypes() {
2811 while (!DeferredCompleteTypes.empty()) {
2812 std::swap(DeferredCompleteTypes, TypesToEmit);
2813 for (const DICompositeType *RecordTy : TypesToEmit)
2814 getCompleteTypeIndex(RecordTy);
2815 TypesToEmit.clear();
2816 }
2817}
2818
2819void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2820 ArrayRef<LocalVariable> Locals) {
2821 // Get the sorted list of parameters and emit them first.
2823 for (const LocalVariable &L : Locals)
2824 if (L.DIVar->isParameter())
2825 Params.push_back(&L);
2826 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2827 return L->DIVar->getArg() < R->DIVar->getArg();
2828 });
2829 for (const LocalVariable *L : Params)
2830 emitLocalVariable(FI, *L);
2831
2832 // Next emit all non-parameters in the order that we found them.
2833 for (const LocalVariable &L : Locals) {
2834 if (!L.DIVar->isParameter()) {
2835 if (L.ConstantValue) {
2836 // If ConstantValue is set we will emit it as a S_CONSTANT instead of a
2837 // S_LOCAL in order to be able to represent it at all.
2838 const DIType *Ty = L.DIVar->getType();
2839 APSInt Val(*L.ConstantValue);
2840 emitConstantSymbolRecord(Ty, Val, std::string(L.DIVar->getName()));
2841 } else {
2842 emitLocalVariable(FI, L);
2843 }
2844 }
2845 }
2846}
2847
2848void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2849 const LocalVariable &Var) {
2850 // LocalSym record, see SymbolRecord.h for more info.
2851 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2852
2853 LocalSymFlags Flags = LocalSymFlags::None;
2854 if (Var.DIVar->isParameter())
2855 Flags |= LocalSymFlags::IsParameter;
2856 if (Var.DefRanges.empty())
2857 Flags |= LocalSymFlags::IsOptimizedOut;
2858
2859 OS.AddComment("TypeIndex");
2860 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
2861 OS.emitInt32(TI.getIndex());
2862 OS.AddComment("Flags");
2863 OS.emitInt16(static_cast<uint16_t>(Flags));
2864 // Truncate the name so we won't overflow the record length field.
2865 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2866 endSymbolRecord(LocalEnd);
2867
2868 // Calculate the on disk prefix of the appropriate def range record. The
2869 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2870 // should be big enough to hold all forms without memory allocation.
2871 SmallString<20> BytePrefix;
2872 for (const auto &Pair : Var.DefRanges) {
2873 LocalVarDef DefRange = Pair.first;
2874 const auto &Ranges = Pair.second;
2875 BytePrefix.clear();
2876 if (DefRange.InMemory) {
2877 int Offset = DefRange.DataOffset;
2878 unsigned Reg = DefRange.CVRegister;
2879
2880 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2881 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2882 // instead. In frames without stack realignment, $T0 will be the CFA.
2883 if (RegisterId(Reg) == RegisterId::ESP) {
2884 Reg = unsigned(RegisterId::VFRAME);
2885 Offset += FI.OffsetAdjustment;
2886 }
2887
2889
2890 if (DefRange.DerefOffset != LocalVarDef::NoDeref) {
2891 uint16_t RegRelFlags = 0;
2892 if (DefRange.IsSubfield) {
2894 (DefRange.StructOffset
2896 }
2897 DefRangeRegisterRelIndirHeader DRHdr;
2898 DRHdr.Register = Reg;
2899 DRHdr.Flags = RegRelFlags;
2900 DRHdr.BasePointerOffset = Offset;
2901 DRHdr.OffsetInUdt = DefRange.DerefOffset;
2902 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2903 } else if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2904 (bool(Flags & LocalSymFlags::IsParameter)
2905 ? (EncFP == FI.EncodedParamFramePtrReg)
2906 : (EncFP == FI.EncodedLocalFramePtrReg))) {
2907 // If we can use the chosen frame pointer for the frame and this isn't a
2908 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2909 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2910 DefRangeFramePointerRelHeader DRHdr;
2911 DRHdr.Offset = Offset;
2912 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2913 } else {
2914 uint16_t RegRelFlags = 0;
2915 if (DefRange.IsSubfield) {
2917 (DefRange.StructOffset
2919 }
2920 DefRangeRegisterRelHeader DRHdr;
2921 DRHdr.Register = Reg;
2922 DRHdr.Flags = RegRelFlags;
2923 DRHdr.BasePointerOffset = Offset;
2924 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2925 }
2926 } else {
2927 assert(DefRange.DataOffset == 0 &&
2928 DefRange.DerefOffset == LocalVarDef::NoDeref &&
2929 "unexpected offset into register");
2930 if (DefRange.IsSubfield) {
2931 DefRangeSubfieldRegisterHeader DRHdr;
2932 DRHdr.Register = DefRange.CVRegister;
2933 DRHdr.MayHaveNoName = 0;
2934 DRHdr.OffsetInParent = DefRange.StructOffset;
2935 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2936 } else {
2937 DefRangeRegisterHeader DRHdr;
2938 DRHdr.Register = DefRange.CVRegister;
2939 DRHdr.MayHaveNoName = 0;
2940 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2941 }
2942 }
2943 }
2944}
2945
2946void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2947 const FunctionInfo& FI) {
2948 for (LexicalBlock *Block : Blocks)
2949 emitLexicalBlock(*Block, FI);
2950}
2951
2952/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2953/// lexical block scope.
2954void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2955 const FunctionInfo& FI) {
2956 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2957 OS.AddComment("PtrParent");
2958 OS.emitInt32(0); // PtrParent
2959 OS.AddComment("PtrEnd");
2960 OS.emitInt32(0); // PtrEnd
2961 OS.AddComment("Code size");
2962 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2963 OS.AddComment("Function section relative address");
2964 OS.emitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2965 OS.AddComment("Function section index");
2966 OS.emitCOFFSectionIndex(FI.Begin); // Func Symbol
2967 OS.AddComment("Lexical block name");
2968 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2969 endSymbolRecord(RecordEnd);
2970
2971 // Emit variables local to this lexical block.
2972 emitLocalVariableList(FI, Block.Locals);
2973 emitGlobalVariableList(Block.Globals);
2974
2975 // Emit lexical blocks contained within this block.
2976 emitLexicalBlockList(Block.Children, FI);
2977
2978 // Close the lexical block scope.
2979 emitEndSymbolRecord(SymbolKind::S_END);
2980}
2981
2982/// Convenience routine for collecting lexical block information for a list
2983/// of lexical scopes.
2984void CodeViewDebug::collectLexicalBlockInfo(
2989 for (LexicalScope *Scope : Scopes)
2990 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2991}
2992
2993/// Populate the lexical blocks and local variable lists of the parent with
2994/// information about the specified lexical scope.
2995void CodeViewDebug::collectLexicalBlockInfo(
2996 LexicalScope &Scope,
2997 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2998 SmallVectorImpl<LocalVariable> &ParentLocals,
2999 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
3000 if (Scope.isAbstractScope())
3001 return;
3002
3003 // Gather information about the lexical scope including local variables,
3004 // global variables, and address ranges.
3005 bool IgnoreScope = false;
3006 auto LI = ScopeVariables.find(&Scope);
3007 SmallVectorImpl<LocalVariable> *Locals =
3008 LI != ScopeVariables.end() ? &LI->second : nullptr;
3009 auto GI = ScopeGlobals.find(Scope.getScopeNode());
3010 SmallVectorImpl<CVGlobalVariable> *Globals =
3011 GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
3012 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
3013 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
3014
3015 // Ignore lexical scopes which do not contain variables.
3016 if (!Locals && !Globals)
3017 IgnoreScope = true;
3018
3019 // Ignore lexical scopes which are not lexical blocks.
3020 if (!DILB)
3021 IgnoreScope = true;
3022
3023 // Ignore scopes which have too many address ranges to represent in the
3024 // current CodeView format or do not have a valid address range.
3025 //
3026 // For lexical scopes with multiple address ranges you may be tempted to
3027 // construct a single range covering every instruction where the block is
3028 // live and everything in between. Unfortunately, Visual Studio only
3029 // displays variables from the first matching lexical block scope. If the
3030 // first lexical block contains exception handling code or cold code which
3031 // is moved to the bottom of the routine creating a single range covering
3032 // nearly the entire routine, then it will hide all other lexical blocks
3033 // and the variables they contain.
3034 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
3035 IgnoreScope = true;
3036
3037 if (IgnoreScope) {
3038 // This scope can be safely ignored and eliminating it will reduce the
3039 // size of the debug information. Be sure to collect any variable and scope
3040 // information from the this scope or any of its children and collapse them
3041 // into the parent scope.
3042 if (Locals)
3043 ParentLocals.append(Locals->begin(), Locals->end());
3044 if (Globals)
3045 ParentGlobals.append(Globals->begin(), Globals->end());
3046 collectLexicalBlockInfo(Scope.getChildren(),
3047 ParentBlocks,
3048 ParentLocals,
3049 ParentGlobals);
3050 return;
3051 }
3052
3053 // Create a new CodeView lexical block for this lexical scope. If we've
3054 // seen this DILexicalBlock before then the scope tree is malformed and
3055 // we can handle this gracefully by not processing it a second time.
3056 auto BlockInsertion = CurFn->LexicalBlocks.try_emplace(DILB);
3057 if (!BlockInsertion.second)
3058 return;
3059
3060 // Create a lexical block containing the variables and collect the
3061 // lexical block information for the children.
3062 const InsnRange &Range = Ranges.front();
3063 assert(Range.first && Range.second);
3064 LexicalBlock &Block = BlockInsertion.first->second;
3065 Block.Begin = getLabelBeforeInsn(Range.first);
3066 Block.End = getLabelAfterInsn(Range.second);
3067 assert(Block.Begin && "missing label for scope begin");
3068 assert(Block.End && "missing label for scope end");
3069 Block.Name = DILB->getName();
3070 if (Locals)
3071 Block.Locals = std::move(*Locals);
3072 if (Globals)
3073 Block.Globals = std::move(*Globals);
3074 ParentBlocks.push_back(&Block);
3075 collectLexicalBlockInfo(Scope.getChildren(),
3076 Block.Children,
3077 Block.Locals,
3078 Block.Globals);
3079}
3080
3082 const Function &GV = MF->getFunction();
3083 assert(FnDebugInfo.count(&GV));
3084 assert(CurFn == FnDebugInfo[&GV].get());
3085
3086 collectVariableInfo(GV.getSubprogram());
3087
3088 // Build the lexical block structure to emit for this routine.
3089 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
3090 collectLexicalBlockInfo(*CFS,
3091 CurFn->ChildBlocks,
3092 CurFn->Locals,
3093 CurFn->Globals);
3094
3095 // Clear the scope and variable information from the map which will not be
3096 // valid after we have finished processing this routine. This also prepares
3097 // the map for the subsequent routine.
3098 ScopeVariables.clear();
3099
3100 // Don't emit anything if we don't have any line tables.
3101 // Thunks are compiler-generated and probably won't have source correlation.
3102 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
3103 FnDebugInfo.erase(&GV);
3104 CurFn = nullptr;
3105 return;
3106 }
3107
3108 // Find heap alloc sites and add to list.
3109 for (const auto &MBB : *MF) {
3110 for (const auto &MI : MBB) {
3111 if (MDNode *MD = MI.getHeapAllocMarker()) {
3112 CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
3114 dyn_cast<DIType>(MD)));
3115 }
3116 }
3117 }
3118
3119 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
3121 collectDebugInfoForJumpTables(MF, isThumb);
3122
3123 CurFn->Annotations = MF->getCodeViewAnnotations();
3124
3125 CurFn->End = Asm->getFunctionEnd();
3126
3127 CurFn = nullptr;
3128}
3129
3130// Usable locations are valid with non-zero line numbers, or artificial
3131// subprograms because they are associated to the corresponding line within the
3132// inlined callee.
3133//
3134// A line number of zero corresponds to optimized code that doesn't have a
3135// distinct source location.
3136//
3137// In this case, we try to use the previous or next source location depending on
3138// the context.
3140 if (!DL)
3141 return false;
3142 if (DL.getLine() != 0)
3143 return true;
3144 if (const DILocalScope *Scope = DL->getScope())
3145 return Scope->getSubprogram()->isArtificial();
3146 return false;
3147}
3148
3151
3152 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3153 if (!Asm || !CurFn || MI->isDebugInstr() ||
3154 MI->getFlag(MachineInstr::FrameSetup))
3155 return;
3156
3157 // If the first instruction of a new MBB has no location, find the first
3158 // instruction with a location and use that.
3159 DebugLoc DL = MI->getDebugLoc();
3160 if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
3161 for (const auto &NextMI : *MI->getParent()) {
3162 if (NextMI.isDebugInstr())
3163 continue;
3164 DL = NextMI.getDebugLoc();
3165 if (isUsableDebugLoc(DL))
3166 break;
3167 }
3168 // FIXME: Handle the case where the BB has no valid locations. This would
3169 // probably require doing a real dataflow analysis.
3170 }
3171 PrevInstBB = MI->getParent();
3172
3173 // If we still don't have a debug location, don't record a location.
3174 if (!isUsableDebugLoc(DL))
3175 return;
3176
3177 maybeRecordLocation(DL, Asm->MF);
3178}
3179
3180MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
3181 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3182 *EndLabel = MMI->getContext().createTempSymbol();
3183 OS.emitInt32(unsigned(Kind));
3184 OS.AddComment("Subsection size");
3185 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
3186 OS.emitLabel(BeginLabel);
3187 return EndLabel;
3188}
3189
3190void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
3191 OS.emitLabel(EndLabel);
3192 // Every subsection must be aligned to a 4-byte boundary.
3194}
3195
3196MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
3197 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3198 *EndLabel = MMI->getContext().createTempSymbol();
3199 OS.AddComment("Record length");
3200 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
3201 OS.emitLabel(BeginLabel);
3202 if (OS.isVerboseAsm())
3203 OS.AddComment("Record kind: " + getSymbolTypeNames().toString(SymKind));
3204 OS.emitInt16(unsigned(SymKind));
3205 return EndLabel;
3206}
3207
3208void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
3209 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
3210 // an extra copy of every symbol record in LLD. This increases object file
3211 // size by less than 1% in the clang build, and is compatible with the Visual
3212 // C++ linker.
3213 OS.emitValueToAlignment(Align(4));
3214 OS.emitLabel(SymEnd);
3215}
3216
3217void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
3218 OS.AddComment("Record length");
3219 OS.emitInt16(2);
3220 if (OS.isVerboseAsm())
3221 OS.AddComment("Record kind: " + getSymbolTypeNames().toString(EndKind));
3222 OS.emitInt16(uint16_t(EndKind)); // Record Kind
3223}
3224
3225void CodeViewDebug::emitDebugInfoForUDTs(
3226 const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3227#ifndef NDEBUG
3228 size_t OriginalSize = UDTs.size();
3229#endif
3230 for (const auto &UDT : UDTs) {
3231 const DIType *T = UDT.second;
3233 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3234 OS.AddComment("Type");
3235 OS.emitInt32(getCompleteTypeIndex(T).getIndex());
3236 assert(OriginalSize == UDTs.size() &&
3237 "getCompleteTypeIndex found new UDTs!");
3239 endSymbolRecord(UDTRecordEnd);
3240 }
3241}
3242
3243void CodeViewDebug::collectGlobalOrStaticLocalVariableInfo(
3244 const DIGlobalVariableExpression *GVE) {
3245 const DIGlobalVariable *DIGV = GVE->getVariable();
3246 const DIExpression *DIE = GVE->getExpression();
3247 // Don't emit string literals in CodeView, as the only useful parts are
3248 // generally the filename and line number, which isn't possible to output
3249 // in CodeView. String literals should be the only unnamed GlobalVariable
3250 // with debug info.
3251 if (DIGV->getName().empty())
3252 return;
3253
3254 if ((DIE->getNumElements() == 2) &&
3255 (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3256 // Record the constant offset for the variable.
3257 //
3258 // A Fortran common block uses this idiom to encode the offset
3259 // of a variable from the common block's starting address.
3260 CVGlobalVariableOffsets.insert(std::make_pair(DIGV, DIE->getElement(1)));
3261
3262 // Emit constant global variables in a global symbol section.
3263 if (!GlobalMap.count(GVE) && DIE->isConstant())
3264 GlobalVariables.emplace_back(CVGlobalVariable{DIGV, DIE});
3265
3266 const auto *GV = GlobalMap.lookup(GVE);
3267 if (!GV || GV->isDeclarationForLinker())
3268 return;
3269
3270 DIScope *Scope = DIGV->getScope();
3271 SmallVector<CVGlobalVariable, 1> *VariableList;
3272 if (Scope && isa<DILocalScope>(Scope)) {
3273 // Locate a global variable list for this scope, creating one if
3274 // necessary.
3275 auto Insertion =
3276 ScopeGlobals.insert({Scope, std::unique_ptr<GlobalVariableList>()});
3277 if (Insertion.second)
3278 Insertion.first->second = std::make_unique<GlobalVariableList>();
3279 VariableList = Insertion.first->second.get();
3280 } else if (GV->hasComdat()) {
3281 // Emit this global variable into a COMDAT section.
3282 VariableList = &ComdatVariables;
3283 } else {
3284 // Emit this global variable in a single global symbol section.
3285 VariableList = &GlobalVariables;
3286 }
3287 VariableList->emplace_back(CVGlobalVariable{DIGV, GV});
3288}
3289
3290void CodeViewDebug::collectGlobalVariableInfo() {
3291 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3293 GV.getDebugInfo(GVEs);
3294 for (const auto *GVE : GVEs)
3295 GlobalMap[GVE] = &GV;
3296 }
3297
3298 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3299 for (const MDNode *Node : CUs->operands()) {
3300 const auto *CU = cast<DICompileUnit>(Node);
3301 for (const auto *GVE : CU->getGlobalVariables()) {
3302 collectGlobalOrStaticLocalVariableInfo(GVE);
3303 }
3304 }
3305}
3306
3307void CodeViewDebug::collectDebugInfoForGlobals() {
3308 for (const CVGlobalVariable &CVGV : GlobalVariables) {
3309 const DIGlobalVariable *DIGV = CVGV.DIGV;
3310 const DIScope *Scope = DIGV->getScope();
3311 getCompleteTypeIndex(DIGV->getType());
3312 getFullyQualifiedName(Scope, DIGV->getName());
3313 }
3314
3315 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3316 const DIGlobalVariable *DIGV = CVGV.DIGV;
3317 const DIScope *Scope = DIGV->getScope();
3318 getCompleteTypeIndex(DIGV->getType());
3319 getFullyQualifiedName(Scope, DIGV->getName());
3320 }
3321}
3322
3323void CodeViewDebug::emitDebugInfoForGlobals() {
3324 // First, emit all globals that are not in a comdat in a single symbol
3325 // substream. MSVC doesn't like it if the substream is empty, so only open
3326 // it if we have at least one global to emit.
3327 switchToDebugSectionForSymbol(nullptr);
3328 if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3329 OS.AddComment("Symbol subsection for globals");
3330 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3331 emitGlobalVariableList(GlobalVariables);
3332 emitStaticConstMemberList();
3333 endCVSubsection(EndLabel);
3334 }
3335
3336 // Second, emit each global that is in a comdat into its own .debug$S
3337 // section along with its own symbol substream.
3338 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3339 const GlobalVariable *GV = cast<const GlobalVariable *>(CVGV.GVInfo);
3340 MCSymbol *GVSym = Asm->getSymbol(GV);
3341 OS.AddComment("Symbol subsection for " +
3343 switchToDebugSectionForSymbol(GVSym);
3344 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3345 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3346 emitDebugInfoForGlobal(CVGV);
3347 endCVSubsection(EndLabel);
3348 }
3349}
3350
3351void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3352 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3353 for (const MDNode *Node : CUs->operands()) {
3354 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3355 if (DIType *RT = dyn_cast<DIType>(Ty)) {
3356 getTypeIndex(RT);
3357 // FIXME: Add to global/local DTU list.
3358 }
3359 }
3360 }
3361}
3362
3363// Emit each global variable in the specified array.
3364void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3365 for (const CVGlobalVariable &CVGV : Globals) {
3366 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3367 emitDebugInfoForGlobal(CVGV);
3368 }
3369}
3370
3371void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3372 const std::string &QualifiedName) {
3373 MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3374 OS.AddComment("Type");
3375 OS.emitInt32(getTypeIndex(DTy).getIndex());
3376
3377 OS.AddComment("Value");
3378
3379 // Encoded integers shouldn't need more than 10 bytes.
3380 uint8_t Data[10];
3381 BinaryStreamWriter Writer(Data, llvm::endianness::little);
3382 CodeViewRecordIO IO(Writer);
3383 cantFail(IO.mapEncodedInteger(Value));
3384 StringRef SRef((char *)Data, Writer.getOffset());
3385 OS.emitBinaryData(SRef);
3386
3387 OS.AddComment("Name");
3388 emitNullTerminatedSymbolName(OS, QualifiedName);
3389 endSymbolRecord(SConstantEnd);
3390}
3391
3392void CodeViewDebug::emitStaticConstMemberList() {
3393 for (const DIDerivedType *DTy : StaticConstMembers) {
3394 const DIScope *Scope = DTy->getScope();
3395
3396 APSInt Value;
3397 if (const ConstantInt *CI =
3398 dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3399 Value = APSInt(CI->getValue(),
3400 DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3401 else if (const ConstantFP *CFP =
3402 dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3403 Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3404 else
3405 llvm_unreachable("cannot emit a constant without a value");
3406
3407 emitConstantSymbolRecord(DTy->getBaseType(), Value,
3408 getFullyQualifiedName(Scope, DTy->getName()));
3409 }
3410}
3411
3412static bool isFloatDIType(const DIType *Ty) {
3413 if (isa<DICompositeType>(Ty))
3414 return false;
3415
3416 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3417 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3418 if (T == dwarf::DW_TAG_pointer_type ||
3419 T == dwarf::DW_TAG_ptr_to_member_type ||
3420 T == dwarf::DW_TAG_reference_type ||
3421 T == dwarf::DW_TAG_rvalue_reference_type)
3422 return false;
3423 assert(DTy->getBaseType() && "Expected valid base type");
3424 return isFloatDIType(DTy->getBaseType());
3425 }
3426
3427 auto *BTy = cast<DIBasicType>(Ty);
3428 return (BTy->getEncoding() == dwarf::DW_ATE_float);
3429}
3430
3431void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3432 const DIGlobalVariable *DIGV = CVGV.DIGV;
3433
3434 const DIScope *Scope = DIGV->getScope();
3435 // For static data members, get the scope from the declaration.
3436 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3438 Scope = MemberDecl->getScope();
3439 // For static local variables and Fortran, the scoping portion is elided
3440 // in its name so that we can reference the variable in the command line
3441 // of the VS debugger.
3442 std::string QualifiedName =
3443 (moduleIsInFortran() || (Scope && isa<DILocalScope>(Scope)))
3444 ? std::string(DIGV->getName())
3445 : getFullyQualifiedName(Scope, DIGV->getName());
3446
3447 if (const GlobalVariable *GV =
3449 // DataSym record, see SymbolRecord.h for more info. Thread local data
3450 // happens to have the same format as global data.
3451 MCSymbol *GVSym = Asm->getSymbol(GV);
3452 SymbolKind DataSym = GV->isThreadLocal()
3453 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3454 : SymbolKind::S_GTHREAD32)
3455 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3456 : SymbolKind::S_GDATA32);
3457 MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3458 OS.AddComment("Type");
3459 OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
3460 OS.AddComment("DataOffset");
3461
3462 // Use the offset seen while collecting info on globals.
3463 uint64_t Offset = CVGlobalVariableOffsets.lookup(DIGV);
3464 OS.emitCOFFSecRel32(GVSym, Offset);
3465
3466 OS.AddComment("Segment");
3467 OS.emitCOFFSectionIndex(GVSym);
3468 OS.AddComment("Name");
3469 const unsigned LengthOfDataRecord = 12;
3470 emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
3471 endSymbolRecord(DataEnd);
3472 } else {
3473 const DIExpression *DIE = cast<const DIExpression *>(CVGV.GVInfo);
3474 assert(DIE->isConstant() &&
3475 "Global constant variables must contain a constant expression.");
3476
3477 // Use unsigned for floats.
3478 bool isUnsigned = isFloatDIType(DIGV->getType())
3479 ? true
3480 : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
3481 APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3482 emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
3483 }
3484}
3485
3487 const MachineFunction *MF, bool isThumb,
3488 const std::function<void(const MachineJumpTableInfo &, const MachineInstr &,
3489 int64_t)> &Callback) {
3490 auto JTI = MF->getJumpTableInfo();
3491 if (JTI && !JTI->isEmpty()) {
3492#ifndef NDEBUG
3493 auto UsedJTs = llvm::SmallBitVector(JTI->getJumpTables().size());
3494#endif
3495 for (const auto &MBB : *MF) {
3496 // Search for indirect branches...
3497 const auto LastMI = MBB.getFirstTerminator();
3498 if (LastMI != MBB.end() && LastMI->isIndirectBranch()) {
3499 if (isThumb) {
3500 // ... that directly use jump table operands.
3501 // NOTE: ARM uses pattern matching to lower its BR_JT SDNode to
3502 // machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node
3503 // interferes with this process *but* the resulting pseudo-instruction
3504 // uses a Jump Table operand, so extract the jump table index directly
3505 // from that.
3506 for (const auto &MO : LastMI->operands()) {
3507 if (MO.isJTI()) {
3508 unsigned Index = MO.getIndex();
3509#ifndef NDEBUG
3510 UsedJTs.set(Index);
3511#endif
3512 Callback(*JTI, *LastMI, Index);
3513 break;
3514 }
3515 }
3516 } else {
3517 // ... that have jump table debug info.
3518 // NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node
3519 // when lowering the BR_JT SDNode to an indirect branch.
3520 for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I) {
3521 if (I->isJumpTableDebugInfo()) {
3522 unsigned Index = I->getOperand(0).getImm();
3523#ifndef NDEBUG
3524 UsedJTs.set(Index);
3525#endif
3526 Callback(*JTI, *LastMI, Index);
3527 break;
3528 }
3529 }
3530 }
3531 }
3532 }
3533#ifndef NDEBUG
3534 assert(UsedJTs.all() &&
3535 "Some of jump tables were not used in a debug info instruction");
3536#endif
3537 }
3538}
3539
3540void CodeViewDebug::discoverJumpTableBranches(const MachineFunction *MF,
3541 bool isThumb) {
3543 MF, isThumb,
3544 [this](const MachineJumpTableInfo &, const MachineInstr &BranchMI,
3545 int64_t) { requestLabelBeforeInsn(&BranchMI); });
3546}
3547
3548void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction *MF,
3549 bool isThumb) {
3551 MF, isThumb,
3552 [this, MF](const MachineJumpTableInfo &JTI, const MachineInstr &BranchMI,
3553 int64_t JumpTableIndex) {
3554 // For label-difference jump tables, find the base expression.
3555 // Otherwise the jump table uses an absolute address (so no base
3556 // is required).
3557 const MCSymbol *Base;
3558 uint64_t BaseOffset = 0;
3559 const MCSymbol *Branch = getLabelBeforeInsn(&BranchMI);
3560 JumpTableEntrySize EntrySize;
3561 switch (JTI.getEntryKind()) {
3566 "EK_Custom32, EK_GPRel32BlockAddress, and "
3567 "EK_GPRel64BlockAddress should never be emitted for COFF");
3569 // Each entry is an absolute address.
3570 EntrySize = JumpTableEntrySize::Pointer;
3571 Base = nullptr;
3572 break;
3576 // Ask the AsmPrinter.
3577 std::tie(Base, BaseOffset, Branch, EntrySize) =
3578 Asm->getCodeViewJumpTableInfo(JumpTableIndex, &BranchMI, Branch);
3579 break;
3580 }
3581
3582 const MachineJumpTableEntry &JTE = JTI.getJumpTables()[JumpTableIndex];
3583 JumpTableInfo CVJTI{EntrySize,
3584 Base,
3585 BaseOffset,
3586 Branch,
3587 MF->getJTISymbol(JumpTableIndex, MMI->getContext()),
3588 JTE.MBBs.size(),
3589 {}};
3590 for (const auto &MBB : JTE.MBBs)
3591 CVJTI.Cases.push_back(MBB->getSymbol());
3592 CurFn->JumpTables.push_back(std::move(CVJTI));
3593 });
3594}
3595
3596void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo &FI) {
3597 // Emit S_LABEL32 records for each jump target
3598 for (const auto &JumpTable : FI.JumpTables) {
3599 for (const auto &CaseSym : JumpTable.Cases) {
3600 MCSymbol *LabelEnd = beginSymbolRecord(SymbolKind::S_LABEL32);
3601 OS.AddComment("Offset and segment");
3602 OS.emitCOFFSecRel32(CaseSym, 0);
3603 OS.AddComment("Flags");
3604 OS.emitInt8(0);
3605 emitNullTerminatedSymbolName(OS, CaseSym->getName());
3606 endSymbolRecord(LabelEnd);
3607 }
3608 }
3609
3610 for (const auto &JumpTable : FI.JumpTables) {
3611 MCSymbol *JumpTableEnd = beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE);
3612 if (JumpTable.Base) {
3613 OS.AddComment("Base offset");
3614 OS.emitCOFFSecRel32(JumpTable.Base, JumpTable.BaseOffset);
3615 OS.AddComment("Base section index");
3616 OS.emitCOFFSectionIndex(JumpTable.Base);
3617 } else {
3618 OS.AddComment("Base offset");
3619 OS.emitInt32(0);
3620 OS.AddComment("Base section index");
3621 OS.emitInt16(0);
3622 }
3623 OS.AddComment("Switch type");
3624 OS.emitInt16(static_cast<uint16_t>(JumpTable.EntrySize));
3625 OS.AddComment("Branch offset");
3626 OS.emitCOFFSecRel32(JumpTable.Branch, /*Offset=*/0);
3627 OS.AddComment("Table offset");
3628 OS.emitCOFFSecRel32(JumpTable.Table, /*Offset=*/0);
3629 OS.AddComment("Branch section index");
3630 OS.emitCOFFSectionIndex(JumpTable.Branch);
3631 OS.AddComment("Table section index");
3632 OS.emitCOFFSectionIndex(JumpTable.Table);
3633 OS.AddComment("Entries count");
3634 OS.emitInt32(JumpTable.TableSize);
3635 endSymbolRecord(JumpTableEnd);
3636 }
3637}
3638
3639void CodeViewDebug::emitInlinees(
3640 const SmallSet<codeview::TypeIndex, 1> &Inlinees) {
3641 // Divide the list of inlinees into chunks such that each chunk fits within
3642 // one record.
3643 constexpr size_t ChunkSize =
3644 (MaxRecordLength - sizeof(SymbolKind) - sizeof(uint32_t)) /
3645 sizeof(uint32_t);
3646
3647 SmallVector<TypeIndex> SortedInlinees{Inlinees.begin(), Inlinees.end()};
3648 llvm::sort(SortedInlinees);
3649
3650 size_t CurrentIndex = 0;
3651 while (CurrentIndex < SortedInlinees.size()) {
3652 auto Symbol = beginSymbolRecord(SymbolKind::S_INLINEES);
3653 auto CurrentChunkSize =
3654 std::min(ChunkSize, SortedInlinees.size() - CurrentIndex);
3655 OS.AddComment("Count");
3656 OS.emitInt32(CurrentChunkSize);
3657
3658 const size_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize;
3659 for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) {
3660 OS.AddComment("Inlinee");
3661 OS.emitInt32(SortedInlinees[CurrentIndex].getIndex());
3662 }
3663 endSymbolRecord(Symbol);
3664 }
3665}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static bool isThumb(const MCSubtargetInfo &STI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static MethodKind translateMethodKindFlags(const DISubprogram *SP, bool Introduced)
static bool isUsableDebugLoc(DebugLoc DL)
static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, StringRef S)
static CPUType mapArchToCVCPUType(Triple::ArchType Type)
static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, unsigned MaxFixedRecordLength=0xF00)
static Version parseVersion(StringRef Name)
static MethodOptions translateMethodOptionFlags(const DISubprogram *SP)
static bool isNonTrivial(const DICompositeType *DCTy)
static std::string formatNestedName(ArrayRef< StringRef > QualifiedNameComponents, StringRef TypeName)
static ClassOptions getCommonClassOptions(const DICompositeType *Ty)
Return ClassOptions that should be present on both the forward declaration and the defintion of a tag...
static PointerToMemberRepresentation translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags)
static FunctionOptions getFunctionOptions(const DISubroutineType *Ty, const DICompositeType *ClassTy=nullptr, StringRef SPName=StringRef(""))
static StringRef removeTemplateArgs(StringRef Name)
static TypeRecordKind getRecordKind(const DICompositeType *Ty)
void forEachJumpTableBranch(const MachineFunction *MF, bool isThumb, const std::function< void(const MachineJumpTableInfo &, const MachineInstr &, int64_t)> &Callback)
static CallingConvention dwarfCCToCodeView(unsigned DwarfCC)
Given a DWARF calling convention, get the CodeView equivalent.
static SourceLanguage MapDWARFLanguageToCVLang(dwarf::SourceLanguageName DWLName)
static bool isFloatDIType(const DIType *Ty)
static void addLocIfNotPresent(SmallVectorImpl< const DILocation * > &Locs, const DILocation *Loc)
static bool shouldEmitUdt(const DIType *T)
static StringRef getPrettyScopeName(const DIScope *Scope)
static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty)
static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
dxil translate DXIL Translate Metadata
This file contains constants used for implementing Dwarf debug support.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static constexpr StringLiteral Filename
#define P(N)
static StringRef getName(Value *V)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallString class.
This file describes how to lower LLVM code to machine code.
static const uint32_t IV[8]
Definition blake3_impl.h:83
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
CodeViewDebug(AsmPrinter *AP)
void beginModule(Module *M) override
bool moduleIsInFortran()
Check if the current module is in Fortran.
void endFunctionImpl(const MachineFunction *) override
Gather post-function debug information.
void endModule() override
Emit the COFF section that holds the line table information.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
Basic type, like 'int' or 'float'.
unsigned getEncoding() const
StringRef getIdentifier() const
DINodeArray getElements() const
DIType * getBaseType() const
LLVM_ABI DIType * getClassType() const
Get casted version of extra data.
LLVM_ABI Constant * getConstant() const
unsigned getNumElements() const
uint64_t getElement(unsigned I) const
static LLVM_ABI bool extractLeadingOffset(ArrayRef< uint64_t > Ops, int64_t &OffsetInBytes, SmallVectorImpl< uint64_t > &RemainingOps)
LLVM_ABI std::optional< SignedOrUnsignedConstant > isConstant() const
Determine whether this represents a constant value, if so.
A pair of DIGlobalVariable and DIExpression.
DIGlobalVariable * getVariable() const
Metadata * getRawStaticDataMemberDeclaration() const
A scope for locals.
DILocalScope * getScope() const
Get the local scope for this variable.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
Base class for scope-like contexts.
StringRef getFilename() const
LLVM_ABI StringRef getName() const
DIFile * getFile() const
StringRef getDirectory() const
LLVM_ABI DIScope * getScope() const
Wrapper structure that holds source language identity metadata that includes language name,...
uint16_t getName() const
Returns a versioned or unversioned language name.
String type, Fortran CHARACTER(n)
Subprogram description. Uses SubclassData1.
Type array for a subprogram.
DITypeArray getTypeArray() const
Base class for types.
uint64_t getOffsetInBits() const
bool isObjectPointer() const
DIFlags getFlags() const
StringRef getName() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
unsigned getLine() const
DIScope * getScope() const
DIScope * getScope() const
DIType * getType() const
StringRef getName() const
static const EntryIndex NoEntry
Special value to indicate that an entry is valid until the end of the function.
static bool isUnsignedDIType(const DIType *Ty)
Return true if type encoding is unsigned.
AsmPrinter * Asm
Target of debug info emission.
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const MachineBasicBlock * PrevInstBB
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
const MachineInstr * PrologEndLoc
This location indicates end of function prologue and beginning of function body.
static uint64_t getBaseTypeSize(const DIType *Ty)
If this type is derived from a base type then return base type size.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:688
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
Definition Function.cpp:830
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:879
Constant * getPersonalityFn() const
Get the personality function associated with this function.
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:682
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition Function.h:312
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Definition Function.h:729
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:723
bool hasComdat() const
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool isDeclarationForLinker() const
This class is used to track scope information.
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
MCSymbol * getCOMDATSymbol() const
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:404
virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size)
Emit the absolute difference between two symbols.
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
virtual void emitValueToAlignment(Align Alignment, int64_t Fill=0, uint8_t FillLen=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
void emitInt32(uint64_t Value)
Definition MCStreamer.h:767
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition MCSymbol.h:251
Metadata node.
Definition Metadata.h:1069
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
unsigned getCVBytesOfCalleeSavedRegisters() const
Returns how many bytes of callee-saved registers the target pushed in the prologue.
bool hasStackProtectorIndex() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
auto getInStackSlotVariableDbgInfo()
Returns the collection of variables for which we have debug info and that have been assigned a stack ...
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
ArrayRef< std::pair< MCSymbol *, MDNode * > > getCodeViewAnnotations() const
Representation of each machine instruction.
bool isDebugValue() const
MachineOperand & getDebugOperand(unsigned Index)
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_LabelDifference64
EK_LabelDifference64 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
const MCContext & getContext() const
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1753
iterator_range< op_iterator > operands()
Definition Metadata.h:1849
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
const_iterator begin() const
Definition SmallSet.h:216
const_iterator end() const
Definition SmallSet.h:222
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
char back() const
Get the last character in the string.
Definition StringRef.h:153
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition StringRef.h:606
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
@ UnknownArch
Definition Triple.h:50
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
@ CurrentDirectory
Absolute CWD path.
Definition TypeRecord.h:678
@ SourceFile
Path to main source file, relative or absolute.
Definition TypeRecord.h:680
@ BuildTool
Absolute compiler path.
Definition TypeRecord.h:679
@ CommandLine
Full canonical command line (maybe -cc1)
Definition TypeRecord.h:682
@ TypeServerPDB
Absolute path of type server PDB (/Fd)
Definition TypeRecord.h:681
LLVM_ABI void begin(ContinuationRecordKind RecordKind)
A 32-bit type reference.
Definition TypeIndex.h:97
SimpleTypeKind getSimpleKind() const
Definition TypeIndex.h:137
static TypeIndex None()
Definition TypeIndex.h:149
SimpleTypeMode getSimpleMode() const
Definition TypeIndex.h:142
static const uint32_t FirstNonSimpleIndex
Definition TypeIndex.h:99
static LLVM_ABI StringRef simpleTypeName(TypeIndex TI)
Definition TypeIndex.cpp:71
static TypeIndex Void()
Definition TypeIndex.h:150
uint32_t getIndex() const
Definition TypeIndex.h:112
static TypeIndex NullptrT()
Definition TypeIndex.h:158
static TypeIndex Int32()
Definition TypeIndex.h:183
void addCallbackToPipeline(TypeVisitorCallbacks &Callbacks)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
IteratorT begin() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
@ DEBUG_HASHES_SECTION_MAGIC
Definition COFF.h:840
@ DEBUG_SECTION_MAGIC
Definition COFF.h:839
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
PointerMode
Equivalent to CV_ptrmode_e.
Definition CodeView.h:335
ProcSymFlags
Corresponds to the CV_PROCFLAGS bitfield.
Definition CodeView.h:415
PointerOptions
Equivalent to misc lfPointerAttr bitfields.
Definition CodeView.h:344
LocalSymFlags
Corresponds to CV_LVARFLAGS bitfield.
Definition CodeView.h:388
MethodKind
Part of member attribute flags. (CV_methodprop_e)
Definition CodeView.h:252
CVRecord< TypeLeafKind > CVType
Definition CVRecord.h:64
PointerKind
Equivalent to CV_ptrtype_e.
Definition CodeView.h:318
CPUType
These values correspond to the CV_CPU_TYPE_e enumeration, and are documented here: https://msdn....
Definition CodeView.h:76
PointerToMemberRepresentation
Equivalent to CV_pmtype_e.
Definition CodeView.h:358
CallingConvention
These values correspond to the CV_call_e enumeration, and are documented at the following locations: ...
Definition CodeView.h:156
MethodOptions
Equivalent to CV_fldattr_t bitfield.
Definition CodeView.h:263
MemberAccess
Source-level access specifier. (CV_access_e)
Definition CodeView.h:244
ThunkOrdinal
These values correspond to the THUNK_ORDINAL enumeration.
Definition CodeView.h:536
LLVM_ABI EnumStrings< SymbolKind, 1 > getSymbolTypeNames()
EncodedFramePtrReg
Two-bit value indicating which register is the designated frame pointer register.
Definition CodeView.h:523
TypeRecordKind
Distinguishes individual records in .debug$T or .debug$P section or PDB type stream.
Definition CodeView.h:27
SymbolKind
Duplicate copy of the above enum, but using the official CV names.
Definition CodeView.h:48
ModifierOptions
Equivalent to CV_modifier_t.
Definition CodeView.h:283
LLVM_ABI EncodedFramePtrReg encodeFramePtrReg(RegisterId Reg, CPUType CPU)
LLVM_ABI Error visitTypeRecord(CVType &Record, TypeIndex Index, TypeVisitorCallbacks &Callbacks, VisitorDataSource Source=VDS_BytesPresent)
SourceLanguage
These values correspond to the CV_CFL_LANG enumeration in the Microsoft Debug Interface Access SDK,...
Definition CodeView.h:146
SourceLanguageName
Definition Dwarf.h:229
std::optional< std::pair< SourceLanguageName, uint32_t > > toDW_LNAME(SourceLanguage language)
Convert a DWARF 5 DW_LANG to a DWARF 6 pair of language name and version.
Definition Dwarf.h:378
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:383
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:573
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
std::string fromHex(StringRef Input)
Convert hexadecimal string Input to its binary representation. The return string is half the size of ...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
std::tuple< uint64_t, uint32_t > InlineSite
LLVM_GET_TYPE_NAME_CONSTEXPR StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
Definition TypeName.h:40
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
This is used to track range of instructions with identical lexical scope.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
const DIDerivedType * MemberTypeNode
std::vector< MemberInfo > MemberList
MemberList Members
Direct members.
std::vector< const DIType * > NestedTypes
MapVector< MDString *, MethodsList > MethodsMap
std::vector< const DIDerivedType * > Inheritance
Base classes.
TinyPtrVector< const DISubprogram * > MethodsList
int InMemory
Indicates that variable data is stored in memory relative to the specified register.
uint32_t CVRegister
Register containing the data or the register base of the memory location containing the data.
static constexpr int32_t NoDeref
Value for DerefOffset indicating this is not an indirect load.
static LLVM_ABI std::optional< DbgVariableLocation > extractFromMachineInstruction(const MachineInstr &Instruction)
Extract a VariableLocation from a MachineInstr.
std::vector< MachineBasicBlock * > MBBs
MBBs - The vector of basic blocks from which to create the jump table.
little32_t OffsetInUdt
Offset to add after dereferencing Register + BasePointerOffset.