LLVM 24.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 const Module *M = MMI->getModule();
897 ArchType Arch = M->getTargetTriple().getArch();
898 // The module flag survives LTO, and is reset to 0 if any merged module lacks
899 // it.
900 auto *HotpatchFlag =
901 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("ms-hotpatch"));
902 if ((HotpatchFlag && HotpatchFlag->isOne()) || Arch == ArchType::thumb ||
903 Arch == ArchType::aarch64) {
904 Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
905 }
906
907 OS.AddComment("Flags and language");
908 OS.emitInt32(Flags);
909
910 OS.AddComment("CPUType");
911 OS.emitInt16(static_cast<uint64_t>(TheCPU));
912
913 StringRef CompilerVersion = "0";
914 if (TheCU)
915 CompilerVersion = TheCU->getProducer();
916
917 Version FrontVer = parseVersion(CompilerVersion);
918 OS.AddComment("Frontend version");
919 for (int N : FrontVer.Part) {
920 OS.emitInt16(N);
921 }
922
923 // Some Microsoft tools, like Binscope, expect a backend version number of at
924 // least 8.something, so we'll coerce the LLVM version into a form that
925 // guarantees it'll be big enough without really lying about the version.
926 int Major = 1000 * LLVM_VERSION_MAJOR +
927 10 * LLVM_VERSION_MINOR +
928 LLVM_VERSION_PATCH;
929 // Clamp it for builds that use unusually large version numbers.
930 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
931 Version BackVer = {{ Major, 0, 0, 0 }};
932 OS.AddComment("Backend version");
933 for (int N : BackVer.Part)
934 OS.emitInt16(N);
935
936 OS.AddComment("Null-terminated compiler version string");
937 emitNullTerminatedSymbolName(OS, CompilerVersion);
938
939 endSymbolRecord(CompilerEnd);
940}
941
943 StringRef S) {
944 StringIdRecord SIR(TypeIndex(0x0), S);
945 return TypeTable.writeLeafType(SIR);
946}
947
948void CodeViewDebug::emitBuildInfo() {
949 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
950 // build info. The known prefix is:
951 // - Absolute path of current directory
952 // - Compiler path
953 // - Main source file path, relative to CWD or absolute
954 // - Type server PDB file
955 // - Canonical compiler command line
956 // If frontend and backend compilation are separated (think llc or LTO), it's
957 // not clear if the compiler path should refer to the executable for the
958 // frontend or the backend. Leave it blank for now.
959 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
960 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
961 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
962 const auto *CU = cast<DICompileUnit>(Node);
963 const DIFile *MainSourceFile = CU->getFile();
964 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
965 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
966 BuildInfoArgs[BuildInfoRecord::SourceFile] =
967 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
968 // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
969 BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
970 getStringIdTypeIdx(TypeTable, "");
971 BuildInfoArgs[BuildInfoRecord::BuildTool] =
972 getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
974 TypeTable, Asm->TM.Options.MCOptions.CommandlineArgs);
975
976 BuildInfoRecord BIR(BuildInfoArgs);
977 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
978
979 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
980 // from the module symbols into the type stream.
981 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
982 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
983 OS.AddComment("LF_BUILDINFO index");
984 OS.emitInt32(BuildInfoIndex.getIndex());
985 endSymbolRecord(BIEnd);
986 endCVSubsection(BISubsecEnd);
987}
988
989void CodeViewDebug::emitInlineeLinesSubsection() {
990 if (InlinedSubprograms.empty())
991 return;
992
993 OS.AddComment("Inlinee lines subsection");
994 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
995
996 // We emit the checksum info for files. This is used by debuggers to
997 // determine if a pdb matches the source before loading it. Visual Studio,
998 // for instance, will display a warning that the breakpoints are not valid if
999 // the pdb does not match the source.
1000 OS.AddComment("Inlinee lines signature");
1001 OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
1002
1003 for (const DISubprogram *SP : InlinedSubprograms) {
1004 assert(TypeIndices.count({SP, nullptr}));
1005 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
1006
1007 OS.addBlankLine();
1008 unsigned FileId = maybeRecordFile(SP->getFile());
1009 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
1010 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
1011 OS.addBlankLine();
1012 OS.AddComment("Type index of inlined function");
1013 OS.emitInt32(InlineeIdx.getIndex());
1014 OS.AddComment("Offset into filechecksum table");
1015 OS.emitCVFileChecksumOffsetDirective(FileId);
1016 OS.AddComment("Starting line number");
1017 OS.emitInt32(SP->getLine());
1018 }
1019
1020 endCVSubsection(InlineEnd);
1021}
1022
1023void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
1024 const DILocation *InlinedAt,
1025 const InlineSite &Site) {
1026 assert(TypeIndices.count({Site.Inlinee, nullptr}));
1027 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
1028
1029 // SymbolRecord
1030 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
1031
1032 OS.AddComment("PtrParent");
1033 OS.emitInt32(0);
1034 OS.AddComment("PtrEnd");
1035 OS.emitInt32(0);
1036 OS.AddComment("Inlinee type index");
1037 OS.emitInt32(InlineeIdx.getIndex());
1038
1039 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
1040 unsigned StartLineNum = Site.Inlinee->getLine();
1041
1042 OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
1043 FI.Begin, FI.End);
1044
1045 endSymbolRecord(InlineEnd);
1046
1047 emitLocalVariableList(FI, Site.InlinedLocals);
1048
1049 // Recurse on child inlined call sites before closing the scope.
1050 for (const DILocation *ChildSite : Site.ChildSites) {
1051 auto I = FI.InlineSites.find(ChildSite);
1052 assert(I != FI.InlineSites.end() &&
1053 "child site not in function inline site map");
1054 emitInlinedCallSite(FI, ChildSite, I->second);
1055 }
1056
1057 // Close the scope.
1058 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
1059}
1060
1061void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
1062 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
1063 // comdat key. A section may be comdat because of -ffunction-sections or
1064 // because it is comdat in the IR.
1065 MCSectionCOFF *GVSec =
1066 GVSym ? static_cast<MCSectionCOFF *>(&GVSym->getSection()) : nullptr;
1067 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
1068
1069 auto *DebugSec = static_cast<MCSectionCOFF *>(
1070 CompilerInfoAsm->getObjFileLowering().getCOFFDebugSymbolsSection());
1071 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
1072
1073 OS.switchSection(DebugSec);
1074
1075 // Emit the magic version number if this is the first time we've switched to
1076 // this section.
1077 if (ComdatDebugSections.insert(DebugSec).second)
1078 emitCodeViewMagicVersion();
1079}
1080
1081// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
1082// The only supported thunk ordinal is currently the standard type.
1083void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
1084 FunctionInfo &FI,
1085 const MCSymbol *Fn) {
1086 std::string FuncName =
1087 std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1088 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
1089
1090 OS.AddComment("Symbol subsection for " + Twine(FuncName));
1091 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1092
1093 // Emit S_THUNK32
1094 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
1095 OS.AddComment("PtrParent");
1096 OS.emitInt32(0);
1097 OS.AddComment("PtrEnd");
1098 OS.emitInt32(0);
1099 OS.AddComment("PtrNext");
1100 OS.emitInt32(0);
1101 OS.AddComment("Thunk section relative address");
1102 OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
1103 OS.AddComment("Thunk section index");
1104 OS.emitCOFFSectionIndex(Fn);
1105 OS.AddComment("Code size");
1106 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
1107 OS.AddComment("Ordinal");
1108 OS.emitInt8(unsigned(ordinal));
1109 OS.AddComment("Function name");
1110 emitNullTerminatedSymbolName(OS, FuncName);
1111 // Additional fields specific to the thunk ordinal would go here.
1112 endSymbolRecord(ThunkRecordEnd);
1113
1114 // Local variables/inlined routines are purposely omitted here. The point of
1115 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
1116
1117 // Emit S_PROC_ID_END
1118 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1119
1120 endCVSubsection(SymbolsEnd);
1121}
1122
1123void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
1124 FunctionInfo &FI) {
1125 // For each function there is a separate subsection which holds the PC to
1126 // file:line table.
1127 const MCSymbol *Fn = Asm->getSymbol(GV);
1128 assert(Fn);
1129
1130 // Switch to the to a comdat section, if appropriate.
1131 switchToDebugSectionForSymbol(Fn);
1132
1133 std::string FuncName;
1134 auto *SP = GV->getSubprogram();
1135 assert(SP);
1136 setCurrentSubprogram(SP);
1137
1138 if (SP->isThunk()) {
1139 emitDebugInfoForThunk(GV, FI, Fn);
1140 return;
1141 }
1142
1143 // If we have a display name, build the fully qualified name by walking the
1144 // chain of scopes.
1145 if (!SP->getName().empty())
1146 FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1147
1148 // If our DISubprogram name is empty, use the mangled name.
1149 if (FuncName.empty())
1150 FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1151
1152 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1153 if (MMI->getModule()->getTargetTriple().getArch() == Triple::x86)
1154 OS.emitCVFPOData(Fn);
1155
1156 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1157 OS.AddComment("Symbol subsection for " + Twine(FuncName));
1158 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1159 {
1160 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1161 : SymbolKind::S_GPROC32_ID;
1162 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1163
1164 // These fields are filled in by tools like CVPACK which run after the fact.
1165 OS.AddComment("PtrParent");
1166 OS.emitInt32(0);
1167 OS.AddComment("PtrEnd");
1168 OS.emitInt32(0);
1169 OS.AddComment("PtrNext");
1170 OS.emitInt32(0);
1171 // This is the important bit that tells the debugger where the function
1172 // code is located and what's its size:
1173 OS.AddComment("Code size");
1174 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1175 OS.AddComment("Offset after prologue");
1176 OS.emitInt32(0);
1177 OS.AddComment("Offset before epilogue");
1178 OS.emitInt32(0);
1179 OS.AddComment("Function type index");
1180 OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
1181 OS.AddComment("Function section relative address");
1182 OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
1183 OS.AddComment("Function section index");
1184 OS.emitCOFFSectionIndex(Fn);
1185 OS.AddComment("Flags");
1186 ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo;
1187 if (FI.HasFramePointer)
1188 ProcFlags |= ProcSymFlags::HasFP;
1189 if (GV->hasFnAttribute(Attribute::NoReturn))
1190 ProcFlags |= ProcSymFlags::IsNoReturn;
1191 if (GV->hasFnAttribute(Attribute::NoInline))
1192 ProcFlags |= ProcSymFlags::IsNoInline;
1193 OS.emitInt8(static_cast<uint8_t>(ProcFlags));
1194 // Emit the function display name as a null-terminated string.
1195 OS.AddComment("Function name");
1196 // Truncate the name so we won't overflow the record length field.
1197 emitNullTerminatedSymbolName(OS, FuncName);
1198 endSymbolRecord(ProcRecordEnd);
1199
1200 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1201 // Subtract out the CSR size since MSVC excludes that and we include it.
1202 OS.AddComment("FrameSize");
1203 OS.emitInt32(FI.FrameSize - FI.CSRSize);
1204 OS.AddComment("Padding");
1205 OS.emitInt32(0);
1206 OS.AddComment("Offset of padding");
1207 OS.emitInt32(0);
1208 OS.AddComment("Bytes of callee saved registers");
1209 OS.emitInt32(FI.CSRSize);
1210 OS.AddComment("Exception handler offset");
1211 OS.emitInt32(0);
1212 OS.AddComment("Exception handler section");
1213 OS.emitInt16(0);
1214 OS.AddComment("Flags (defines frame register)");
1215 OS.emitInt32(uint32_t(FI.FrameProcOpts));
1216 endSymbolRecord(FrameProcEnd);
1217
1218 emitInlinees(FI.Inlinees);
1219 emitLocalVariableList(FI, FI.Locals);
1220 emitGlobalVariableList(FI.Globals);
1221 emitLexicalBlockList(FI.ChildBlocks, FI);
1222
1223 // Emit inlined call site information. Only emit functions inlined directly
1224 // into the parent function. We'll emit the other sites recursively as part
1225 // of their parent inline site.
1226 for (const DILocation *InlinedAt : FI.ChildSites) {
1227 auto I = FI.InlineSites.find(InlinedAt);
1228 assert(I != FI.InlineSites.end() &&
1229 "child site not in function inline site map");
1230 emitInlinedCallSite(FI, InlinedAt, I->second);
1231 }
1232
1233 for (auto Annot : FI.Annotations) {
1234 MCSymbol *Label = Annot.first;
1235 MDTuple *Strs = cast<MDTuple>(Annot.second);
1236 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1237 OS.emitCOFFSecRel32(Label, /*Offset=*/0);
1238 // FIXME: Make sure we don't overflow the max record size.
1239 OS.emitCOFFSectionIndex(Label);
1240 OS.emitInt16(Strs->getNumOperands());
1241 for (Metadata *MD : Strs->operands()) {
1242 // MDStrings are null terminated, so we can do EmitBytes and get the
1243 // nice .asciz directive.
1244 StringRef Str = cast<MDString>(MD)->getString();
1245 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1246 OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
1247 }
1248 endSymbolRecord(AnnotEnd);
1249 }
1250
1251 for (auto HeapAllocSite : FI.HeapAllocSites) {
1252 const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1253 const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1254 const DIType *DITy = std::get<2>(HeapAllocSite);
1255 MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1256 OS.AddComment("Call site offset");
1257 OS.emitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1258 OS.AddComment("Call site section index");
1259 OS.emitCOFFSectionIndex(BeginLabel);
1260 OS.AddComment("Call instruction length");
1261 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1262 OS.AddComment("Type index");
1263 OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
1264 endSymbolRecord(HeapAllocEnd);
1265 }
1266
1267 if (SP != nullptr)
1268 emitDebugInfoForUDTs(LocalUDTs);
1269
1270 emitDebugInfoForJumpTables(FI);
1271
1272 // We're done with this function.
1273 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1274 }
1275 endCVSubsection(SymbolsEnd);
1276
1277 // We have an assembler directive that takes care of the whole line table.
1278 OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1279}
1280
1282CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset,
1283 int32_t DerefOffset) {
1284 LocalVarDef DR;
1285 DR.InMemory = -1;
1286 DR.DataOffset = Offset;
1287 assert(DR.DataOffset == Offset && "truncation");
1288 DR.IsSubfield = 0;
1289 DR.StructOffset = 0;
1290 DR.CVRegister = CVRegister;
1291 DR.DerefOffset = DerefOffset;
1292 return DR;
1293}
1294
1295void CodeViewDebug::collectVariableInfoFromMFTable(
1296 DenseSet<InlinedEntity> &Processed) {
1297 const MachineFunction &MF = *Asm->MF;
1298 const TargetSubtargetInfo &TSI = MF.getSubtarget();
1299 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1300 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1301
1302 for (const MachineFunction::VariableDbgInfo &VI :
1304 if (!VI.Var)
1305 continue;
1306 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1307 "Expected inlined-at fields to agree");
1308
1309 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1310 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1311
1312 // If variable scope is not found then skip this variable.
1313 if (!Scope)
1314 continue;
1315
1316 // If the variable has an attached offset expression, extract it.
1317 int64_t ExprOffset = 0;
1318 int64_t DerefOffset = LocalVarDef::NoDeref;
1319 if (VI.Expr) {
1320 SmallVector<uint64_t, 2> FirstRemaining;
1321 if (!VI.Expr->extractLeadingOffset(ExprOffset, FirstRemaining))
1322 continue;
1323 if (!FirstRemaining.empty()) {
1324 if (FirstRemaining.front() != dwarf::DW_OP_deref)
1325 continue;
1326 SmallVector<uint64_t, 1> LastRemaining;
1328 ArrayRef(FirstRemaining).drop_front(), DerefOffset,
1329 LastRemaining))
1330 continue;
1331 if (!LastRemaining.empty())
1332 continue;
1333 }
1334 }
1335
1336 // Get the frame register used and the offset.
1337 Register FrameReg;
1338 StackOffset FrameOffset =
1339 TFI->getFrameIndexReference(*Asm->MF, VI.getStackSlot(), FrameReg);
1340 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1341
1342 if (FrameOffset.getScalable()) {
1343 // No encoding currently exists for scalable offsets; bail out.
1344 continue;
1345 }
1346 if (DerefOffset < INT32_MIN || DerefOffset > INT32_MAX)
1347 continue;
1348
1349 // Calculate the label ranges.
1350 LocalVarDef DefRange =
1351 createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset,
1352 static_cast<int32_t>(DerefOffset));
1353
1354 LocalVariable Var;
1355 Var.DIVar = VI.Var;
1356
1357 for (const InsnRange &Range : Scope->getRanges()) {
1358 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1359 const MCSymbol *End = getLabelAfterInsn(Range.second);
1360 End = End ? End : Asm->getFunctionEnd();
1361 Var.DefRanges[DefRange].emplace_back(Begin, End);
1362 }
1363
1364 recordLocalVariable(std::move(Var), Scope);
1365 }
1366}
1367
1368void CodeViewDebug::calculateRanges(
1369 LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1370 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1371
1372 // Calculate the definition ranges.
1373 for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1374 const auto &Entry = *I;
1375 if (!Entry.isDbgValue())
1376 continue;
1377 const MachineInstr *DVInst = Entry.getInstr();
1378 assert(DVInst->isDebugValue() && "Invalid History entry");
1379 // FIXME: Find a way to represent constant variables, since they are
1380 // relatively common.
1381 std::optional<DbgVariableLocation> Location =
1383 if (!Location)
1384 {
1385 // When we don't have a location this is usually because LLVM has
1386 // transformed it into a constant and we only have an llvm.dbg.value. We
1387 // can't represent these well in CodeView since S_LOCAL only works on
1388 // registers and memory locations. Instead, we will pretend this to be a
1389 // constant value to at least have it show up in the debugger.
1390 auto Op = DVInst->getDebugOperand(0);
1391 if (Op.isImm())
1392 Var.ConstantValue = APSInt(APInt(64, Op.getImm()), false);
1393 continue;
1394 }
1395
1396 // We can only handle a register, an offsetted load of a register, or an
1397 // indirect offsetted load.
1398 if (!Location->Register || Location->LoadChain.size() > 2)
1399 continue;
1400
1401 // Codeview can only express byte-aligned offsets, ensure that we have a
1402 // byte-boundaried location.
1403 if (Location->FragmentInfo)
1404 if (Location->FragmentInfo->OffsetInBits % 8)
1405 continue;
1406
1407 if (TRI->isIgnoredCVReg(Location->Register)) {
1408 // No encoding currently exists for this register; bail out.
1409 continue;
1410 }
1411
1412 LocalVarDef DR;
1413 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1414 DR.InMemory = !Location->LoadChain.empty();
1415 DR.DataOffset = 0;
1416 DR.DerefOffset = LocalVarDef::NoDeref;
1417 if (!Location->LoadChain.empty()) {
1418 DR.DataOffset = Location->LoadChain[0];
1419 if (Location->LoadChain.size() >= 2)
1420 DR.DerefOffset = Location->LoadChain[1];
1421 }
1422 if (Location->FragmentInfo) {
1423 DR.IsSubfield = true;
1424 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1425 } else {
1426 DR.IsSubfield = false;
1427 DR.StructOffset = 0;
1428 }
1429
1430 // Compute the label range.
1431 const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1432 const MCSymbol *End;
1433 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1434 auto &EndingEntry = Entries[Entry.getEndIndex()];
1435 End = EndingEntry.isDbgValue()
1436 ? getLabelBeforeInsn(EndingEntry.getInstr())
1437 : getLabelAfterInsn(EndingEntry.getInstr());
1438 } else
1439 End = Asm->getFunctionEnd();
1440
1441 // If the last range end is our begin, just extend the last range.
1442 // Otherwise make a new range.
1443 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1444 Var.DefRanges[DR];
1445 if (!R.empty() && R.back().second == Begin)
1446 R.back().second = End;
1447 else
1448 R.emplace_back(Begin, End);
1449
1450 // FIXME: Do more range combining.
1451 }
1452}
1453
1454void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1455 DenseSet<InlinedEntity> Processed;
1456 // Grab the variable info that was squirreled away in the MMI side-table.
1457 collectVariableInfoFromMFTable(Processed);
1458
1459 for (const MDNode *N : SP->getRetainedNodes())
1460 if (const auto *GVE = dyn_cast<DIGlobalVariableExpression>(N))
1461 collectGlobalOrStaticLocalVariableInfo(GVE);
1462
1463 for (const auto &I : DbgValues) {
1464 InlinedEntity IV = I.first;
1465 if (Processed.count(IV))
1466 continue;
1467 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1468 const DILocation *InlinedAt = IV.second;
1469
1470 // Instruction ranges, specifying where IV is accessible.
1471 const auto &Entries = I.second;
1472
1473 LexicalScope *Scope = nullptr;
1474 if (InlinedAt)
1475 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1476 else
1477 Scope = LScopes.findLexicalScope(DIVar->getScope());
1478 // If variable scope is not found then skip this variable.
1479 if (!Scope)
1480 continue;
1481
1482 LocalVariable Var;
1483 Var.DIVar = DIVar;
1484
1485 calculateRanges(Var, Entries);
1486 recordLocalVariable(std::move(Var), Scope);
1487 }
1488}
1489
1491 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1492 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1493 const MachineFrameInfo &MFI = MF->getFrameInfo();
1494 const Function &GV = MF->getFunction();
1495 auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1496 assert(Insertion.second && "function already has info");
1497 CurFn = Insertion.first->second.get();
1498 CurFn->FuncId = NextFuncId++;
1499 CurFn->Begin = Asm->getFunctionBegin();
1500
1501 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1502 // callee-saved registers were used. For targets that don't use a PUSH
1503 // instruction (AArch64), this will be zero.
1504 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1505 CurFn->FrameSize = MFI.getStackSize();
1506 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1507 CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
1508
1509 // For this function S_FRAMEPROC record, figure out which codeview register
1510 // will be the frame pointer.
1511 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1512 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1513 if (CurFn->FrameSize > 0) {
1514 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1515 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1516 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1517 } else {
1518 CurFn->HasFramePointer = true;
1519 // If there is an FP, parameters are always relative to it.
1520 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1521 if (CurFn->HasStackRealignment) {
1522 // If the stack needs realignment, locals are relative to SP or VFRAME.
1523 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1524 } else {
1525 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1526 // other stack adjustments.
1527 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1528 }
1529 }
1530 }
1531
1532 // Compute other frame procedure options.
1534 if (MFI.hasVarSizedObjects())
1536 if (MF->exposesReturnsTwice())
1538 // FIXME: Set HasLongJmp if we ever track that info.
1539 if (MF->hasInlineAsm())
1541 if (GV.hasPersonalityFn()) {
1545 else
1547 }
1548 if (GV.hasFnAttribute(Attribute::InlineHint))
1550 if (GV.hasFnAttribute(Attribute::Naked))
1552 if (MFI.hasStackProtectorIndex()) {
1554 if (GV.hasFnAttribute(Attribute::StackProtectStrong) ||
1555 GV.hasFnAttribute(Attribute::StackProtectReq)) {
1557 }
1558 } else if (!GV.hasStackProtectorFnAttr()) {
1559 // __declspec(safebuffers) disables stack guards.
1561 }
1562 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1563 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1564 if (Asm->TM.getOptLevel() != CodeGenOptLevel::None && !GV.hasOptSize() &&
1565 !GV.hasOptNone())
1567 if (GV.hasProfileData()) {
1570 }
1571 // FIXME: Set GuardCfg when it is implemented.
1572 CurFn->FrameProcOpts = FPO;
1573
1574 OS.emitCVFuncIdDirective(CurFn->FuncId);
1575
1576 // Find the end of the function prolog. First known non-DBG_VALUE and
1577 // non-frame setup location marks the beginning of the function body.
1578 // FIXME: is there a simpler a way to do this? Can we just search
1579 // for the first instruction of the function, not the last of the prolog?
1581 bool EmptyPrologue = true;
1582 for (const auto &MBB : *MF) {
1583 for (const auto &MI : MBB) {
1584 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1585 MI.getDebugLoc()) {
1586 PrologEndLoc = MI.getDebugLoc();
1587 break;
1588 } else if (!MI.isMetaInstruction()) {
1589 EmptyPrologue = false;
1590 }
1591 }
1592 }
1593
1594 // Record beginning of function if we have a non-empty prologue.
1595 if (PrologEndLoc && !EmptyPrologue) {
1596 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1597 maybeRecordLocation(FnStartDL, MF);
1598 }
1599
1600 // Find heap alloc sites and emit labels around them.
1601 for (const auto &MBB : *MF) {
1602 for (const auto &MI : MBB) {
1603 if (MI.getHeapAllocMarker()) {
1606 }
1607 }
1608 }
1609
1610 // Mark branches that may potentially be using jump tables with labels.
1611 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
1613 discoverJumpTableBranches(MF, isThumb);
1614}
1615
1616static bool shouldEmitUdt(const DIType *T) {
1617 if (!T)
1618 return false;
1619
1620 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1621 if (T->getTag() == dwarf::DW_TAG_typedef) {
1622 if (DIScope *Scope = T->getScope()) {
1623 switch (Scope->getTag()) {
1624 case dwarf::DW_TAG_structure_type:
1625 case dwarf::DW_TAG_class_type:
1626 case dwarf::DW_TAG_union_type:
1627 return false;
1628 default:
1629 // do nothing.
1630 ;
1631 }
1632 }
1633 }
1634
1635 while (true) {
1636 if (!T || T->isForwardDecl())
1637 return false;
1638
1640 if (!DT)
1641 return true;
1642 T = DT->getBaseType();
1643 }
1644 return true;
1645}
1646
1647void CodeViewDebug::addToUDTs(const DIType *Ty) {
1648 // Don't record empty UDTs.
1649 if (Ty->getName().empty())
1650 return;
1651 if (!shouldEmitUdt(Ty))
1652 return;
1653
1654 SmallVector<StringRef, 5> ParentScopeNames;
1655 const DISubprogram *ClosestSubprogram =
1656 collectParentScopeNames(Ty->getScope(), ParentScopeNames);
1657
1658 std::string FullyQualifiedName =
1659 formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
1660
1661 if (ClosestSubprogram == nullptr) {
1662 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1663 } else if (ClosestSubprogram == CurrentSubprogram) {
1664 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1665 }
1666
1667 // TODO: What if the ClosestSubprogram is neither null or the current
1668 // subprogram? Currently, the UDT just gets dropped on the floor.
1669 //
1670 // The current behavior is not desirable. To get maximal fidelity, we would
1671 // need to perform all type translation before beginning emission of .debug$S
1672 // and then make LocalUDTs a member of FunctionInfo
1673}
1674
1675TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1676 // Generic dispatch for lowering an unknown type.
1677 switch (Ty->getTag()) {
1678 case dwarf::DW_TAG_array_type:
1679 return lowerTypeArray(cast<DICompositeType>(Ty));
1680 case dwarf::DW_TAG_typedef:
1681 return lowerTypeAlias(cast<DIDerivedType>(Ty));
1682 case dwarf::DW_TAG_base_type:
1683 return lowerTypeBasic(cast<DIBasicType>(Ty));
1684 case dwarf::DW_TAG_pointer_type:
1685 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1686 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1687 [[fallthrough]];
1688 case dwarf::DW_TAG_reference_type:
1689 case dwarf::DW_TAG_rvalue_reference_type:
1690 return lowerTypePointer(cast<DIDerivedType>(Ty));
1691 case dwarf::DW_TAG_ptr_to_member_type:
1692 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1693 case dwarf::DW_TAG_restrict_type:
1694 case dwarf::DW_TAG_const_type:
1695 case dwarf::DW_TAG_volatile_type:
1696 // TODO: add support for DW_TAG_atomic_type here
1697 return lowerTypeModifier(cast<DIDerivedType>(Ty));
1698 case dwarf::DW_TAG_subroutine_type:
1699 if (ClassTy) {
1700 // The member function type of a member function pointer has no
1701 // ThisAdjustment.
1702 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1703 /*ThisAdjustment=*/0,
1704 /*IsStaticMethod=*/false);
1705 }
1706 return lowerTypeFunction(cast<DISubroutineType>(Ty));
1707 case dwarf::DW_TAG_enumeration_type:
1708 return lowerTypeEnum(cast<DICompositeType>(Ty));
1709 case dwarf::DW_TAG_class_type:
1710 case dwarf::DW_TAG_structure_type:
1711 return lowerTypeClass(cast<DICompositeType>(Ty));
1712 case dwarf::DW_TAG_union_type:
1713 return lowerTypeUnion(cast<DICompositeType>(Ty));
1714 case dwarf::DW_TAG_string_type:
1715 return lowerTypeString(cast<DIStringType>(Ty));
1716 case dwarf::DW_TAG_unspecified_type:
1717 if (Ty->getName() == "decltype(nullptr)")
1718 return TypeIndex::NullptrT();
1719 return TypeIndex::None();
1720 default:
1721 // Use the null type index.
1722 return TypeIndex();
1723 }
1724}
1725
1726TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1727 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1728 StringRef TypeName = Ty->getName();
1729
1730 addToUDTs(Ty);
1731
1732 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1733 TypeName == "HRESULT")
1734 return TypeIndex(SimpleTypeKind::HResult);
1735 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1736 TypeName == "wchar_t")
1737 return TypeIndex(SimpleTypeKind::WideCharacter);
1738
1739 return UnderlyingTypeIndex;
1740}
1741
1742TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1743 const DIType *ElementType = Ty->getBaseType();
1744 TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1745 // IndexType is size_t, which depends on the bitness of the target.
1746 TypeIndex IndexType = getPointerSizeInBytes() == 8
1747 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1748 : TypeIndex(SimpleTypeKind::UInt32Long);
1749
1750 uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1751
1752 // Add subranges to array type.
1753 DINodeArray Elements = Ty->getElements();
1754 for (int i = Elements.size() - 1; i >= 0; --i) {
1755 const DINode *Element = Elements[i];
1756 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1757
1758 const DISubrange *Subrange = cast<DISubrange>(Element);
1759 int64_t Count = -1;
1760
1761 // If Subrange has a Count field, use it.
1762 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1763 // where lowerbound is from the LowerBound field of the Subrange,
1764 // or the language default lowerbound if that field is unspecified.
1765 if (auto *CI = dyn_cast_if_present<ConstantInt *>(Subrange->getCount()))
1766 Count = CI->getSExtValue();
1767 else if (auto *UI = dyn_cast_if_present<ConstantInt *>(
1768 Subrange->getUpperBound())) {
1769 // Fortran uses 1 as the default lowerbound; other languages use 0.
1770 int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
1771 auto *LI = dyn_cast_if_present<ConstantInt *>(Subrange->getLowerBound());
1772 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1773 Count = UI->getSExtValue() - Lowerbound + 1;
1774 }
1775
1776 // Forward declarations of arrays without a size and VLAs use a count of -1.
1777 // Emit a count of zero in these cases to match what MSVC does for arrays
1778 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1779 // should do for them even if we could distinguish them.
1780 if (Count == -1)
1781 Count = 0;
1782
1783 // Update the element size and element type index for subsequent subranges.
1784 ElementSize *= Count;
1785
1786 // If this is the outermost array, use the size from the array. It will be
1787 // more accurate if we had a VLA or an incomplete element type size.
1788 uint64_t ArraySize =
1789 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1790
1791 StringRef Name = (i == 0) ? Ty->getName() : "";
1792 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1793 ElementTypeIndex = TypeTable.writeLeafType(AR);
1794 }
1795
1796 return ElementTypeIndex;
1797}
1798
1799// This function lowers a Fortran character type (DIStringType).
1800// Note that it handles only the character*n variant (using SizeInBits
1801// field in DIString to describe the type size) at the moment.
1802// Other variants (leveraging the StringLength and StringLengthExp
1803// fields in DIStringType) remain TBD.
1804TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1805 TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1806 uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1807 StringRef Name = Ty->getName();
1808 // IndexType is size_t, which depends on the bitness of the target.
1809 TypeIndex IndexType = getPointerSizeInBytes() == 8
1810 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1811 : TypeIndex(SimpleTypeKind::UInt32Long);
1812
1813 // Create a type of character array of ArraySize.
1814 ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1815
1816 return TypeTable.writeLeafType(AR);
1817}
1818
1819TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1820 TypeIndex Index;
1822 uint32_t ByteSize;
1823
1824 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1825 ByteSize = Ty->getSizeInBits() / 8;
1826
1827 SimpleTypeKind STK = SimpleTypeKind::None;
1828 switch (Kind) {
1829 case dwarf::DW_ATE_address:
1830 // FIXME: Translate
1831 break;
1832 case dwarf::DW_ATE_boolean:
1833 switch (ByteSize) {
1834 case 1: STK = SimpleTypeKind::Boolean8; break;
1835 case 2: STK = SimpleTypeKind::Boolean16; break;
1836 case 4: STK = SimpleTypeKind::Boolean32; break;
1837 case 8: STK = SimpleTypeKind::Boolean64; break;
1838 case 16: STK = SimpleTypeKind::Boolean128; break;
1839 }
1840 break;
1841 case dwarf::DW_ATE_complex_float:
1842 // The CodeView size for a complex represents the size of
1843 // an individual component.
1844 switch (ByteSize) {
1845 case 4: STK = SimpleTypeKind::Complex16; break;
1846 case 8: STK = SimpleTypeKind::Complex32; break;
1847 case 16: STK = SimpleTypeKind::Complex64; break;
1848 case 20: STK = SimpleTypeKind::Complex80; break;
1849 case 32: STK = SimpleTypeKind::Complex128; break;
1850 }
1851 break;
1852 case dwarf::DW_ATE_float:
1853 switch (ByteSize) {
1854 case 2: STK = SimpleTypeKind::Float16; break;
1855 case 4: STK = SimpleTypeKind::Float32; break;
1856 case 6: STK = SimpleTypeKind::Float48; break;
1857 case 8: STK = SimpleTypeKind::Float64; break;
1858 case 10: STK = SimpleTypeKind::Float80; break;
1859 case 16: STK = SimpleTypeKind::Float128; break;
1860 }
1861 break;
1862 case dwarf::DW_ATE_signed:
1863 switch (ByteSize) {
1864 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1865 case 2: STK = SimpleTypeKind::Int16Short; break;
1866 case 4: STK = SimpleTypeKind::Int32; break;
1867 case 8: STK = SimpleTypeKind::Int64Quad; break;
1868 case 16: STK = SimpleTypeKind::Int128Oct; break;
1869 }
1870 break;
1871 case dwarf::DW_ATE_unsigned:
1872 switch (ByteSize) {
1873 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1874 case 2: STK = SimpleTypeKind::UInt16Short; break;
1875 case 4: STK = SimpleTypeKind::UInt32; break;
1876 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1877 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1878 }
1879 break;
1880 case dwarf::DW_ATE_UTF:
1881 switch (ByteSize) {
1882 case 1: STK = SimpleTypeKind::Character8; break;
1883 case 2: STK = SimpleTypeKind::Character16; break;
1884 case 4: STK = SimpleTypeKind::Character32; break;
1885 }
1886 break;
1887 case dwarf::DW_ATE_signed_char:
1888 if (ByteSize == 1)
1889 STK = SimpleTypeKind::SignedCharacter;
1890 break;
1891 case dwarf::DW_ATE_unsigned_char:
1892 if (ByteSize == 1)
1893 STK = SimpleTypeKind::UnsignedCharacter;
1894 break;
1895 default:
1896 break;
1897 }
1898
1899 // Apply some fixups based on the source-level type name.
1900 // Include some amount of canonicalization from an old naming scheme Clang
1901 // used to use for integer types (in an outdated effort to be compatible with
1902 // GCC's debug info/GDB's behavior, which has since been addressed).
1903 if (STK == SimpleTypeKind::Int32 &&
1904 (Ty->getName() == "long int" || Ty->getName() == "long"))
1905 STK = SimpleTypeKind::Int32Long;
1906 if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1907 Ty->getName() == "unsigned long"))
1908 STK = SimpleTypeKind::UInt32Long;
1909 if (STK == SimpleTypeKind::UInt16Short &&
1910 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1911 STK = SimpleTypeKind::WideCharacter;
1912 if ((STK == SimpleTypeKind::SignedCharacter ||
1913 STK == SimpleTypeKind::UnsignedCharacter) &&
1914 Ty->getName() == "char")
1915 STK = SimpleTypeKind::NarrowCharacter;
1916
1917 return TypeIndex(STK);
1918}
1919
1920TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1921 PointerOptions PO) {
1922 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1923
1924 // Pointers to simple types without any options can use SimpleTypeMode, rather
1925 // than having a dedicated pointer type record.
1926 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1927 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1928 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1929 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1930 ? SimpleTypeMode::NearPointer64
1931 : SimpleTypeMode::NearPointer32;
1932 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1933 }
1934
1935 PointerKind PK =
1936 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1937 PointerMode PM = PointerMode::Pointer;
1938 switch (Ty->getTag()) {
1939 default: llvm_unreachable("not a pointer tag type");
1940 case dwarf::DW_TAG_pointer_type:
1941 PM = PointerMode::Pointer;
1942 break;
1943 case dwarf::DW_TAG_reference_type:
1944 PM = PointerMode::LValueReference;
1945 break;
1946 case dwarf::DW_TAG_rvalue_reference_type:
1947 PM = PointerMode::RValueReference;
1948 break;
1949 }
1950
1951 if (Ty->isObjectPointer())
1952 PO |= PointerOptions::Const;
1953
1954 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1955 return TypeTable.writeLeafType(PR);
1956}
1957
1959translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1960 // SizeInBytes being zero generally implies that the member pointer type was
1961 // incomplete, which can happen if it is part of a function prototype. In this
1962 // case, use the unknown model instead of the general model.
1963 if (IsPMF) {
1964 switch (Flags & DINode::FlagPtrToMemberRep) {
1965 case 0:
1966 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1968 case DINode::FlagSingleInheritance:
1970 case DINode::FlagMultipleInheritance:
1972 case DINode::FlagVirtualInheritance:
1974 }
1975 } else {
1976 switch (Flags & DINode::FlagPtrToMemberRep) {
1977 case 0:
1978 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1980 case DINode::FlagSingleInheritance:
1982 case DINode::FlagMultipleInheritance:
1984 case DINode::FlagVirtualInheritance:
1986 }
1987 }
1988 llvm_unreachable("invalid ptr to member representation");
1989}
1990
1991TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1992 PointerOptions PO) {
1993 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1994 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1995 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1996 TypeIndex PointeeTI =
1997 getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
1998 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1999 : PointerKind::Near32;
2000 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
2001 : PointerMode::PointerToDataMember;
2002
2003 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
2004 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
2005 MemberPointerInfo MPI(
2006 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
2007 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
2008 return TypeTable.writeLeafType(PR);
2009}
2010
2011/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
2012/// have a translation, use the NearC convention.
2013static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
2014 switch (DwarfCC) {
2015 case dwarf::DW_CC_normal: return CallingConvention::NearC;
2016 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
2017 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
2018 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
2019 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
2020 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
2021 }
2023}
2024
2025TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
2026 ModifierOptions Mods = ModifierOptions::None;
2027 PointerOptions PO = PointerOptions::None;
2028 bool IsModifier = true;
2029 const DIType *BaseTy = Ty;
2030 while (IsModifier && BaseTy) {
2031 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
2032 switch (BaseTy->getTag()) {
2033 case dwarf::DW_TAG_const_type:
2034 Mods |= ModifierOptions::Const;
2035 PO |= PointerOptions::Const;
2036 break;
2037 case dwarf::DW_TAG_volatile_type:
2038 Mods |= ModifierOptions::Volatile;
2039 PO |= PointerOptions::Volatile;
2040 break;
2041 case dwarf::DW_TAG_restrict_type:
2042 // Only pointer types be marked with __restrict. There is no known flag
2043 // for __restrict in LF_MODIFIER records.
2044 PO |= PointerOptions::Restrict;
2045 break;
2046 default:
2047 IsModifier = false;
2048 break;
2049 }
2050 if (IsModifier)
2051 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
2052 }
2053
2054 // Check if the inner type will use an LF_POINTER record. If so, the
2055 // qualifiers will go in the LF_POINTER record. This comes up for types like
2056 // 'int *const' and 'int *__restrict', not the more common cases like 'const
2057 // char *'.
2058 if (BaseTy) {
2059 switch (BaseTy->getTag()) {
2060 case dwarf::DW_TAG_pointer_type:
2061 case dwarf::DW_TAG_reference_type:
2062 case dwarf::DW_TAG_rvalue_reference_type:
2063 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
2064 case dwarf::DW_TAG_ptr_to_member_type:
2065 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
2066 default:
2067 break;
2068 }
2069 }
2070
2071 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
2072
2073 // Return the base type index if there aren't any modifiers. For example, the
2074 // metadata could contain restrict wrappers around non-pointer types.
2075 if (Mods == ModifierOptions::None)
2076 return ModifiedTI;
2077
2078 ModifierRecord MR(ModifiedTI, Mods);
2079 return TypeTable.writeLeafType(MR);
2080}
2081
2082TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
2083 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
2084 for (const DIType *ArgType : Ty->getTypeArray())
2085 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
2086
2087 // MSVC uses type none for variadic argument.
2088 if (ReturnAndArgTypeIndices.size() > 1 &&
2089 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
2090 ReturnAndArgTypeIndices.back() = TypeIndex::None();
2091 }
2092 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2093 ArrayRef<TypeIndex> ArgTypeIndices = {};
2094 if (!ReturnAndArgTypeIndices.empty()) {
2095 auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices);
2096 ReturnTypeIndex = ReturnAndArgTypesRef.consume_front();
2097 ArgTypeIndices = ReturnAndArgTypesRef;
2098 }
2099
2100 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2101 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2102
2104
2106 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
2107 ArgListIndex);
2108 return TypeTable.writeLeafType(Procedure);
2109}
2110
2111TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
2112 const DIType *ClassTy,
2113 int ThisAdjustment,
2114 bool IsStaticMethod,
2115 FunctionOptions FO) {
2116 // Lower the containing class type.
2117 TypeIndex ClassType = getTypeIndex(ClassTy);
2118
2119 DITypeArray ReturnAndArgs = Ty->getTypeArray();
2120
2121 unsigned Index = 0;
2122 SmallVector<TypeIndex, 8> ArgTypeIndices;
2123 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2124 if (ReturnAndArgs.size() > Index) {
2125 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
2126 }
2127
2128 // If the first argument is a pointer type and this isn't a static method,
2129 // treat it as the special 'this' parameter, which is encoded separately from
2130 // the arguments.
2131 TypeIndex ThisTypeIndex;
2132 if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
2133 if (const DIDerivedType *PtrTy =
2134 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
2135 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2136 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
2137 Index++;
2138 }
2139 }
2140 }
2141
2142 while (Index < ReturnAndArgs.size())
2143 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
2144
2145 // MSVC uses type none for variadic argument.
2146 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
2147 ArgTypeIndices.back() = TypeIndex::None();
2148
2149 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2150 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2151
2153
2154 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
2155 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
2156 return TypeTable.writeLeafType(MFR);
2157}
2158
2159TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
2160 unsigned VSlotCount =
2161 Ty->getSizeInBits() / (8 * Asm->MAI.getCodePointerSize());
2162 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
2163
2164 VFTableShapeRecord VFTSR(Slots);
2165 return TypeTable.writeLeafType(VFTSR);
2166}
2167
2168static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
2169 switch (Flags & DINode::FlagAccessibility) {
2170 case DINode::FlagPrivate: return MemberAccess::Private;
2171 case DINode::FlagPublic: return MemberAccess::Public;
2172 case DINode::FlagProtected: return MemberAccess::Protected;
2173 case 0:
2174 // If there was no explicit access control, provide the default for the tag.
2175 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2177 }
2178 llvm_unreachable("access flags are exclusive");
2179}
2180
2182 if (SP->isArtificial())
2184
2185 // FIXME: Handle other MethodOptions.
2186
2187 return MethodOptions::None;
2188}
2189
2191 bool Introduced) {
2192 if (SP->getFlags() & DINode::FlagStaticMember)
2193 return MethodKind::Static;
2194
2195 switch (SP->getVirtuality()) {
2196 case dwarf::DW_VIRTUALITY_none:
2197 break;
2198 case dwarf::DW_VIRTUALITY_virtual:
2200 case dwarf::DW_VIRTUALITY_pure_virtual:
2201 return Introduced ? MethodKind::PureIntroducingVirtual
2203 default:
2204 llvm_unreachable("unhandled virtuality case");
2205 }
2206
2207 return MethodKind::Vanilla;
2208}
2209
2211 switch (Ty->getTag()) {
2212 case dwarf::DW_TAG_class_type:
2213 return TypeRecordKind::Class;
2214 case dwarf::DW_TAG_structure_type:
2215 return TypeRecordKind::Struct;
2216 default:
2217 llvm_unreachable("unexpected tag");
2218 }
2219}
2220
2221/// Return ClassOptions that should be present on both the forward declaration
2222/// and the defintion of a tag type.
2225
2226 // MSVC always sets this flag, even for local types. Clang doesn't always
2227 // appear to give every type a linkage name, which may be problematic for us.
2228 // FIXME: Investigate the consequences of not following them here.
2229 if (!Ty->getIdentifier().empty())
2231
2232 // Put the Nested flag on a type if it appears immediately inside a tag type.
2233 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2234 // here. That flag is only set on definitions, and not forward declarations.
2235 const DIScope *ImmediateScope = Ty->getScope();
2236 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2238
2239 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2240 // type only when it has an immediate function scope. Clang never puts enums
2241 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2242 // always in function, class, or file scopes.
2243 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2244 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2246 } else {
2247 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2248 Scope = Scope->getScope()) {
2249 if (isa<DISubprogram>(Scope)) {
2251 break;
2252 }
2253 }
2254 }
2255
2256 return CO;
2257}
2258
2259void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2260 switch (Ty->getTag()) {
2261 case dwarf::DW_TAG_class_type:
2262 case dwarf::DW_TAG_structure_type:
2263 case dwarf::DW_TAG_union_type:
2264 case dwarf::DW_TAG_enumeration_type:
2265 break;
2266 default:
2267 return;
2268 }
2269
2270 if (const auto *File = Ty->getFile()) {
2271 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2272 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2273
2274 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2275 TypeTable.writeLeafType(USLR);
2276 }
2277}
2278
2279TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2281 TypeIndex FTI;
2282 unsigned EnumeratorCount = 0;
2283
2284 if (Ty->isForwardDecl()) {
2285 CO |= ClassOptions::ForwardReference;
2286 } else {
2287 ContinuationRecordBuilder ContinuationBuilder;
2288 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2289 for (const DINode *Element : Ty->getElements()) {
2290 // We assume that the frontend provides all members in source declaration
2291 // order, which is what MSVC does.
2292 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2293 EnumeratorRecord ER(
2294 MemberAccess::Public,
2295 APSInt(Enumerator->getValue(), Enumerator->isUnsigned()),
2296 Enumerator->getName());
2297 ContinuationBuilder.writeMemberType(ER);
2298 EnumeratorCount++;
2299 }
2300 }
2301 FTI = TypeTable.insertRecord(ContinuationBuilder);
2302 }
2303
2304 std::string FullName = getFullyQualifiedName(Ty);
2305
2306 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2307 getTypeIndex(Ty->getBaseType()));
2308 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2309
2310 addUDTSrcLine(Ty, EnumTI);
2311
2312 return EnumTI;
2313}
2314
2315//===----------------------------------------------------------------------===//
2316// ClassInfo
2317//===----------------------------------------------------------------------===//
2318
2324 // [MemberInfo]
2325 using MemberList = std::vector<MemberInfo>;
2326
2328 // MethodName -> MethodsList
2330
2331 /// Base classes.
2332 std::vector<const DIDerivedType *> Inheritance;
2333
2334 /// Direct members.
2336 // Direct overloaded methods gathered by name.
2338
2340
2341 std::vector<const DIType *> NestedTypes;
2342};
2343
2344void CodeViewDebug::clear() {
2345 assert(CurFn == nullptr);
2346 FileIdMap.clear();
2347 FnDebugInfo.clear();
2348 FileToFilepathMap.clear();
2349 LocalUDTs.clear();
2350 GlobalUDTs.clear();
2351 TypeIndices.clear();
2352 CompleteTypeIndices.clear();
2353 ScopeGlobals.clear();
2354 CVGlobalVariableOffsets.clear();
2355}
2356
2357void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2358 const DIDerivedType *DDTy) {
2359 if (!DDTy->getName().empty()) {
2360 Info.Members.push_back({DDTy, 0});
2361
2362 // Collect static const data members with values.
2363 if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2364 DINode::FlagStaticMember) {
2365 if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2366 isa<ConstantFP>(DDTy->getConstant())))
2367 StaticConstMembers.push_back(DDTy);
2368 }
2369
2370 return;
2371 }
2372
2373 // An unnamed member may represent a nested struct or union. Attempt to
2374 // interpret the unnamed member as a DICompositeType possibly wrapped in
2375 // qualifier types. Add all the indirect fields to the current record if that
2376 // succeeds, and drop the member if that fails.
2377 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2379 const DIType *Ty = DDTy->getBaseType();
2380 bool FullyResolved = false;
2381 while (!FullyResolved) {
2382 switch (Ty->getTag()) {
2383 case dwarf::DW_TAG_const_type:
2384 case dwarf::DW_TAG_volatile_type:
2385 // FIXME: we should apply the qualifier types to the indirect fields
2386 // rather than dropping them.
2387 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2388 break;
2389 default:
2390 FullyResolved = true;
2391 break;
2392 }
2393 }
2394
2395 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2396 if (!DCTy)
2397 return;
2398
2399 ClassInfo NestedInfo = collectClassInfo(DCTy);
2400 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2401 Info.Members.push_back(
2402 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2403}
2404
2405ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2406 ClassInfo Info;
2407 // Add elements to structure type.
2408 DINodeArray Elements = Ty->getElements();
2409 for (auto *Element : Elements) {
2410 // We assume that the frontend provides all members in source declaration
2411 // order, which is what MSVC does.
2412 if (!Element)
2413 continue;
2414 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2415 Info.Methods[SP->getRawName()].push_back(SP);
2416 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2417 if (DDTy->getTag() == dwarf::DW_TAG_member) {
2418 collectMemberInfo(Info, DDTy);
2419 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2420 Info.Inheritance.push_back(DDTy);
2421 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2422 DDTy->getName() == "__vtbl_ptr_type") {
2423 Info.VShapeTI = getTypeIndex(DDTy);
2424 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2425 Info.NestedTypes.push_back(DDTy);
2426 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2427 // Ignore friend members. It appears that MSVC emitted info about
2428 // friends in the past, but modern versions do not.
2429 }
2430 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2431 Info.NestedTypes.push_back(Composite);
2432 }
2433 // Skip other unrecognized kinds of elements.
2434 }
2435 return Info;
2436}
2437
2439 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2440 // if a complete type should be emitted instead of a forward reference.
2441 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2442 !Ty->isForwardDecl();
2443}
2444
2445TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2446 // Emit the complete type for unnamed structs. C++ classes with methods
2447 // which have a circular reference back to the class type are expected to
2448 // be named by the front-end and should not be "unnamed". C unnamed
2449 // structs should not have circular references.
2451 // If this unnamed complete type is already in the process of being defined
2452 // then the description of the type is malformed and cannot be emitted
2453 // into CodeView correctly so report a fatal error.
2454 auto I = CompleteTypeIndices.find(Ty);
2455 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2456 report_fatal_error("cannot debug circular reference to unnamed type");
2457 return getCompleteTypeIndex(Ty);
2458 }
2459
2460 // First, construct the forward decl. Don't look into Ty to compute the
2461 // forward decl options, since it might not be available in all TUs.
2463 ClassOptions CO =
2464 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2465 std::string FullName = getFullyQualifiedName(Ty);
2466 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2467 FullName, Ty->getIdentifier());
2468 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2469 if (!Ty->isForwardDecl())
2470 DeferredCompleteTypes.push_back(Ty);
2471 return FwdDeclTI;
2472}
2473
2474TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2475 // Construct the field list and complete type record.
2478 TypeIndex FieldTI;
2479 TypeIndex VShapeTI;
2480 unsigned FieldCount;
2482 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2483 lowerRecordFieldList(Ty);
2484
2486 CO |= ClassOptions::ContainsNestedClass;
2487
2488 // MSVC appears to set this flag by searching any destructor or method with
2489 // FunctionOptions::Constructor among the emitted members. Clang AST has all
2490 // the members, however special member functions are not yet emitted into
2491 // debug information. For now checking a class's non-triviality seems enough.
2492 // FIXME: not true for a nested unnamed struct.
2493 if (isNonTrivial(Ty))
2494 CO |= ClassOptions::HasConstructorOrDestructor;
2495
2496 std::string FullName = getFullyQualifiedName(Ty);
2497
2498 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2499
2500 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2501 SizeInBytes, FullName, Ty->getIdentifier());
2502 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2503
2504 addUDTSrcLine(Ty, ClassTI);
2505
2506 addToUDTs(Ty);
2507
2508 return ClassTI;
2509}
2510
2511TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2512 // Emit the complete type for unnamed unions.
2514 return getCompleteTypeIndex(Ty);
2515
2516 ClassOptions CO =
2517 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2518 std::string FullName = getFullyQualifiedName(Ty);
2519 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2520 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2521 if (!Ty->isForwardDecl())
2522 DeferredCompleteTypes.push_back(Ty);
2523 return FwdDeclTI;
2524}
2525
2526TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2527 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2528 TypeIndex FieldTI;
2529 unsigned FieldCount;
2531 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2532 lowerRecordFieldList(Ty);
2533
2535 CO |= ClassOptions::ContainsNestedClass;
2536
2537 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2538 std::string FullName = getFullyQualifiedName(Ty);
2539
2540 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2541 Ty->getIdentifier());
2542 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2543
2544 addUDTSrcLine(Ty, UnionTI);
2545
2546 addToUDTs(Ty);
2547
2548 return UnionTI;
2549}
2550
2551std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2552CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2553 // Manually count members. MSVC appears to count everything that generates a
2554 // field list record. Each individual overload in a method overload group
2555 // contributes to this count, even though the overload group is a single field
2556 // list record.
2557 unsigned MemberCount = 0;
2558 ClassInfo Info = collectClassInfo(Ty);
2559 ContinuationRecordBuilder ContinuationBuilder;
2560 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2561
2562 // Create base classes.
2563 for (const DIDerivedType *I : Info.Inheritance) {
2564 if (I->getFlags() & DINode::FlagVirtual) {
2565 // Virtual base.
2566 unsigned VBPtrOffset = I->getVBPtrOffset();
2567 // FIXME: Despite the accessor name, the offset is really in bytes.
2568 unsigned VBTableIndex = I->getOffsetInBits() / 4;
2569 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2570 ? TypeRecordKind::IndirectVirtualBaseClass
2571 : TypeRecordKind::VirtualBaseClass;
2572 VirtualBaseClassRecord VBCR(
2573 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2574 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2575 VBTableIndex);
2576
2577 ContinuationBuilder.writeMemberType(VBCR);
2578 MemberCount++;
2579 } else {
2580 assert(I->getOffsetInBits() % 8 == 0 &&
2581 "bases must be on byte boundaries");
2582 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2583 getTypeIndex(I->getBaseType()),
2584 I->getOffsetInBits() / 8);
2585 ContinuationBuilder.writeMemberType(BCR);
2586 MemberCount++;
2587 }
2588 }
2589
2590 // Create members.
2591 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2592 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2593 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2594 StringRef MemberName = Member->getName();
2596 translateAccessFlags(Ty->getTag(), Member->getFlags());
2597
2598 if (Member->isStaticMember()) {
2599 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2600 ContinuationBuilder.writeMemberType(SDMR);
2601 MemberCount++;
2602 continue;
2603 }
2604
2605 // Virtual function pointer member.
2606 if ((Member->getFlags() & DINode::FlagArtificial) &&
2607 Member->getName().starts_with("_vptr$")) {
2608 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2609 ContinuationBuilder.writeMemberType(VFPR);
2610 MemberCount++;
2611 continue;
2612 }
2613
2614 // Data member.
2615 uint64_t MemberOffsetInBits =
2616 Member->getOffsetInBits() + MemberInfo.BaseOffset;
2617 if (Member->isBitField()) {
2618 uint64_t StartBitOffset = MemberOffsetInBits;
2619 if (const auto *CI =
2620 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2621 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2622 }
2623 StartBitOffset -= MemberOffsetInBits;
2624 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2625 StartBitOffset);
2626 MemberBaseType = TypeTable.writeLeafType(BFR);
2627 }
2628 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2629 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2630 MemberName);
2631 ContinuationBuilder.writeMemberType(DMR);
2632 MemberCount++;
2633 }
2634
2635 // Create methods
2636 for (auto &MethodItr : Info.Methods) {
2637 StringRef Name = MethodItr.first->getString();
2638
2639 std::vector<OneMethodRecord> Methods;
2640 for (const DISubprogram *SP : MethodItr.second) {
2641 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2642 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2643
2644 unsigned VFTableOffset = -1;
2645 if (Introduced)
2646 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2647
2648 Methods.push_back(OneMethodRecord(
2649 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2650 translateMethodKindFlags(SP, Introduced),
2651 translateMethodOptionFlags(SP), VFTableOffset, Name));
2652 MemberCount++;
2653 }
2654 assert(!Methods.empty() && "Empty methods map entry");
2655 if (Methods.size() == 1)
2656 ContinuationBuilder.writeMemberType(Methods[0]);
2657 else {
2658 // FIXME: Make this use its own ContinuationBuilder so that
2659 // MethodOverloadList can be split correctly.
2660 MethodOverloadListRecord MOLR(Methods);
2661 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2662
2663 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2664 ContinuationBuilder.writeMemberType(OMR);
2665 }
2666 }
2667
2668 // Create nested classes.
2669 for (const DIType *Nested : Info.NestedTypes) {
2670 NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2671 ContinuationBuilder.writeMemberType(R);
2672 MemberCount++;
2673 }
2674
2675 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2676 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2677 !Info.NestedTypes.empty());
2678}
2679
2680TypeIndex CodeViewDebug::getVBPTypeIndex() {
2681 if (!VBPType.getIndex()) {
2682 // Make a 'const int *' type.
2683 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2684 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2685
2686 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2687 : PointerKind::Near32;
2688 PointerMode PM = PointerMode::Pointer;
2689 PointerOptions PO = PointerOptions::None;
2690 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2691 VBPType = TypeTable.writeLeafType(PR);
2692 }
2693
2694 return VBPType;
2695}
2696
2697TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2698 // The null DIType is the void type. Don't try to hash it.
2699 if (!Ty)
2700 return TypeIndex::Void();
2701
2702 // Check if we've already translated this type. Don't try to do a
2703 // get-or-create style insertion that caches the hash lookup across the
2704 // lowerType call. It will update the TypeIndices map.
2705 auto I = TypeIndices.find({Ty, ClassTy});
2706 if (I != TypeIndices.end())
2707 return I->second;
2708
2709 TypeLoweringScope S(*this);
2710 TypeIndex TI = lowerType(Ty, ClassTy);
2711 return recordTypeIndexForDINode(Ty, TI, ClassTy);
2712}
2713
2715CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2716 const DISubroutineType *SubroutineTy) {
2717 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2718 "this type must be a pointer type");
2719
2720 PointerOptions Options = PointerOptions::None;
2721 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2722 Options = PointerOptions::LValueRefThisPointer;
2723 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2724 Options = PointerOptions::RValueRefThisPointer;
2725
2726 // Check if we've already translated this type. If there is no ref qualifier
2727 // on the function then we look up this pointer type with no associated class
2728 // so that the TypeIndex for the this pointer can be shared with the type
2729 // index for other pointers to this class type. If there is a ref qualifier
2730 // then we lookup the pointer using the subroutine as the parent type.
2731 auto I = TypeIndices.find({PtrTy, SubroutineTy});
2732 if (I != TypeIndices.end())
2733 return I->second;
2734
2735 TypeLoweringScope S(*this);
2736 TypeIndex TI = lowerTypePointer(PtrTy, Options);
2737 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2738}
2739
2740TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2741 // The null DIType is the void type. Don't try to hash it.
2742 if (!Ty)
2743 return TypeIndex::Void();
2744
2745 // Look through typedefs when getting the complete type index. Call
2746 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2747 // emitted only once.
2748 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2749 (void)getTypeIndex(Ty);
2750 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2751 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2752
2753 // If this is a non-record type, the complete type index is the same as the
2754 // normal type index. Just call getTypeIndex.
2755 switch (Ty->getTag()) {
2756 case dwarf::DW_TAG_class_type:
2757 case dwarf::DW_TAG_structure_type:
2758 case dwarf::DW_TAG_union_type:
2759 break;
2760 default:
2761 return getTypeIndex(Ty);
2762 }
2763
2764 const auto *CTy = cast<DICompositeType>(Ty);
2765
2766 TypeLoweringScope S(*this);
2767
2768 // Make sure the forward declaration is emitted first. It's unclear if this
2769 // is necessary, but MSVC does it, and we should follow suit until we can show
2770 // otherwise.
2771 // We only emit a forward declaration for named types.
2772 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2773 TypeIndex FwdDeclTI = getTypeIndex(CTy);
2774
2775 // Just use the forward decl if we don't have complete type info. This
2776 // might happen if the frontend is using modules and expects the complete
2777 // definition to be emitted elsewhere.
2778 if (CTy->isForwardDecl())
2779 return FwdDeclTI;
2780 }
2781
2782 // Check if we've already translated the complete record type.
2783 // Insert the type with a null TypeIndex to signify that the type is currently
2784 // being lowered.
2785 auto InsertResult = CompleteTypeIndices.try_emplace(CTy);
2786 if (!InsertResult.second)
2787 return InsertResult.first->second;
2788
2789 TypeIndex TI;
2790 switch (CTy->getTag()) {
2791 case dwarf::DW_TAG_class_type:
2792 case dwarf::DW_TAG_structure_type:
2793 TI = lowerCompleteTypeClass(CTy);
2794 break;
2795 case dwarf::DW_TAG_union_type:
2796 TI = lowerCompleteTypeUnion(CTy);
2797 break;
2798 default:
2799 llvm_unreachable("not a record");
2800 }
2801
2802 // Update the type index associated with this CompositeType. This cannot
2803 // use the 'InsertResult' iterator above because it is potentially
2804 // invalidated by map insertions which can occur while lowering the class
2805 // type above.
2806 CompleteTypeIndices[CTy] = TI;
2807 return TI;
2808}
2809
2810/// Emit all the deferred complete record types. Try to do this in FIFO order,
2811/// and do this until fixpoint, as each complete record type typically
2812/// references
2813/// many other record types.
2814void CodeViewDebug::emitDeferredCompleteTypes() {
2816 while (!DeferredCompleteTypes.empty()) {
2817 std::swap(DeferredCompleteTypes, TypesToEmit);
2818 for (const DICompositeType *RecordTy : TypesToEmit)
2819 getCompleteTypeIndex(RecordTy);
2820 TypesToEmit.clear();
2821 }
2822}
2823
2824void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2825 ArrayRef<LocalVariable> Locals) {
2826 // Get the sorted list of parameters and emit them first.
2828 for (const LocalVariable &L : Locals)
2829 if (L.DIVar->isParameter())
2830 Params.push_back(&L);
2831 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2832 return L->DIVar->getArg() < R->DIVar->getArg();
2833 });
2834 for (const LocalVariable *L : Params)
2835 emitLocalVariable(FI, *L);
2836
2837 // Next emit all non-parameters in the order that we found them.
2838 for (const LocalVariable &L : Locals) {
2839 if (!L.DIVar->isParameter()) {
2840 if (L.ConstantValue) {
2841 // If ConstantValue is set we will emit it as a S_CONSTANT instead of a
2842 // S_LOCAL in order to be able to represent it at all.
2843 const DIType *Ty = L.DIVar->getType();
2844 APSInt Val(*L.ConstantValue);
2845 emitConstantSymbolRecord(Ty, Val, std::string(L.DIVar->getName()));
2846 } else {
2847 emitLocalVariable(FI, L);
2848 }
2849 }
2850 }
2851}
2852
2853void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2854 const LocalVariable &Var) {
2855 // LocalSym record, see SymbolRecord.h for more info.
2856 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2857
2858 LocalSymFlags Flags = LocalSymFlags::None;
2859 if (Var.DIVar->isParameter())
2860 Flags |= LocalSymFlags::IsParameter;
2861 if (Var.DefRanges.empty())
2862 Flags |= LocalSymFlags::IsOptimizedOut;
2863
2864 OS.AddComment("TypeIndex");
2865 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
2866 OS.emitInt32(TI.getIndex());
2867 OS.AddComment("Flags");
2868 OS.emitInt16(static_cast<uint16_t>(Flags));
2869 // Truncate the name so we won't overflow the record length field.
2870 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2871 endSymbolRecord(LocalEnd);
2872
2873 // Calculate the on disk prefix of the appropriate def range record. The
2874 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2875 // should be big enough to hold all forms without memory allocation.
2876 SmallString<20> BytePrefix;
2877 for (const auto &Pair : Var.DefRanges) {
2878 LocalVarDef DefRange = Pair.first;
2879 const auto &Ranges = Pair.second;
2880 BytePrefix.clear();
2881 if (DefRange.InMemory) {
2882 int Offset = DefRange.DataOffset;
2883 unsigned Reg = DefRange.CVRegister;
2884
2885 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2886 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2887 // instead. In frames without stack realignment, $T0 will be the CFA.
2888 if (RegisterId(Reg) == RegisterId::ESP) {
2889 Reg = unsigned(RegisterId::VFRAME);
2890 Offset += FI.OffsetAdjustment;
2891 }
2892
2894
2895 if (DefRange.DerefOffset != LocalVarDef::NoDeref) {
2896 uint16_t RegRelFlags = 0;
2897 if (DefRange.IsSubfield) {
2899 (DefRange.StructOffset
2901 }
2902 DefRangeRegisterRelIndirHeader DRHdr;
2903 DRHdr.Register = Reg;
2904 DRHdr.Flags = RegRelFlags;
2905 DRHdr.BasePointerOffset = Offset;
2906 DRHdr.OffsetInUdt = DefRange.DerefOffset;
2907 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2908 } else if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2909 (bool(Flags & LocalSymFlags::IsParameter)
2910 ? (EncFP == FI.EncodedParamFramePtrReg)
2911 : (EncFP == FI.EncodedLocalFramePtrReg))) {
2912 // If we can use the chosen frame pointer for the frame and this isn't a
2913 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2914 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2915 DefRangeFramePointerRelHeader DRHdr;
2916 DRHdr.Offset = Offset;
2917 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2918 } else {
2919 uint16_t RegRelFlags = 0;
2920 if (DefRange.IsSubfield) {
2922 (DefRange.StructOffset
2924 }
2925 DefRangeRegisterRelHeader DRHdr;
2926 DRHdr.Register = Reg;
2927 DRHdr.Flags = RegRelFlags;
2928 DRHdr.BasePointerOffset = Offset;
2929 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2930 }
2931 } else {
2932 assert(DefRange.DataOffset == 0 &&
2933 DefRange.DerefOffset == LocalVarDef::NoDeref &&
2934 "unexpected offset into register");
2935 if (DefRange.IsSubfield) {
2936 DefRangeSubfieldRegisterHeader DRHdr;
2937 DRHdr.Register = DefRange.CVRegister;
2938 DRHdr.MayHaveNoName = 0;
2939 DRHdr.OffsetInParent = DefRange.StructOffset;
2940 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2941 } else {
2942 DefRangeRegisterHeader DRHdr;
2943 DRHdr.Register = DefRange.CVRegister;
2944 DRHdr.MayHaveNoName = 0;
2945 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2946 }
2947 }
2948 }
2949}
2950
2951void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2952 const FunctionInfo& FI) {
2953 for (LexicalBlock *Block : Blocks)
2954 emitLexicalBlock(*Block, FI);
2955}
2956
2957/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2958/// lexical block scope.
2959void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2960 const FunctionInfo& FI) {
2961 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2962 OS.AddComment("PtrParent");
2963 OS.emitInt32(0); // PtrParent
2964 OS.AddComment("PtrEnd");
2965 OS.emitInt32(0); // PtrEnd
2966 OS.AddComment("Code size");
2967 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2968 OS.AddComment("Function section relative address");
2969 OS.emitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2970 OS.AddComment("Function section index");
2971 OS.emitCOFFSectionIndex(FI.Begin); // Func Symbol
2972 OS.AddComment("Lexical block name");
2973 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2974 endSymbolRecord(RecordEnd);
2975
2976 // Emit variables local to this lexical block.
2977 emitLocalVariableList(FI, Block.Locals);
2978 emitGlobalVariableList(Block.Globals);
2979
2980 // Emit lexical blocks contained within this block.
2981 emitLexicalBlockList(Block.Children, FI);
2982
2983 // Close the lexical block scope.
2984 emitEndSymbolRecord(SymbolKind::S_END);
2985}
2986
2987/// Convenience routine for collecting lexical block information for a list
2988/// of lexical scopes.
2989void CodeViewDebug::collectLexicalBlockInfo(
2994 for (LexicalScope *Scope : Scopes)
2995 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2996}
2997
2998/// Populate the lexical blocks and local variable lists of the parent with
2999/// information about the specified lexical scope.
3000void CodeViewDebug::collectLexicalBlockInfo(
3001 LexicalScope &Scope,
3002 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
3003 SmallVectorImpl<LocalVariable> &ParentLocals,
3004 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
3005 if (Scope.isAbstractScope())
3006 return;
3007
3008 // Gather information about the lexical scope including local variables,
3009 // global variables, and address ranges.
3010 bool IgnoreScope = false;
3011 auto LI = ScopeVariables.find(&Scope);
3012 SmallVectorImpl<LocalVariable> *Locals =
3013 LI != ScopeVariables.end() ? &LI->second : nullptr;
3014 auto GI = ScopeGlobals.find(Scope.getScopeNode());
3015 SmallVectorImpl<CVGlobalVariable> *Globals =
3016 GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
3017 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
3018 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
3019
3020 // Ignore lexical scopes which do not contain variables.
3021 if (!Locals && !Globals)
3022 IgnoreScope = true;
3023
3024 // Ignore lexical scopes which are not lexical blocks.
3025 if (!DILB)
3026 IgnoreScope = true;
3027
3028 // Ignore scopes which have too many address ranges to represent in the
3029 // current CodeView format or do not have a valid address range.
3030 //
3031 // For lexical scopes with multiple address ranges you may be tempted to
3032 // construct a single range covering every instruction where the block is
3033 // live and everything in between. Unfortunately, Visual Studio only
3034 // displays variables from the first matching lexical block scope. If the
3035 // first lexical block contains exception handling code or cold code which
3036 // is moved to the bottom of the routine creating a single range covering
3037 // nearly the entire routine, then it will hide all other lexical blocks
3038 // and the variables they contain.
3039 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
3040 IgnoreScope = true;
3041
3042 if (IgnoreScope) {
3043 // This scope can be safely ignored and eliminating it will reduce the
3044 // size of the debug information. Be sure to collect any variable and scope
3045 // information from the this scope or any of its children and collapse them
3046 // into the parent scope.
3047 if (Locals)
3048 ParentLocals.append(Locals->begin(), Locals->end());
3049 if (Globals)
3050 ParentGlobals.append(Globals->begin(), Globals->end());
3051 collectLexicalBlockInfo(Scope.getChildren(),
3052 ParentBlocks,
3053 ParentLocals,
3054 ParentGlobals);
3055 return;
3056 }
3057
3058 // Create a new CodeView lexical block for this lexical scope. If we've
3059 // seen this DILexicalBlock before then the scope tree is malformed and
3060 // we can handle this gracefully by not processing it a second time.
3061 auto BlockInsertion = CurFn->LexicalBlocks.try_emplace(DILB);
3062 if (!BlockInsertion.second)
3063 return;
3064
3065 // Create a lexical block containing the variables and collect the
3066 // lexical block information for the children.
3067 const InsnRange &Range = Ranges.front();
3068 assert(Range.first && Range.second);
3069 LexicalBlock &Block = BlockInsertion.first->second;
3070 Block.Begin = getLabelBeforeInsn(Range.first);
3071 Block.End = getLabelAfterInsn(Range.second);
3072 assert(Block.Begin && "missing label for scope begin");
3073 assert(Block.End && "missing label for scope end");
3074 Block.Name = DILB->getName();
3075 if (Locals)
3076 Block.Locals = std::move(*Locals);
3077 if (Globals)
3078 Block.Globals = std::move(*Globals);
3079 ParentBlocks.push_back(&Block);
3080 collectLexicalBlockInfo(Scope.getChildren(),
3081 Block.Children,
3082 Block.Locals,
3083 Block.Globals);
3084}
3085
3087 const Function &GV = MF->getFunction();
3088 assert(FnDebugInfo.count(&GV));
3089 assert(CurFn == FnDebugInfo[&GV].get());
3090
3091 collectVariableInfo(GV.getSubprogram());
3092
3093 // Build the lexical block structure to emit for this routine.
3094 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
3095 collectLexicalBlockInfo(*CFS,
3096 CurFn->ChildBlocks,
3097 CurFn->Locals,
3098 CurFn->Globals);
3099
3100 // Clear the scope and variable information from the map which will not be
3101 // valid after we have finished processing this routine. This also prepares
3102 // the map for the subsequent routine.
3103 ScopeVariables.clear();
3104
3105 // Don't emit anything if we don't have any line tables.
3106 // Thunks are compiler-generated and probably won't have source correlation.
3107 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
3108 FnDebugInfo.erase(&GV);
3109 CurFn = nullptr;
3110 return;
3111 }
3112
3113 // Find heap alloc sites and add to list.
3114 for (const auto &MBB : *MF) {
3115 for (const auto &MI : MBB) {
3116 if (MDNode *MD = MI.getHeapAllocMarker()) {
3117 CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
3119 dyn_cast<DIType>(MD)));
3120 }
3121 }
3122 }
3123
3124 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
3126 collectDebugInfoForJumpTables(MF, isThumb);
3127
3128 CurFn->Annotations = MF->getCodeViewAnnotations();
3129
3130 CurFn->End = Asm->getFunctionEnd();
3131
3132 CurFn = nullptr;
3133}
3134
3135// Usable locations are valid with non-zero line numbers, or artificial
3136// subprograms because they are associated to the corresponding line within the
3137// inlined callee.
3138//
3139// A line number of zero corresponds to optimized code that doesn't have a
3140// distinct source location.
3141//
3142// In this case, we try to use the previous or next source location depending on
3143// the context.
3145 if (!DL)
3146 return false;
3147 if (DL.getLine() != 0)
3148 return true;
3149 if (const DILocalScope *Scope = DL->getScope())
3150 return Scope->getSubprogram()->isArtificial();
3151 return false;
3152}
3153
3156
3157 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3158 if (!Asm || !CurFn || MI->isDebugInstr() ||
3159 MI->getFlag(MachineInstr::FrameSetup))
3160 return;
3161
3162 // If the first instruction of a new MBB has no location, find the first
3163 // instruction with a location and use that.
3164 DebugLoc DL = MI->getDebugLoc();
3165 if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
3166 for (const auto &NextMI : *MI->getParent()) {
3167 if (NextMI.isDebugInstr())
3168 continue;
3169 DL = NextMI.getDebugLoc();
3170 if (isUsableDebugLoc(DL))
3171 break;
3172 }
3173 // FIXME: Handle the case where the BB has no valid locations. This would
3174 // probably require doing a real dataflow analysis.
3175 }
3176 PrevInstBB = MI->getParent();
3177
3178 // If we still don't have a debug location, don't record a location.
3179 if (!isUsableDebugLoc(DL))
3180 return;
3181
3182 maybeRecordLocation(DL, Asm->MF);
3183}
3184
3185MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
3186 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3187 *EndLabel = MMI->getContext().createTempSymbol();
3188 OS.emitInt32(unsigned(Kind));
3189 OS.AddComment("Subsection size");
3190 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
3191 OS.emitLabel(BeginLabel);
3192 return EndLabel;
3193}
3194
3195void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
3196 OS.emitLabel(EndLabel);
3197 // Every subsection must be aligned to a 4-byte boundary.
3199}
3200
3201MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
3202 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3203 *EndLabel = MMI->getContext().createTempSymbol();
3204 OS.AddComment("Record length");
3205 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
3206 OS.emitLabel(BeginLabel);
3207 if (OS.isVerboseAsm())
3208 OS.AddComment("Record kind: " + getSymbolTypeNames().toString(SymKind));
3209 OS.emitInt16(unsigned(SymKind));
3210 return EndLabel;
3211}
3212
3213void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
3214 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
3215 // an extra copy of every symbol record in LLD. This increases object file
3216 // size by less than 1% in the clang build, and is compatible with the Visual
3217 // C++ linker.
3218 OS.emitValueToAlignment(Align(4));
3219 OS.emitLabel(SymEnd);
3220}
3221
3222void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
3223 OS.AddComment("Record length");
3224 OS.emitInt16(2);
3225 if (OS.isVerboseAsm())
3226 OS.AddComment("Record kind: " + getSymbolTypeNames().toString(EndKind));
3227 OS.emitInt16(uint16_t(EndKind)); // Record Kind
3228}
3229
3230void CodeViewDebug::emitDebugInfoForUDTs(
3231 const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3232#ifndef NDEBUG
3233 size_t OriginalSize = UDTs.size();
3234#endif
3235 for (const auto &UDT : UDTs) {
3236 const DIType *T = UDT.second;
3238 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3239 OS.AddComment("Type");
3240 OS.emitInt32(getCompleteTypeIndex(T).getIndex());
3241 assert(OriginalSize == UDTs.size() &&
3242 "getCompleteTypeIndex found new UDTs!");
3244 endSymbolRecord(UDTRecordEnd);
3245 }
3246}
3247
3248void CodeViewDebug::collectGlobalOrStaticLocalVariableInfo(
3249 const DIGlobalVariableExpression *GVE) {
3250 const DIGlobalVariable *DIGV = GVE->getVariable();
3251 const DIExpression *DIE = GVE->getExpression();
3252 // Don't emit string literals in CodeView, as the only useful parts are
3253 // generally the filename and line number, which isn't possible to output
3254 // in CodeView. String literals should be the only unnamed GlobalVariable
3255 // with debug info.
3256 if (DIGV->getName().empty())
3257 return;
3258
3259 if ((DIE->getNumElements() == 2) &&
3260 (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3261 // Record the constant offset for the variable.
3262 //
3263 // A Fortran common block uses this idiom to encode the offset
3264 // of a variable from the common block's starting address.
3265 CVGlobalVariableOffsets.insert(std::make_pair(DIGV, DIE->getElement(1)));
3266
3267 // Emit constant global variables in a global symbol section.
3268 if (!GlobalMap.count(GVE) && DIE->isConstant())
3269 GlobalVariables.emplace_back(CVGlobalVariable{DIGV, DIE});
3270
3271 const auto *GV = GlobalMap.lookup(GVE);
3272 if (!GV || GV->isDeclarationForLinker())
3273 return;
3274
3275 DIScope *Scope = DIGV->getScope();
3276 SmallVector<CVGlobalVariable, 1> *VariableList;
3277 if (Scope && isa<DILocalScope>(Scope)) {
3278 // Locate a global variable list for this scope, creating one if
3279 // necessary.
3280 auto Insertion =
3281 ScopeGlobals.insert({Scope, std::unique_ptr<GlobalVariableList>()});
3282 if (Insertion.second)
3283 Insertion.first->second = std::make_unique<GlobalVariableList>();
3284 VariableList = Insertion.first->second.get();
3285 } else if (GV->hasComdat()) {
3286 // Emit this global variable into a COMDAT section.
3287 VariableList = &ComdatVariables;
3288 } else {
3289 // Emit this global variable in a single global symbol section.
3290 VariableList = &GlobalVariables;
3291 }
3292 VariableList->emplace_back(CVGlobalVariable{DIGV, GV});
3293}
3294
3295void CodeViewDebug::collectGlobalVariableInfo() {
3296 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3298 GV.getDebugInfo(GVEs);
3299 for (const auto *GVE : GVEs)
3300 GlobalMap[GVE] = &GV;
3301 }
3302
3303 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3304 for (const MDNode *Node : CUs->operands()) {
3305 const auto *CU = cast<DICompileUnit>(Node);
3306 for (const auto *GVE : CU->getGlobalVariables()) {
3307 collectGlobalOrStaticLocalVariableInfo(GVE);
3308 }
3309 }
3310}
3311
3312void CodeViewDebug::collectDebugInfoForGlobals() {
3313 for (const CVGlobalVariable &CVGV : GlobalVariables) {
3314 const DIGlobalVariable *DIGV = CVGV.DIGV;
3315 const DIScope *Scope = DIGV->getScope();
3316 getCompleteTypeIndex(DIGV->getType());
3317 getFullyQualifiedName(Scope, DIGV->getName());
3318 }
3319
3320 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3321 const DIGlobalVariable *DIGV = CVGV.DIGV;
3322 const DIScope *Scope = DIGV->getScope();
3323 getCompleteTypeIndex(DIGV->getType());
3324 getFullyQualifiedName(Scope, DIGV->getName());
3325 }
3326}
3327
3328void CodeViewDebug::emitDebugInfoForGlobals() {
3329 // First, emit all globals that are not in a comdat in a single symbol
3330 // substream. MSVC doesn't like it if the substream is empty, so only open
3331 // it if we have at least one global to emit.
3332 switchToDebugSectionForSymbol(nullptr);
3333 if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3334 OS.AddComment("Symbol subsection for globals");
3335 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3336 emitGlobalVariableList(GlobalVariables);
3337 emitStaticConstMemberList();
3338 endCVSubsection(EndLabel);
3339 }
3340
3341 // Second, emit each global that is in a comdat into its own .debug$S
3342 // section along with its own symbol substream.
3343 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3344 const GlobalVariable *GV = cast<const GlobalVariable *>(CVGV.GVInfo);
3345 MCSymbol *GVSym = Asm->getSymbol(GV);
3346 OS.AddComment("Symbol subsection for " +
3348 switchToDebugSectionForSymbol(GVSym);
3349 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3350 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3351 emitDebugInfoForGlobal(CVGV);
3352 endCVSubsection(EndLabel);
3353 }
3354}
3355
3356void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3357 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3358 for (const MDNode *Node : CUs->operands()) {
3359 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3360 if (DIType *RT = dyn_cast<DIType>(Ty)) {
3361 getTypeIndex(RT);
3362 // FIXME: Add to global/local DTU list.
3363 }
3364 }
3365 }
3366}
3367
3368// Emit each global variable in the specified array.
3369void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3370 for (const CVGlobalVariable &CVGV : Globals) {
3371 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3372 emitDebugInfoForGlobal(CVGV);
3373 }
3374}
3375
3376void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3377 const std::string &QualifiedName) {
3378 MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3379 OS.AddComment("Type");
3380 OS.emitInt32(getTypeIndex(DTy).getIndex());
3381
3382 OS.AddComment("Value");
3383
3384 // Encoded integers shouldn't need more than 10 bytes.
3385 uint8_t Data[10];
3386 BinaryStreamWriter Writer(Data, llvm::endianness::little);
3387 CodeViewRecordIO IO(Writer);
3388 cantFail(IO.mapEncodedInteger(Value));
3389 StringRef SRef((char *)Data, Writer.getOffset());
3390 OS.emitBinaryData(SRef);
3391
3392 OS.AddComment("Name");
3393 emitNullTerminatedSymbolName(OS, QualifiedName);
3394 endSymbolRecord(SConstantEnd);
3395}
3396
3397void CodeViewDebug::emitStaticConstMemberList() {
3398 for (const DIDerivedType *DTy : StaticConstMembers) {
3399 const DIScope *Scope = DTy->getScope();
3400
3401 APSInt Value;
3402 if (const ConstantInt *CI =
3403 dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3404 Value = APSInt(CI->getValue(),
3405 DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3406 else if (const ConstantFP *CFP =
3407 dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3408 Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3409 else
3410 llvm_unreachable("cannot emit a constant without a value");
3411
3412 emitConstantSymbolRecord(DTy->getBaseType(), Value,
3413 getFullyQualifiedName(Scope, DTy->getName()));
3414 }
3415}
3416
3417static bool isFloatDIType(const DIType *Ty) {
3418 if (isa<DICompositeType>(Ty))
3419 return false;
3420
3421 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3422 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3423 if (T == dwarf::DW_TAG_pointer_type ||
3424 T == dwarf::DW_TAG_ptr_to_member_type ||
3425 T == dwarf::DW_TAG_reference_type ||
3426 T == dwarf::DW_TAG_rvalue_reference_type)
3427 return false;
3428 assert(DTy->getBaseType() && "Expected valid base type");
3429 return isFloatDIType(DTy->getBaseType());
3430 }
3431
3432 auto *BTy = cast<DIBasicType>(Ty);
3433 return (BTy->getEncoding() == dwarf::DW_ATE_float);
3434}
3435
3436void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3437 const DIGlobalVariable *DIGV = CVGV.DIGV;
3438
3439 const DIScope *Scope = DIGV->getScope();
3440 // For static data members, get the scope from the declaration.
3441 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3443 Scope = MemberDecl->getScope();
3444 // For static local variables and Fortran, the scoping portion is elided
3445 // in its name so that we can reference the variable in the command line
3446 // of the VS debugger.
3447 std::string QualifiedName =
3448 (moduleIsInFortran() || (Scope && isa<DILocalScope>(Scope)))
3449 ? std::string(DIGV->getName())
3450 : getFullyQualifiedName(Scope, DIGV->getName());
3451
3452 if (const GlobalVariable *GV =
3454 // DataSym record, see SymbolRecord.h for more info. Thread local data
3455 // happens to have the same format as global data.
3456 MCSymbol *GVSym = Asm->getSymbol(GV);
3457 SymbolKind DataSym = GV->isThreadLocal()
3458 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3459 : SymbolKind::S_GTHREAD32)
3460 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3461 : SymbolKind::S_GDATA32);
3462 MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3463 OS.AddComment("Type");
3464 OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
3465 OS.AddComment("DataOffset");
3466
3467 // Use the offset seen while collecting info on globals.
3468 uint64_t Offset = CVGlobalVariableOffsets.lookup(DIGV);
3469 OS.emitCOFFSecRel32(GVSym, Offset);
3470
3471 OS.AddComment("Segment");
3472 OS.emitCOFFSectionIndex(GVSym);
3473 OS.AddComment("Name");
3474 const unsigned LengthOfDataRecord = 12;
3475 emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
3476 endSymbolRecord(DataEnd);
3477 } else {
3478 const DIExpression *DIE = cast<const DIExpression *>(CVGV.GVInfo);
3479 assert(DIE->isConstant() &&
3480 "Global constant variables must contain a constant expression.");
3481
3482 // Use unsigned for floats.
3483 bool isUnsigned = isFloatDIType(DIGV->getType())
3484 ? true
3485 : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
3486 APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3487 emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
3488 }
3489}
3490
3492 const MachineFunction *MF, bool isThumb,
3493 const std::function<void(const MachineJumpTableInfo &, const MachineInstr &,
3494 int64_t)> &Callback) {
3495 auto JTI = MF->getJumpTableInfo();
3496 if (JTI && !JTI->isEmpty()) {
3497#ifndef NDEBUG
3498 auto UsedJTs = llvm::SmallBitVector(JTI->getJumpTables().size());
3499#endif
3500 for (const auto &MBB : *MF) {
3501 // Search for indirect branches...
3502 const auto LastMI = MBB.getFirstTerminator();
3503 if (LastMI != MBB.end() && LastMI->isIndirectBranch()) {
3504 if (isThumb) {
3505 // ... that directly use jump table operands.
3506 // NOTE: ARM uses pattern matching to lower its BR_JT SDNode to
3507 // machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node
3508 // interferes with this process *but* the resulting pseudo-instruction
3509 // uses a Jump Table operand, so extract the jump table index directly
3510 // from that.
3511 for (const auto &MO : LastMI->operands()) {
3512 if (MO.isJTI()) {
3513 unsigned Index = MO.getIndex();
3514#ifndef NDEBUG
3515 UsedJTs.set(Index);
3516#endif
3517 Callback(*JTI, *LastMI, Index);
3518 break;
3519 }
3520 }
3521 } else {
3522 // ... that have jump table debug info.
3523 // NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node
3524 // when lowering the BR_JT SDNode to an indirect branch.
3525 for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I) {
3526 if (I->isJumpTableDebugInfo()) {
3527 unsigned Index = I->getOperand(0).getImm();
3528#ifndef NDEBUG
3529 UsedJTs.set(Index);
3530#endif
3531 Callback(*JTI, *LastMI, Index);
3532 break;
3533 }
3534 }
3535 }
3536 }
3537 }
3538#ifndef NDEBUG
3539 assert(UsedJTs.all() &&
3540 "Some of jump tables were not used in a debug info instruction");
3541#endif
3542 }
3543}
3544
3545void CodeViewDebug::discoverJumpTableBranches(const MachineFunction *MF,
3546 bool isThumb) {
3548 MF, isThumb,
3549 [this](const MachineJumpTableInfo &, const MachineInstr &BranchMI,
3550 int64_t) { requestLabelBeforeInsn(&BranchMI); });
3551}
3552
3553void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction *MF,
3554 bool isThumb) {
3556 MF, isThumb,
3557 [this, MF](const MachineJumpTableInfo &JTI, const MachineInstr &BranchMI,
3558 int64_t JumpTableIndex) {
3559 // For label-difference jump tables, find the base expression.
3560 // Otherwise the jump table uses an absolute address (so no base
3561 // is required).
3562 const MCSymbol *Base;
3563 uint64_t BaseOffset = 0;
3564 const MCSymbol *Branch = getLabelBeforeInsn(&BranchMI);
3565 JumpTableEntrySize EntrySize;
3566 switch (JTI.getEntryKind()) {
3571 "EK_Custom32, EK_GPRel32BlockAddress, and "
3572 "EK_GPRel64BlockAddress should never be emitted for COFF");
3574 // Each entry is an absolute address.
3575 EntrySize = JumpTableEntrySize::Pointer;
3576 Base = nullptr;
3577 break;
3581 // Ask the AsmPrinter.
3582 std::tie(Base, BaseOffset, Branch, EntrySize) =
3583 Asm->getCodeViewJumpTableInfo(JumpTableIndex, &BranchMI, Branch);
3584 break;
3585 }
3586
3587 const MachineJumpTableEntry &JTE = JTI.getJumpTables()[JumpTableIndex];
3588 JumpTableInfo CVJTI{EntrySize,
3589 Base,
3590 BaseOffset,
3591 Branch,
3592 MF->getJTISymbol(JumpTableIndex, MMI->getContext()),
3593 JTE.MBBs.size(),
3594 {}};
3595 for (const auto &MBB : JTE.MBBs)
3596 CVJTI.Cases.push_back(MBB->getSymbol());
3597 CurFn->JumpTables.push_back(std::move(CVJTI));
3598 });
3599}
3600
3601void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo &FI) {
3602 // Emit S_LABEL32 records for each jump target
3603 for (const auto &JumpTable : FI.JumpTables) {
3604 for (const auto &CaseSym : JumpTable.Cases) {
3605 MCSymbol *LabelEnd = beginSymbolRecord(SymbolKind::S_LABEL32);
3606 OS.AddComment("Offset and segment");
3607 OS.emitCOFFSecRel32(CaseSym, 0);
3608 OS.AddComment("Flags");
3609 OS.emitInt8(0);
3610 emitNullTerminatedSymbolName(OS, CaseSym->getName());
3611 endSymbolRecord(LabelEnd);
3612 }
3613 }
3614
3615 for (const auto &JumpTable : FI.JumpTables) {
3616 MCSymbol *JumpTableEnd = beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE);
3617 if (JumpTable.Base) {
3618 OS.AddComment("Base offset");
3619 OS.emitCOFFSecRel32(JumpTable.Base, JumpTable.BaseOffset);
3620 OS.AddComment("Base section index");
3621 OS.emitCOFFSectionIndex(JumpTable.Base);
3622 } else {
3623 OS.AddComment("Base offset");
3624 OS.emitInt32(0);
3625 OS.AddComment("Base section index");
3626 OS.emitInt16(0);
3627 }
3628 OS.AddComment("Switch type");
3629 OS.emitInt16(static_cast<uint16_t>(JumpTable.EntrySize));
3630 OS.AddComment("Branch offset");
3631 OS.emitCOFFSecRel32(JumpTable.Branch, /*Offset=*/0);
3632 OS.AddComment("Table offset");
3633 OS.emitCOFFSecRel32(JumpTable.Table, /*Offset=*/0);
3634 OS.AddComment("Branch section index");
3635 OS.emitCOFFSectionIndex(JumpTable.Branch);
3636 OS.AddComment("Table section index");
3637 OS.emitCOFFSectionIndex(JumpTable.Table);
3638 OS.AddComment("Entries count");
3639 OS.emitInt32(JumpTable.TableSize);
3640 endSymbolRecord(JumpTableEnd);
3641 }
3642}
3643
3644void CodeViewDebug::emitInlinees(
3645 const SmallSet<codeview::TypeIndex, 1> &Inlinees) {
3646 // Divide the list of inlinees into chunks such that each chunk fits within
3647 // one record.
3648 constexpr size_t ChunkSize =
3649 (MaxRecordLength - sizeof(SymbolKind) - sizeof(uint32_t)) /
3650 sizeof(uint32_t);
3651
3652 SmallVector<TypeIndex> SortedInlinees{Inlinees.begin(), Inlinees.end()};
3653 llvm::sort(SortedInlinees);
3654
3655 size_t CurrentIndex = 0;
3656 while (CurrentIndex < SortedInlinees.size()) {
3657 auto Symbol = beginSymbolRecord(SymbolKind::S_INLINEES);
3658 auto CurrentChunkSize =
3659 std::min(ChunkSize, SortedInlinees.size() - CurrentIndex);
3660 OS.AddComment("Count");
3661 OS.emitInt32(CurrentChunkSize);
3662
3663 const size_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize;
3664 for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) {
3665 OS.AddComment("Inlinee");
3666 OS.emitInt32(SortedInlinees[CurrentIndex].getIndex());
3667 }
3668 endSymbolRecord(Symbol);
3669 }
3670}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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:699
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
Definition Function.cpp:841
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:890
Constant * getPersonalityFn() const
Get the personality function associated with this function.
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition Function.h:313
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Definition Function.h:740
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:734
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:769
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:1081
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
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:68
A tuple of MDNodes.
Definition Metadata.h:1797
iterator_range< op_iterator > operands()
Definition Metadata.h:1893
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:51
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
PointerMode
Equivalent to CV_ptrmode_e.
Definition CodeView.h:337
ProcSymFlags
Corresponds to the CV_PROCFLAGS bitfield.
Definition CodeView.h:417
PointerOptions
Equivalent to misc lfPointerAttr bitfields.
Definition CodeView.h:346
LocalSymFlags
Corresponds to CV_LVARFLAGS bitfield.
Definition CodeView.h:390
MethodKind
Part of member attribute flags. (CV_methodprop_e)
Definition CodeView.h:254
CVRecord< TypeLeafKind > CVType
Definition CVRecord.h:64
PointerKind
Equivalent to CV_ptrtype_e.
Definition CodeView.h:320
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:360
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:265
MemberAccess
Source-level access specifier. (CV_access_e)
Definition CodeView.h:246
ThunkOrdinal
These values correspond to the THUNK_ORDINAL enumeration.
Definition CodeView.h:538
LLVM_ABI EnumStrings< SymbolKind, 1 > getSymbolTypeNames()
EncodedFramePtrReg
Two-bit value indicating which register is the designated frame pointer register.
Definition CodeView.h:525
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:285
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:402
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:694
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
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:577
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:42
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:408
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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:1926
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:1963
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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.