Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
35271 views
//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains support for writing Microsoft CodeView debug info.9//10//===----------------------------------------------------------------------===//1112#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H13#define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H1415#include "llvm/ADT/APSInt.h"16#include "llvm/ADT/ArrayRef.h"17#include "llvm/ADT/DenseMap.h"18#include "llvm/ADT/DenseSet.h"19#include "llvm/ADT/MapVector.h"20#include "llvm/ADT/PointerUnion.h"21#include "llvm/ADT/SetVector.h"22#include "llvm/ADT/SmallSet.h"23#include "llvm/ADT/SmallVector.h"24#include "llvm/CodeGen/DbgEntityHistoryCalculator.h"25#include "llvm/CodeGen/DebugHandlerBase.h"26#include "llvm/CodeGen/MachineJumpTableInfo.h"27#include "llvm/DebugInfo/CodeView/CodeView.h"28#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"29#include "llvm/DebugInfo/CodeView/TypeIndex.h"30#include "llvm/IR/DebugLoc.h"31#include "llvm/Support/Allocator.h"32#include "llvm/Support/Compiler.h"33#include <cstdint>34#include <map>35#include <string>36#include <tuple>37#include <unordered_map>38#include <utility>39#include <vector>4041namespace llvm {4243struct ClassInfo;44class StringRef;45class AsmPrinter;46class Function;47class GlobalVariable;48class MCSectionCOFF;49class MCStreamer;50class MCSymbol;51class MachineFunction;5253/// Collects and handles line tables information in a CodeView format.54class LLVM_LIBRARY_VISIBILITY CodeViewDebug : public DebugHandlerBase {55public:56struct LocalVarDef {57/// Indicates that variable data is stored in memory relative to the58/// specified register.59int InMemory : 1;6061/// Offset of variable data in memory.62int DataOffset : 31;6364/// Non-zero if this is a piece of an aggregate.65uint16_t IsSubfield : 1;6667/// Offset into aggregate.68uint16_t StructOffset : 15;6970/// Register containing the data or the register base of the memory71/// location containing the data.72uint16_t CVRegister;7374uint64_t static toOpaqueValue(const LocalVarDef DR) {75uint64_t Val = 0;76std::memcpy(&Val, &DR, sizeof(Val));77return Val;78}7980LocalVarDef static createFromOpaqueValue(uint64_t Val) {81LocalVarDef DR;82std::memcpy(&DR, &Val, sizeof(Val));83return DR;84}85};8687static_assert(sizeof(uint64_t) == sizeof(LocalVarDef));8889private:90MCStreamer &OS;91BumpPtrAllocator Allocator;92codeview::GlobalTypeTableBuilder TypeTable;9394/// Whether to emit type record hashes into .debug$H.95bool EmitDebugGlobalHashes = false;9697/// The codeview CPU type used by the translation unit.98codeview::CPUType TheCPU;99100static LocalVarDef createDefRangeMem(uint16_t CVRegister, int Offset);101102/// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.103struct LocalVariable {104const DILocalVariable *DIVar = nullptr;105MapVector<LocalVarDef,106SmallVector<std::pair<const MCSymbol *, const MCSymbol *>, 1>>107DefRanges;108bool UseReferenceType = false;109std::optional<APSInt> ConstantValue;110};111112struct CVGlobalVariable {113const DIGlobalVariable *DIGV;114PointerUnion<const GlobalVariable *, const DIExpression *> GVInfo;115};116117struct InlineSite {118SmallVector<LocalVariable, 1> InlinedLocals;119SmallVector<const DILocation *, 1> ChildSites;120const DISubprogram *Inlinee = nullptr;121122/// The ID of the inline site or function used with .cv_loc. Not a type123/// index.124unsigned SiteFuncId = 0;125};126127// Combines information from DILexicalBlock and LexicalScope.128struct LexicalBlock {129SmallVector<LocalVariable, 1> Locals;130SmallVector<CVGlobalVariable, 1> Globals;131SmallVector<LexicalBlock *, 1> Children;132const MCSymbol *Begin;133const MCSymbol *End;134StringRef Name;135};136137struct JumpTableInfo {138codeview::JumpTableEntrySize EntrySize;139const MCSymbol *Base;140uint64_t BaseOffset;141const MCSymbol *Branch;142const MCSymbol *Table;143size_t TableSize;144};145146// For each function, store a vector of labels to its instructions, as well as147// to the end of the function.148struct FunctionInfo {149FunctionInfo() = default;150151// Uncopyable.152FunctionInfo(const FunctionInfo &FI) = delete;153154/// Map from inlined call site to inlined instructions and child inlined155/// call sites. Listed in program order.156std::unordered_map<const DILocation *, InlineSite> InlineSites;157158/// Ordered list of top-level inlined call sites.159SmallVector<const DILocation *, 1> ChildSites;160161/// Set of all functions directly inlined into this one.162SmallSet<codeview::TypeIndex, 1> Inlinees;163164SmallVector<LocalVariable, 1> Locals;165SmallVector<CVGlobalVariable, 1> Globals;166167std::unordered_map<const DILexicalBlockBase*, LexicalBlock> LexicalBlocks;168169// Lexical blocks containing local variables.170SmallVector<LexicalBlock *, 1> ChildBlocks;171172std::vector<std::pair<MCSymbol *, MDNode *>> Annotations;173std::vector<std::tuple<const MCSymbol *, const MCSymbol *, const DIType *>>174HeapAllocSites;175176std::vector<JumpTableInfo> JumpTables;177178const MCSymbol *Begin = nullptr;179const MCSymbol *End = nullptr;180unsigned FuncId = 0;181unsigned LastFileId = 0;182183/// Number of bytes allocated in the prologue for all local stack objects.184unsigned FrameSize = 0;185186/// Number of bytes of parameters on the stack.187unsigned ParamSize = 0;188189/// Number of bytes pushed to save CSRs.190unsigned CSRSize = 0;191192/// Adjustment to apply on x86 when using the VFRAME frame pointer.193int OffsetAdjustment = 0;194195/// Two-bit value indicating which register is the designated frame pointer196/// register for local variables. Included in S_FRAMEPROC.197codeview::EncodedFramePtrReg EncodedLocalFramePtrReg =198codeview::EncodedFramePtrReg::None;199200/// Two-bit value indicating which register is the designated frame pointer201/// register for stack parameters. Included in S_FRAMEPROC.202codeview::EncodedFramePtrReg EncodedParamFramePtrReg =203codeview::EncodedFramePtrReg::None;204205codeview::FrameProcedureOptions FrameProcOpts;206207bool HasStackRealignment = false;208209bool HaveLineInfo = false;210211bool HasFramePointer = false;212};213FunctionInfo *CurFn = nullptr;214215codeview::SourceLanguage CurrentSourceLanguage =216codeview::SourceLanguage::Masm;217218// This map records the constant offset in DIExpression of the219// DIGlobalVariableExpression referencing the DIGlobalVariable.220DenseMap<const DIGlobalVariable *, uint64_t> CVGlobalVariableOffsets;221222// Map used to separate variables according to the lexical scope they belong223// in. This is populated by recordLocalVariable() before224// collectLexicalBlocks() separates the variables between the FunctionInfo225// and LexicalBlocks.226DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables;227228// Map to separate global variables according to the lexical scope they229// belong in. A null local scope represents the global scope.230typedef SmallVector<CVGlobalVariable, 1> GlobalVariableList;231DenseMap<const DIScope*, std::unique_ptr<GlobalVariableList> > ScopeGlobals;232233// Array of global variables which need to be emitted into a COMDAT section.234SmallVector<CVGlobalVariable, 1> ComdatVariables;235236// Array of non-COMDAT global variables.237SmallVector<CVGlobalVariable, 1> GlobalVariables;238239/// List of static const data members to be emitted as S_CONSTANTs.240SmallVector<const DIDerivedType *, 4> StaticConstMembers;241242/// The set of comdat .debug$S sections that we've seen so far. Each section243/// must start with a magic version number that must only be emitted once.244/// This set tracks which sections we've already opened.245DenseSet<MCSectionCOFF *> ComdatDebugSections;246247/// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol248/// of an emitted global value, is in a comdat COFF section, this will switch249/// to a new .debug$S section in that comdat. This method ensures that the250/// section starts with the magic version number on first use. If GVSym is251/// null, uses the main .debug$S section.252void switchToDebugSectionForSymbol(const MCSymbol *GVSym);253254/// The next available function index for use with our .cv_* directives. Not255/// to be confused with type indices for LF_FUNC_ID records.256unsigned NextFuncId = 0;257258InlineSite &getInlineSite(const DILocation *InlinedAt,259const DISubprogram *Inlinee);260261codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP);262263void calculateRanges(LocalVariable &Var,264const DbgValueHistoryMap::Entries &Entries);265266/// Remember some debug info about each function. Keep it in a stable order to267/// emit at the end of the TU.268MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo;269270/// Map from full file path to .cv_file id. Full paths are built from DIFiles271/// and are stored in FileToFilepathMap;272DenseMap<StringRef, unsigned> FileIdMap;273274/// All inlined subprograms in the order they should be emitted.275SmallSetVector<const DISubprogram *, 4> InlinedSubprograms;276277/// Map from a pair of DI metadata nodes and its DI type (or scope) that can278/// be nullptr, to CodeView type indices. Primarily indexed by279/// {DIType*, DIType*} and {DISubprogram*, DIType*}.280///281/// The second entry in the key is needed for methods as DISubroutineType282/// representing static method type are shared with non-method function type.283DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex>284TypeIndices;285286/// Map from DICompositeType* to complete type index. Non-record types are287/// always looked up in the normal TypeIndices map.288DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices;289290/// Complete record types to emit after all active type lowerings are291/// finished.292SmallVector<const DICompositeType *, 4> DeferredCompleteTypes;293294/// Number of type lowering frames active on the stack.295unsigned TypeEmissionLevel = 0;296297codeview::TypeIndex VBPType;298299const DISubprogram *CurrentSubprogram = nullptr;300301// The UDTs we have seen while processing types; each entry is a pair of type302// index and type name.303std::vector<std::pair<std::string, const DIType *>> LocalUDTs;304std::vector<std::pair<std::string, const DIType *>> GlobalUDTs;305306using FileToFilepathMapTy = std::map<const DIFile *, std::string>;307FileToFilepathMapTy FileToFilepathMap;308309StringRef getFullFilepath(const DIFile *File);310311unsigned maybeRecordFile(const DIFile *F);312313void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF);314315void clear();316317void setCurrentSubprogram(const DISubprogram *SP) {318CurrentSubprogram = SP;319LocalUDTs.clear();320}321322/// Emit the magic version number at the start of a CodeView type or symbol323/// section. Appears at the front of every .debug$S or .debug$T or .debug$P324/// section.325void emitCodeViewMagicVersion();326327void emitTypeInformation();328329void emitTypeGlobalHashes();330331void emitObjName();332333void emitCompilerInformation();334335void emitBuildInfo();336337void emitInlineeLinesSubsection();338339void emitDebugInfoForThunk(const Function *GV,340FunctionInfo &FI,341const MCSymbol *Fn);342343void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI);344345void emitDebugInfoForRetainedTypes();346347void emitDebugInfoForUDTs(348const std::vector<std::pair<std::string, const DIType *>> &UDTs);349350void collectDebugInfoForGlobals();351void emitDebugInfoForGlobals();352void emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals);353void emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,354const std::string &QualifiedName);355void emitDebugInfoForGlobal(const CVGlobalVariable &CVGV);356void emitStaticConstMemberList();357358/// Opens a subsection of the given kind in a .debug$S codeview section.359/// Returns an end label for use with endCVSubsection when the subsection is360/// finished.361MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind);362void endCVSubsection(MCSymbol *EndLabel);363364/// Opens a symbol record of the given kind. Returns an end label for use with365/// endSymbolRecord.366MCSymbol *beginSymbolRecord(codeview::SymbolKind Kind);367void endSymbolRecord(MCSymbol *SymEnd);368369/// Emits an S_END, S_INLINESITE_END, or S_PROC_ID_END record. These records370/// are empty, so we emit them with a simpler assembly sequence that doesn't371/// involve labels.372void emitEndSymbolRecord(codeview::SymbolKind EndKind);373374void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt,375const InlineSite &Site);376377void emitInlinees(const SmallSet<codeview::TypeIndex, 1> &Inlinees);378379using InlinedEntity = DbgValueHistoryMap::InlinedEntity;380381void collectGlobalVariableInfo();382void collectVariableInfo(const DISubprogram *SP);383384void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed);385386// Construct the lexical block tree for a routine, pruning emptpy lexical387// scopes, and populate it with local variables.388void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes,389SmallVectorImpl<LexicalBlock *> &Blocks,390SmallVectorImpl<LocalVariable> &Locals,391SmallVectorImpl<CVGlobalVariable> &Globals);392void collectLexicalBlockInfo(LexicalScope &Scope,393SmallVectorImpl<LexicalBlock *> &ParentBlocks,394SmallVectorImpl<LocalVariable> &ParentLocals,395SmallVectorImpl<CVGlobalVariable> &ParentGlobals);396397/// Records information about a local variable in the appropriate scope. In398/// particular, locals from inlined code live inside the inlining site.399void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS);400401/// Emits local variables in the appropriate order.402void emitLocalVariableList(const FunctionInfo &FI,403ArrayRef<LocalVariable> Locals);404405/// Emits an S_LOCAL record and its associated defined ranges.406void emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var);407408/// Emits a sequence of lexical block scopes and their children.409void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,410const FunctionInfo& FI);411412/// Emit a lexical block scope and its children.413void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI);414415/// Translates the DIType to codeview if necessary and returns a type index416/// for it.417codeview::TypeIndex getTypeIndex(const DIType *Ty,418const DIType *ClassTy = nullptr);419420codeview::TypeIndex421getTypeIndexForThisPtr(const DIDerivedType *PtrTy,422const DISubroutineType *SubroutineTy);423424codeview::TypeIndex getTypeIndexForReferenceTo(const DIType *Ty);425426codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP,427const DICompositeType *Class);428429codeview::TypeIndex getScopeIndex(const DIScope *Scope);430431codeview::TypeIndex getVBPTypeIndex();432433void addToUDTs(const DIType *Ty);434435void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI);436437codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy);438codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty);439codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty);440codeview::TypeIndex lowerTypeString(const DIStringType *Ty);441codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty);442codeview::TypeIndex lowerTypePointer(443const DIDerivedType *Ty,444codeview::PointerOptions PO = codeview::PointerOptions::None);445codeview::TypeIndex lowerTypeMemberPointer(446const DIDerivedType *Ty,447codeview::PointerOptions PO = codeview::PointerOptions::None);448codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty);449codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty);450codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty);451codeview::TypeIndex lowerTypeMemberFunction(452const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment,453bool IsStaticMethod,454codeview::FunctionOptions FO = codeview::FunctionOptions::None);455codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty);456codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty);457codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty);458459/// Symbol records should point to complete types, but type records should460/// always point to incomplete types to avoid cycles in the type graph. Only461/// use this entry point when generating symbol records. The complete and462/// incomplete type indices only differ for record types. All other types use463/// the same index.464codeview::TypeIndex getCompleteTypeIndex(const DIType *Ty);465466codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty);467codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty);468469struct TypeLoweringScope;470471void emitDeferredCompleteTypes();472473void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy);474ClassInfo collectClassInfo(const DICompositeType *Ty);475476/// Common record member lowering functionality for record types, which are477/// structs, classes, and unions. Returns the field list index and the member478/// count.479std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool>480lowerRecordFieldList(const DICompositeType *Ty);481482/// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.483codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node,484codeview::TypeIndex TI,485const DIType *ClassTy = nullptr);486487/// Collect the names of parent scopes, innermost to outermost. Return the488/// innermost subprogram scope if present. Ensure that parent type scopes are489/// inserted into the type table.490const DISubprogram *491collectParentScopeNames(const DIScope *Scope,492SmallVectorImpl<StringRef> &ParentScopeNames);493std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name);494std::string getFullyQualifiedName(const DIScope *Scope);495496unsigned getPointerSizeInBytes();497498void discoverJumpTableBranches(const MachineFunction *MF, bool isThumb);499void collectDebugInfoForJumpTables(const MachineFunction *MF, bool isThumb);500void emitDebugInfoForJumpTables(const FunctionInfo &FI);501502protected:503/// Gather pre-function debug information.504void beginFunctionImpl(const MachineFunction *MF) override;505506/// Gather post-function debug information.507void endFunctionImpl(const MachineFunction *) override;508509/// Check if the current module is in Fortran.510bool moduleIsInFortran() {511return CurrentSourceLanguage == codeview::SourceLanguage::Fortran;512}513514public:515CodeViewDebug(AsmPrinter *AP);516517void beginModule(Module *M) override;518519/// Emit the COFF section that holds the line table information.520void endModule() override;521522/// Process beginning of an instruction.523void beginInstruction(const MachineInstr *MI) override;524};525526template <> struct DenseMapInfo<CodeViewDebug::LocalVarDef> {527528static inline CodeViewDebug::LocalVarDef getEmptyKey() {529return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL);530}531532static inline CodeViewDebug::LocalVarDef getTombstoneKey() {533return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL - 1ULL);534}535536static unsigned getHashValue(const CodeViewDebug::LocalVarDef &DR) {537return CodeViewDebug::LocalVarDef::toOpaqueValue(DR) * 37ULL;538}539540static bool isEqual(const CodeViewDebug::LocalVarDef &LHS,541const CodeViewDebug::LocalVarDef &RHS) {542return CodeViewDebug::LocalVarDef::toOpaqueValue(LHS) ==543CodeViewDebug::LocalVarDef::toOpaqueValue(RHS);544}545};546547} // end namespace llvm548549#endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H550551552