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