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