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