1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for writing Microsoft CodeView debug info. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H 15 #define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H 16 17 #include "DbgEntityHistoryCalculator.h" 18 #include "DebugHandlerBase.h" 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/DenseSet.h" 22 #include "llvm/ADT/MapVector.h" 23 #include "llvm/ADT/SetVector.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/DebugInfo/CodeView/CodeView.h" 26 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h" 27 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 28 #include "llvm/IR/DebugLoc.h" 29 #include "llvm/Support/Allocator.h" 30 #include "llvm/Support/Compiler.h" 31 #include <cstdint> 32 #include <map> 33 #include <string> 34 #include <tuple> 35 #include <unordered_map> 36 #include <utility> 37 #include <vector> 38 39 namespace llvm { 40 41 struct ClassInfo; 42 class StringRef; 43 class AsmPrinter; 44 class Function; 45 class GlobalVariable; 46 class MCSectionCOFF; 47 class MCStreamer; 48 class MCSymbol; 49 class MachineFunction; 50 51 /// Collects and handles line tables information in a CodeView format. 52 class LLVM_LIBRARY_VISIBILITY CodeViewDebug : public DebugHandlerBase { 53 MCStreamer &OS; 54 BumpPtrAllocator Allocator; 55 codeview::GlobalTypeTableBuilder TypeTable; 56 57 /// The codeview CPU type used by the translation unit. 58 codeview::CPUType TheCPU; 59 60 /// Represents the most general definition range. 61 struct LocalVarDefRange { 62 /// Indicates that variable data is stored in memory relative to the 63 /// specified register. 64 int InMemory : 1; 65 66 /// Offset of variable data in memory. 67 int DataOffset : 31; 68 69 /// Non-zero if this is a piece of an aggregate. 70 uint16_t IsSubfield : 1; 71 72 /// Offset into aggregate. 73 uint16_t StructOffset : 15; 74 75 /// Register containing the data or the register base of the memory 76 /// location containing the data. 77 uint16_t CVRegister; 78 79 /// Compares all location fields. This includes all fields except the label 80 /// ranges. 81 bool isDifferentLocation(LocalVarDefRange &O) { 82 return InMemory != O.InMemory || DataOffset != O.DataOffset || 83 IsSubfield != O.IsSubfield || StructOffset != O.StructOffset || 84 CVRegister != O.CVRegister; 85 } 86 87 SmallVector<std::pair<const MCSymbol *, const MCSymbol *>, 1> Ranges; 88 }; 89 90 static LocalVarDefRange createDefRangeMem(uint16_t CVRegister, int Offset); 91 92 /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific. 93 struct LocalVariable { 94 const DILocalVariable *DIVar = nullptr; 95 SmallVector<LocalVarDefRange, 1> DefRanges; 96 bool UseReferenceType = false; 97 }; 98 99 struct InlineSite { 100 SmallVector<LocalVariable, 1> InlinedLocals; 101 SmallVector<const DILocation *, 1> ChildSites; 102 const DISubprogram *Inlinee = nullptr; 103 104 /// The ID of the inline site or function used with .cv_loc. Not a type 105 /// index. 106 unsigned SiteFuncId = 0; 107 }; 108 109 // Combines information from DILexicalBlock and LexicalScope. 110 struct LexicalBlock { 111 SmallVector<LocalVariable, 1> Locals; 112 SmallVector<LexicalBlock *, 1> Children; 113 const MCSymbol *Begin; 114 const MCSymbol *End; 115 StringRef Name; 116 }; 117 118 // For each function, store a vector of labels to its instructions, as well as 119 // to the end of the function. 120 struct FunctionInfo { 121 FunctionInfo() = default; 122 123 // Uncopyable. 124 FunctionInfo(const FunctionInfo &FI) = delete; 125 126 /// Map from inlined call site to inlined instructions and child inlined 127 /// call sites. Listed in program order. 128 std::unordered_map<const DILocation *, InlineSite> InlineSites; 129 130 /// Ordered list of top-level inlined call sites. 131 SmallVector<const DILocation *, 1> ChildSites; 132 133 SmallVector<LocalVariable, 1> Locals; 134 135 std::unordered_map<const DILexicalBlockBase*, LexicalBlock> LexicalBlocks; 136 137 // Lexical blocks containing local variables. 138 SmallVector<LexicalBlock *, 1> ChildBlocks; 139 140 std::vector<std::pair<MCSymbol *, MDNode *>> Annotations; 141 142 const MCSymbol *Begin = nullptr; 143 const MCSymbol *End = nullptr; 144 unsigned FuncId = 0; 145 unsigned LastFileId = 0; 146 147 /// Number of bytes allocated in the prologue for all local stack objects. 148 unsigned FrameSize = 0; 149 150 /// Number of bytes of parameters on the stack. 151 unsigned ParamSize = 0; 152 153 /// Number of bytes pushed to save CSRs. 154 unsigned CSRSize = 0; 155 156 /// Adjustment to apply on x86 when using the VFRAME frame pointer. 157 int OffsetAdjustment = 0; 158 159 /// Two-bit value indicating which register is the designated frame pointer 160 /// register for local variables. Included in S_FRAMEPROC. 161 codeview::EncodedFramePtrReg EncodedLocalFramePtrReg = 162 codeview::EncodedFramePtrReg::None; 163 164 /// Two-bit value indicating which register is the designated frame pointer 165 /// register for stack parameters. Included in S_FRAMEPROC. 166 codeview::EncodedFramePtrReg EncodedParamFramePtrReg = 167 codeview::EncodedFramePtrReg::None; 168 169 codeview::FrameProcedureOptions FrameProcOpts; 170 171 bool HasStackRealignment = false; 172 173 bool HaveLineInfo = false; 174 }; 175 FunctionInfo *CurFn = nullptr; 176 177 // Map used to seperate variables according to the lexical scope they belong 178 // in. This is populated by recordLocalVariable() before 179 // collectLexicalBlocks() separates the variables between the FunctionInfo 180 // and LexicalBlocks. 181 DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables; 182 183 /// The set of comdat .debug$S sections that we've seen so far. Each section 184 /// must start with a magic version number that must only be emitted once. 185 /// This set tracks which sections we've already opened. 186 DenseSet<MCSectionCOFF *> ComdatDebugSections; 187 188 /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol 189 /// of an emitted global value, is in a comdat COFF section, this will switch 190 /// to a new .debug$S section in that comdat. This method ensures that the 191 /// section starts with the magic version number on first use. If GVSym is 192 /// null, uses the main .debug$S section. 193 void switchToDebugSectionForSymbol(const MCSymbol *GVSym); 194 195 /// The next available function index for use with our .cv_* directives. Not 196 /// to be confused with type indices for LF_FUNC_ID records. 197 unsigned NextFuncId = 0; 198 199 InlineSite &getInlineSite(const DILocation *InlinedAt, 200 const DISubprogram *Inlinee); 201 202 codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP); 203 204 void calculateRanges(LocalVariable &Var, 205 const DbgValueHistoryMap::InstrRanges &Ranges); 206 207 static void collectInlineSiteChildren(SmallVectorImpl<unsigned> &Children, 208 const FunctionInfo &FI, 209 const InlineSite &Site); 210 211 /// Remember some debug info about each function. Keep it in a stable order to 212 /// emit at the end of the TU. 213 MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo; 214 215 /// Map from full file path to .cv_file id. Full paths are built from DIFiles 216 /// and are stored in FileToFilepathMap; 217 DenseMap<StringRef, unsigned> FileIdMap; 218 219 /// All inlined subprograms in the order they should be emitted. 220 SmallSetVector<const DISubprogram *, 4> InlinedSubprograms; 221 222 /// Map from a pair of DI metadata nodes and its DI type (or scope) that can 223 /// be nullptr, to CodeView type indices. Primarily indexed by 224 /// {DIType*, DIType*} and {DISubprogram*, DIType*}. 225 /// 226 /// The second entry in the key is needed for methods as DISubroutineType 227 /// representing static method type are shared with non-method function type. 228 DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex> 229 TypeIndices; 230 231 /// Map from DICompositeType* to complete type index. Non-record types are 232 /// always looked up in the normal TypeIndices map. 233 DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices; 234 235 /// Complete record types to emit after all active type lowerings are 236 /// finished. 237 SmallVector<const DICompositeType *, 4> DeferredCompleteTypes; 238 239 /// Number of type lowering frames active on the stack. 240 unsigned TypeEmissionLevel = 0; 241 242 codeview::TypeIndex VBPType; 243 244 const DISubprogram *CurrentSubprogram = nullptr; 245 246 // The UDTs we have seen while processing types; each entry is a pair of type 247 // index and type name. 248 std::vector<std::pair<std::string, const DIType *>> LocalUDTs; 249 std::vector<std::pair<std::string, const DIType *>> GlobalUDTs; 250 251 using FileToFilepathMapTy = std::map<const DIFile *, std::string>; 252 FileToFilepathMapTy FileToFilepathMap; 253 254 StringRef getFullFilepath(const DIFile *File); 255 256 unsigned maybeRecordFile(const DIFile *F); 257 258 void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF); 259 260 void clear(); 261 262 void setCurrentSubprogram(const DISubprogram *SP) { 263 CurrentSubprogram = SP; 264 LocalUDTs.clear(); 265 } 266 267 /// Emit the magic version number at the start of a CodeView type or symbol 268 /// section. Appears at the front of every .debug$S or .debug$T or .debug$P 269 /// section. 270 void emitCodeViewMagicVersion(); 271 272 void emitTypeInformation(); 273 274 void emitTypeGlobalHashes(); 275 276 void emitCompilerInformation(); 277 278 void emitBuildInfo(); 279 280 void emitInlineeLinesSubsection(); 281 282 void emitDebugInfoForThunk(const Function *GV, 283 FunctionInfo &FI, 284 const MCSymbol *Fn); 285 286 void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI); 287 288 void emitDebugInfoForGlobals(); 289 290 void emitDebugInfoForRetainedTypes(); 291 292 void 293 emitDebugInfoForUDTs(ArrayRef<std::pair<std::string, const DIType *>> UDTs); 294 295 void emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, 296 const GlobalVariable *GV, MCSymbol *GVSym); 297 298 /// Opens a subsection of the given kind in a .debug$S codeview section. 299 /// Returns an end label for use with endCVSubsection when the subsection is 300 /// finished. 301 MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind); 302 303 void endCVSubsection(MCSymbol *EndLabel); 304 305 void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt, 306 const InlineSite &Site); 307 308 using InlinedEntity = DbgValueHistoryMap::InlinedEntity; 309 310 void collectVariableInfo(const DISubprogram *SP); 311 312 void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed); 313 314 // Construct the lexical block tree for a routine, pruning emptpy lexical 315 // scopes, and populate it with local variables. 316 void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes, 317 SmallVectorImpl<LexicalBlock *> &Blocks, 318 SmallVectorImpl<LocalVariable> &Locals); 319 void collectLexicalBlockInfo(LexicalScope &Scope, 320 SmallVectorImpl<LexicalBlock *> &ParentBlocks, 321 SmallVectorImpl<LocalVariable> &ParentLocals); 322 323 /// Records information about a local variable in the appropriate scope. In 324 /// particular, locals from inlined code live inside the inlining site. 325 void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS); 326 327 /// Emits local variables in the appropriate order. 328 void emitLocalVariableList(const FunctionInfo &FI, 329 ArrayRef<LocalVariable> Locals); 330 331 /// Emits an S_LOCAL record and its associated defined ranges. 332 void emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var); 333 334 /// Emits a sequence of lexical block scopes and their children. 335 void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks, 336 const FunctionInfo& FI); 337 338 /// Emit a lexical block scope and its children. 339 void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI); 340 341 /// Translates the DIType to codeview if necessary and returns a type index 342 /// for it. 343 codeview::TypeIndex getTypeIndex(DITypeRef TypeRef, 344 DITypeRef ClassTyRef = DITypeRef()); 345 346 codeview::TypeIndex getTypeIndexForReferenceTo(DITypeRef TypeRef); 347 348 codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP, 349 const DICompositeType *Class); 350 351 codeview::TypeIndex getScopeIndex(const DIScope *Scope); 352 353 codeview::TypeIndex getVBPTypeIndex(); 354 355 void addToUDTs(const DIType *Ty); 356 357 void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI); 358 359 codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy); 360 codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty); 361 codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty); 362 codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty); 363 codeview::TypeIndex lowerTypePointer( 364 const DIDerivedType *Ty, 365 codeview::PointerOptions PO = codeview::PointerOptions::None); 366 codeview::TypeIndex lowerTypeMemberPointer( 367 const DIDerivedType *Ty, 368 codeview::PointerOptions PO = codeview::PointerOptions::None); 369 codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty); 370 codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty); 371 codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty); 372 codeview::TypeIndex lowerTypeMemberFunction( 373 const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment, 374 bool IsStaticMethod, 375 codeview::FunctionOptions FO = codeview::FunctionOptions::None); 376 codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty); 377 codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty); 378 codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty); 379 380 /// Symbol records should point to complete types, but type records should 381 /// always point to incomplete types to avoid cycles in the type graph. Only 382 /// use this entry point when generating symbol records. The complete and 383 /// incomplete type indices only differ for record types. All other types use 384 /// the same index. 385 codeview::TypeIndex getCompleteTypeIndex(DITypeRef TypeRef); 386 387 codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty); 388 codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty); 389 390 struct TypeLoweringScope; 391 392 void emitDeferredCompleteTypes(); 393 394 void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy); 395 ClassInfo collectClassInfo(const DICompositeType *Ty); 396 397 /// Common record member lowering functionality for record types, which are 398 /// structs, classes, and unions. Returns the field list index and the member 399 /// count. 400 std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool> 401 lowerRecordFieldList(const DICompositeType *Ty); 402 403 /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates. 404 codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node, 405 codeview::TypeIndex TI, 406 const DIType *ClassTy = nullptr); 407 408 unsigned getPointerSizeInBytes(); 409 410 protected: 411 /// Gather pre-function debug information. 412 void beginFunctionImpl(const MachineFunction *MF) override; 413 414 /// Gather post-function debug information. 415 void endFunctionImpl(const MachineFunction *) override; 416 417 public: 418 CodeViewDebug(AsmPrinter *AP); 419 420 void setSymbolSize(const MCSymbol *, uint64_t) override {} 421 422 /// Emit the COFF section that holds the line table information. 423 void endModule() override; 424 425 /// Process beginning of an instruction. 426 void beginInstruction(const MachineInstr *MI) override; 427 }; 428 429 } // end namespace llvm 430 431 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H 432