brintos

brintos / llvm-project-archived public Read only

0
0
Text · 20.3 KiB · 7fd2cec Raw
560 lines · c
1//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===//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-exception6//7//===----------------------------------------------------------------------===//8//9// This file contains support for writing Microsoft CodeView debug info.10//11//===----------------------------------------------------------------------===//12 13#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H14#define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H15 16#include "llvm/ADT/APSInt.h"17#include "llvm/ADT/ArrayRef.h"18#include "llvm/ADT/DenseMap.h"19#include "llvm/ADT/DenseSet.h"20#include "llvm/ADT/MapVector.h"21#include "llvm/ADT/PointerUnion.h"22#include "llvm/ADT/SetVector.h"23#include "llvm/ADT/SmallSet.h"24#include "llvm/ADT/SmallVector.h"25#include "llvm/CodeGen/DbgEntityHistoryCalculator.h"26#include "llvm/CodeGen/DebugHandlerBase.h"27#include "llvm/CodeGen/MachineJumpTableInfo.h"28#include "llvm/DebugInfo/CodeView/CodeView.h"29#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"30#include "llvm/DebugInfo/CodeView/TypeIndex.h"31#include "llvm/IR/DebugLoc.h"32#include "llvm/Support/Allocator.h"33#include "llvm/Support/Compiler.h"34#include <cstdint>35#include <map>36#include <string>37#include <tuple>38#include <unordered_map>39#include <utility>40#include <vector>41 42namespace llvm {43 44struct ClassInfo;45class StringRef;46class AsmPrinter;47class Function;48class GlobalVariable;49class MCSectionCOFF;50class MCStreamer;51class MCSymbol;52class MachineFunction;53 54/// Collects and handles line tables information in a CodeView format.55class LLVM_LIBRARY_VISIBILITY CodeViewDebug : public DebugHandlerBase {56public:57  struct LocalVarDef {58    /// Indicates that variable data is stored in memory relative to the59    /// specified register.60    int InMemory : 1;61 62    /// Offset of variable data in memory.63    int DataOffset : 31;64 65    /// Non-zero if this is a piece of an aggregate.66    uint32_t IsSubfield : 1;67 68    /// Offset into aggregate.69    uint32_t StructOffset : 15;70 71    /// Register containing the data or the register base of the memory72    /// location containing the data.73    uint32_t CVRegister : 16;74 75    uint64_t static toOpaqueValue(const LocalVarDef DR) {76      uint64_t Val = 0;77      std::memcpy(&Val, &DR, sizeof(Val));78      return Val;79    }80 81    LocalVarDef static createFromOpaqueValue(uint64_t Val) {82      LocalVarDef DR;83      std::memcpy(&DR, &Val, sizeof(Val));84      return DR;85    }86  };87 88  static_assert(sizeof(uint64_t) == sizeof(LocalVarDef));89 90private:91  MCStreamer &OS;92  BumpPtrAllocator Allocator;93  codeview::GlobalTypeTableBuilder TypeTable;94 95  /// Whether to emit type record hashes into .debug$H.96  bool EmitDebugGlobalHashes = false;97 98  /// The codeview CPU type used by the translation unit.99  codeview::CPUType TheCPU;100 101  const DICompileUnit *TheCU = nullptr;102 103  /// The AsmPrinter used for emitting compiler metadata. When only compiler104  /// info is being emitted, DebugHandlerBase::Asm may be null.105  AsmPrinter *CompilerInfoAsm = nullptr;106 107  static LocalVarDef createDefRangeMem(uint16_t CVRegister, int Offset);108 109  /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.110  struct LocalVariable {111    const DILocalVariable *DIVar = nullptr;112    MapVector<LocalVarDef,113              SmallVector<std::pair<const MCSymbol *, const MCSymbol *>, 1>>114        DefRanges;115    bool UseReferenceType = false;116    std::optional<APSInt> ConstantValue;117  };118 119  struct CVGlobalVariable {120    const DIGlobalVariable *DIGV;121    PointerUnion<const GlobalVariable *, const DIExpression *> GVInfo;122  };123 124  struct InlineSite {125    SmallVector<LocalVariable, 1> InlinedLocals;126    SmallVector<const DILocation *, 1> ChildSites;127    const DISubprogram *Inlinee = nullptr;128 129    /// The ID of the inline site or function used with .cv_loc. Not a type130    /// index.131    unsigned SiteFuncId = 0;132  };133 134  // Combines information from DILexicalBlock and LexicalScope.135  struct LexicalBlock {136    SmallVector<LocalVariable, 1> Locals;137    SmallVector<CVGlobalVariable, 1> Globals;138    SmallVector<LexicalBlock *, 1> Children;139    const MCSymbol *Begin;140    const MCSymbol *End;141    StringRef Name;142  };143 144  struct JumpTableInfo {145    codeview::JumpTableEntrySize EntrySize;146    const MCSymbol *Base;147    uint64_t BaseOffset;148    const MCSymbol *Branch;149    const MCSymbol *Table;150    size_t TableSize;151    std::vector<const MCSymbol *> Cases;152  };153 154  // For each function, store a vector of labels to its instructions, as well as155  // to the end of the function.156  struct FunctionInfo {157    FunctionInfo() = default;158 159    // Uncopyable.160    FunctionInfo(const FunctionInfo &FI) = delete;161 162    /// Map from inlined call site to inlined instructions and child inlined163    /// call sites. Listed in program order.164    std::unordered_map<const DILocation *, InlineSite> InlineSites;165 166    /// Ordered list of top-level inlined call sites.167    SmallVector<const DILocation *, 1> ChildSites;168 169    /// Set of all functions directly inlined into this one.170    SmallSet<codeview::TypeIndex, 1> Inlinees;171 172    SmallVector<LocalVariable, 1> Locals;173    SmallVector<CVGlobalVariable, 1> Globals;174 175    std::unordered_map<const DILexicalBlockBase*, LexicalBlock> LexicalBlocks;176 177    // Lexical blocks containing local variables.178    SmallVector<LexicalBlock *, 1> ChildBlocks;179 180    std::vector<std::pair<MCSymbol *, MDNode *>> Annotations;181    std::vector<std::tuple<const MCSymbol *, const MCSymbol *, const DIType *>>182        HeapAllocSites;183 184    std::vector<JumpTableInfo> JumpTables;185 186    const MCSymbol *Begin = nullptr;187    const MCSymbol *End = nullptr;188    unsigned FuncId = 0;189    unsigned LastFileId = 0;190 191    /// Number of bytes allocated in the prologue for all local stack objects.192    unsigned FrameSize = 0;193 194    /// Number of bytes of parameters on the stack.195    unsigned ParamSize = 0;196 197    /// Number of bytes pushed to save CSRs.198    unsigned CSRSize = 0;199 200    /// Adjustment to apply on x86 when using the VFRAME frame pointer.201    int OffsetAdjustment = 0;202 203    /// Two-bit value indicating which register is the designated frame pointer204    /// register for local variables. Included in S_FRAMEPROC.205    codeview::EncodedFramePtrReg EncodedLocalFramePtrReg =206        codeview::EncodedFramePtrReg::None;207 208    /// Two-bit value indicating which register is the designated frame pointer209    /// register for stack parameters. Included in S_FRAMEPROC.210    codeview::EncodedFramePtrReg EncodedParamFramePtrReg =211        codeview::EncodedFramePtrReg::None;212 213    codeview::FrameProcedureOptions FrameProcOpts;214 215    bool HasStackRealignment = false;216 217    bool HaveLineInfo = false;218 219    bool HasFramePointer = false;220  };221  FunctionInfo *CurFn = nullptr;222 223  codeview::SourceLanguage CurrentSourceLanguage =224      codeview::SourceLanguage::Masm;225 226  // This map records the constant offset in DIExpression of the227  // DIGlobalVariableExpression referencing the DIGlobalVariable.228  DenseMap<const DIGlobalVariable *, uint64_t> CVGlobalVariableOffsets;229 230  // Map used to separate variables according to the lexical scope they belong231  // in.  This is populated by recordLocalVariable() before232  // collectLexicalBlocks() separates the variables between the FunctionInfo233  // and LexicalBlocks.234  DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables;235 236  // Map to separate global variables according to the lexical scope they237  // belong in. A null local scope represents the global scope.238  typedef SmallVector<CVGlobalVariable, 1> GlobalVariableList;239  DenseMap<const DIScope*, std::unique_ptr<GlobalVariableList> > ScopeGlobals;240 241  // Array of global variables which  need to be emitted into a COMDAT section.242  SmallVector<CVGlobalVariable, 1> ComdatVariables;243 244  // Array of non-COMDAT global variables.245  SmallVector<CVGlobalVariable, 1> GlobalVariables;246 247  /// List of static const data members to be emitted as S_CONSTANTs.248  SmallVector<const DIDerivedType *, 4> StaticConstMembers;249 250  /// The set of comdat .debug$S sections that we've seen so far. Each section251  /// must start with a magic version number that must only be emitted once.252  /// This set tracks which sections we've already opened.253  DenseSet<MCSectionCOFF *> ComdatDebugSections;254 255  /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol256  /// of an emitted global value, is in a comdat COFF section, this will switch257  /// to a new .debug$S section in that comdat. This method ensures that the258  /// section starts with the magic version number on first use. If GVSym is259  /// null, uses the main .debug$S section.260  void switchToDebugSectionForSymbol(const MCSymbol *GVSym);261 262  /// The next available function index for use with our .cv_* directives. Not263  /// to be confused with type indices for LF_FUNC_ID records.264  unsigned NextFuncId = 0;265 266  InlineSite &getInlineSite(const DILocation *InlinedAt,267                            const DISubprogram *Inlinee);268 269  codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP);270 271  void calculateRanges(LocalVariable &Var,272                       const DbgValueHistoryMap::Entries &Entries);273 274  /// Remember some debug info about each function. Keep it in a stable order to275  /// emit at the end of the TU.276  MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo;277 278  /// Map from full file path to .cv_file id. Full paths are built from DIFiles279  /// and are stored in FileToFilepathMap;280  DenseMap<StringRef, unsigned> FileIdMap;281 282  /// All inlined subprograms in the order they should be emitted.283  SmallSetVector<const DISubprogram *, 4> InlinedSubprograms;284 285  /// Map from a pair of DI metadata nodes and its DI type (or scope) that can286  /// be nullptr, to CodeView type indices. Primarily indexed by287  /// {DIType*, DIType*} and {DISubprogram*, DIType*}.288  ///289  /// The second entry in the key is needed for methods as DISubroutineType290  /// representing static method type are shared with non-method function type.291  DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex>292      TypeIndices;293 294  /// Map from DICompositeType* to complete type index. Non-record types are295  /// always looked up in the normal TypeIndices map.296  DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices;297 298  /// Complete record types to emit after all active type lowerings are299  /// finished.300  SmallVector<const DICompositeType *, 4> DeferredCompleteTypes;301 302  /// Number of type lowering frames active on the stack.303  unsigned TypeEmissionLevel = 0;304 305  codeview::TypeIndex VBPType;306 307  const DISubprogram *CurrentSubprogram = nullptr;308 309  // The UDTs we have seen while processing types; each entry is a pair of type310  // index and type name.311  std::vector<std::pair<std::string, const DIType *>> LocalUDTs;312  std::vector<std::pair<std::string, const DIType *>> GlobalUDTs;313 314  using FileToFilepathMapTy = std::map<const DIFile *, std::string>;315  FileToFilepathMapTy FileToFilepathMap;316 317  StringRef getFullFilepath(const DIFile *File);318 319  unsigned maybeRecordFile(const DIFile *F);320 321  void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF);322 323  void clear();324 325  void setCurrentSubprogram(const DISubprogram *SP) {326    CurrentSubprogram = SP;327    LocalUDTs.clear();328  }329 330  /// Emit the magic version number at the start of a CodeView type or symbol331  /// section. Appears at the front of every .debug$S or .debug$T or .debug$P332  /// section.333  void emitCodeViewMagicVersion();334 335  void emitTypeInformation();336 337  void emitTypeGlobalHashes();338 339  void emitObjName();340 341  void emitCompilerInformation();342 343  void emitSecureHotPatchInformation();344 345  void emitBuildInfo();346 347  void emitInlineeLinesSubsection();348 349  void emitDebugInfoForThunk(const Function *GV,350                             FunctionInfo &FI,351                             const MCSymbol *Fn);352 353  void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI);354 355  void emitDebugInfoForRetainedTypes();356 357  void emitDebugInfoForUDTs(358      const std::vector<std::pair<std::string, const DIType *>> &UDTs);359 360  void collectDebugInfoForGlobals();361  void emitDebugInfoForGlobals();362  void emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals);363  void emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,364                                const std::string &QualifiedName);365  void emitDebugInfoForGlobal(const CVGlobalVariable &CVGV);366  void emitStaticConstMemberList();367 368  /// Opens a subsection of the given kind in a .debug$S codeview section.369  /// Returns an end label for use with endCVSubsection when the subsection is370  /// finished.371  MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind);372  void endCVSubsection(MCSymbol *EndLabel);373 374  /// Opens a symbol record of the given kind. Returns an end label for use with375  /// endSymbolRecord.376  MCSymbol *beginSymbolRecord(codeview::SymbolKind Kind);377  void endSymbolRecord(MCSymbol *SymEnd);378 379  /// Emits an S_END, S_INLINESITE_END, or S_PROC_ID_END record. These records380  /// are empty, so we emit them with a simpler assembly sequence that doesn't381  /// involve labels.382  void emitEndSymbolRecord(codeview::SymbolKind EndKind);383 384  void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt,385                           const InlineSite &Site);386 387  void emitInlinees(const SmallSet<codeview::TypeIndex, 1> &Inlinees);388 389  using InlinedEntity = DbgValueHistoryMap::InlinedEntity;390 391  void collectGlobalVariableInfo();392  void collectVariableInfo(const DISubprogram *SP);393 394  void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed);395 396  // Construct the lexical block tree for a routine, pruning emptpy lexical397  // scopes, and populate it with local variables.398  void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes,399                               SmallVectorImpl<LexicalBlock *> &Blocks,400                               SmallVectorImpl<LocalVariable> &Locals,401                               SmallVectorImpl<CVGlobalVariable> &Globals);402  void collectLexicalBlockInfo(LexicalScope &Scope,403                               SmallVectorImpl<LexicalBlock *> &ParentBlocks,404                               SmallVectorImpl<LocalVariable> &ParentLocals,405                               SmallVectorImpl<CVGlobalVariable> &ParentGlobals);406 407  /// Records information about a local variable in the appropriate scope. In408  /// particular, locals from inlined code live inside the inlining site.409  void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS);410 411  /// Emits local variables in the appropriate order.412  void emitLocalVariableList(const FunctionInfo &FI,413                             ArrayRef<LocalVariable> Locals);414 415  /// Emits an S_LOCAL record and its associated defined ranges.416  void emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var);417 418  /// Emits a sequence of lexical block scopes and their children.419  void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,420                            const FunctionInfo& FI);421 422  /// Emit a lexical block scope and its children.423  void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI);424 425  /// Translates the DIType to codeview if necessary and returns a type index426  /// for it.427  codeview::TypeIndex getTypeIndex(const DIType *Ty,428                                   const DIType *ClassTy = nullptr);429 430  codeview::TypeIndex431  getTypeIndexForThisPtr(const DIDerivedType *PtrTy,432                         const DISubroutineType *SubroutineTy);433 434  codeview::TypeIndex getTypeIndexForReferenceTo(const DIType *Ty);435 436  codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP,437                                            const DICompositeType *Class);438 439  codeview::TypeIndex getScopeIndex(const DIScope *Scope);440 441  codeview::TypeIndex getVBPTypeIndex();442 443  void addToUDTs(const DIType *Ty);444 445  void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI);446 447  codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy);448  codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty);449  codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty);450  codeview::TypeIndex lowerTypeString(const DIStringType *Ty);451  codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty);452  codeview::TypeIndex lowerTypePointer(453      const DIDerivedType *Ty,454      codeview::PointerOptions PO = codeview::PointerOptions::None);455  codeview::TypeIndex lowerTypeMemberPointer(456      const DIDerivedType *Ty,457      codeview::PointerOptions PO = codeview::PointerOptions::None);458  codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty);459  codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty);460  codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty);461  codeview::TypeIndex lowerTypeMemberFunction(462      const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment,463      bool IsStaticMethod,464      codeview::FunctionOptions FO = codeview::FunctionOptions::None);465  codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty);466  codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty);467  codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty);468 469  /// Symbol records should point to complete types, but type records should470  /// always point to incomplete types to avoid cycles in the type graph. Only471  /// use this entry point when generating symbol records. The complete and472  /// incomplete type indices only differ for record types. All other types use473  /// the same index.474  codeview::TypeIndex getCompleteTypeIndex(const DIType *Ty);475 476  codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty);477  codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty);478 479  struct TypeLoweringScope;480 481  void emitDeferredCompleteTypes();482 483  void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy);484  ClassInfo collectClassInfo(const DICompositeType *Ty);485 486  /// Common record member lowering functionality for record types, which are487  /// structs, classes, and unions. Returns the field list index and the member488  /// count.489  std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool>490  lowerRecordFieldList(const DICompositeType *Ty);491 492  /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.493  codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node,494                                               codeview::TypeIndex TI,495                                               const DIType *ClassTy = nullptr);496 497  /// Collect the names of parent scopes, innermost to outermost. Return the498  /// innermost subprogram scope if present. Ensure that parent type scopes are499  /// inserted into the type table.500  const DISubprogram *501  collectParentScopeNames(const DIScope *Scope,502                          SmallVectorImpl<StringRef> &ParentScopeNames);503  std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name);504  std::string getFullyQualifiedName(const DIScope *Scope);505 506  unsigned getPointerSizeInBytes();507 508  void discoverJumpTableBranches(const MachineFunction *MF, bool isThumb);509  void collectDebugInfoForJumpTables(const MachineFunction *MF, bool isThumb);510  void emitDebugInfoForJumpTables(const FunctionInfo &FI);511 512protected:513  /// Gather pre-function debug information.514  void beginFunctionImpl(const MachineFunction *MF) override;515 516  /// Gather post-function debug information.517  void endFunctionImpl(const MachineFunction *) override;518 519  /// Check if the current module is in Fortran.520  bool moduleIsInFortran() {521    return CurrentSourceLanguage == codeview::SourceLanguage::Fortran;522  }523 524public:525  CodeViewDebug(AsmPrinter *AP);526 527  void beginModule(Module *M) override;528 529  /// Emit the COFF section that holds the line table information.530  void endModule() override;531 532  /// Process beginning of an instruction.533  void beginInstruction(const MachineInstr *MI) override;534};535 536template <> struct DenseMapInfo<CodeViewDebug::LocalVarDef> {537 538  static inline CodeViewDebug::LocalVarDef getEmptyKey() {539    return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL);540  }541 542  static inline CodeViewDebug::LocalVarDef getTombstoneKey() {543    return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL - 1ULL);544  }545 546  static unsigned getHashValue(const CodeViewDebug::LocalVarDef &DR) {547    return CodeViewDebug::LocalVarDef::toOpaqueValue(DR) * 37ULL;548  }549 550  static bool isEqual(const CodeViewDebug::LocalVarDef &LHS,551                      const CodeViewDebug::LocalVarDef &RHS) {552    return CodeViewDebug::LocalVarDef::toOpaqueValue(LHS) ==553           CodeViewDebug::LocalVarDef::toOpaqueValue(RHS);554  }555};556 557} // end namespace llvm558 559#endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H560