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 /// Two-bit value indicating which register is the designated frame pointer 157 /// register for local variables. Included in S_FRAMEPROC. 158 codeview::EncodedFramePtrReg EncodedLocalFramePtrReg = 159 codeview::EncodedFramePtrReg::None; 160 161 /// Two-bit value indicating which register is the designated frame pointer 162 /// register for stack parameters. Included in S_FRAMEPROC. 163 codeview::EncodedFramePtrReg EncodedParamFramePtrReg = 164 codeview::EncodedFramePtrReg::None; 165 166 codeview::FrameProcedureOptions FrameProcOpts; 167 168 bool HasStackRealignment = false; 169 170 bool HaveLineInfo = false; 171 }; 172 FunctionInfo *CurFn = nullptr; 173 174 // Map used to seperate variables according to the lexical scope they belong 175 // in. This is populated by recordLocalVariable() before 176 // collectLexicalBlocks() separates the variables between the FunctionInfo 177 // and LexicalBlocks. 178 DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables; 179 180 /// The set of comdat .debug$S sections that we've seen so far. Each section 181 /// must start with a magic version number that must only be emitted once. 182 /// This set tracks which sections we've already opened. 183 DenseSet<MCSectionCOFF *> ComdatDebugSections; 184 185 /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol 186 /// of an emitted global value, is in a comdat COFF section, this will switch 187 /// to a new .debug$S section in that comdat. This method ensures that the 188 /// section starts with the magic version number on first use. If GVSym is 189 /// null, uses the main .debug$S section. 190 void switchToDebugSectionForSymbol(const MCSymbol *GVSym); 191 192 /// The next available function index for use with our .cv_* directives. Not 193 /// to be confused with type indices for LF_FUNC_ID records. 194 unsigned NextFuncId = 0; 195 196 InlineSite &getInlineSite(const DILocation *InlinedAt, 197 const DISubprogram *Inlinee); 198 199 codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP); 200 201 void calculateRanges(LocalVariable &Var, 202 const DbgValueHistoryMap::InstrRanges &Ranges); 203 204 static void collectInlineSiteChildren(SmallVectorImpl<unsigned> &Children, 205 const FunctionInfo &FI, 206 const InlineSite &Site); 207 208 /// Remember some debug info about each function. Keep it in a stable order to 209 /// emit at the end of the TU. 210 MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo; 211 212 /// Map from full file path to .cv_file id. Full paths are built from DIFiles 213 /// and are stored in FileToFilepathMap; 214 DenseMap<StringRef, unsigned> FileIdMap; 215 216 /// All inlined subprograms in the order they should be emitted. 217 SmallSetVector<const DISubprogram *, 4> InlinedSubprograms; 218 219 /// Map from a pair of DI metadata nodes and its DI type (or scope) that can 220 /// be nullptr, to CodeView type indices. Primarily indexed by 221 /// {DIType*, DIType*} and {DISubprogram*, DIType*}. 222 /// 223 /// The second entry in the key is needed for methods as DISubroutineType 224 /// representing static method type are shared with non-method function type. 225 DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex> 226 TypeIndices; 227 228 /// Map from DICompositeType* to complete type index. Non-record types are 229 /// always looked up in the normal TypeIndices map. 230 DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices; 231 232 /// Complete record types to emit after all active type lowerings are 233 /// finished. 234 SmallVector<const DICompositeType *, 4> DeferredCompleteTypes; 235 236 /// Number of type lowering frames active on the stack. 237 unsigned TypeEmissionLevel = 0; 238 239 codeview::TypeIndex VBPType; 240 241 const DISubprogram *CurrentSubprogram = nullptr; 242 243 // The UDTs we have seen while processing types; each entry is a pair of type 244 // index and type name. 245 std::vector<std::pair<std::string, const DIType *>> LocalUDTs; 246 std::vector<std::pair<std::string, const DIType *>> GlobalUDTs; 247 248 using FileToFilepathMapTy = std::map<const DIFile *, std::string>; 249 FileToFilepathMapTy FileToFilepathMap; 250 251 StringRef getFullFilepath(const DIFile *File); 252 253 unsigned maybeRecordFile(const DIFile *F); 254 255 void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF); 256 257 void clear(); 258 259 void setCurrentSubprogram(const DISubprogram *SP) { 260 CurrentSubprogram = SP; 261 LocalUDTs.clear(); 262 } 263 264 /// Emit the magic version number at the start of a CodeView type or symbol 265 /// section. Appears at the front of every .debug$S or .debug$T or .debug$P 266 /// section. 267 void emitCodeViewMagicVersion(); 268 269 void emitTypeInformation(); 270 271 void emitTypeGlobalHashes(); 272 273 void emitCompilerInformation(); 274 275 void emitBuildInfo(); 276 277 void emitInlineeLinesSubsection(); 278 279 void emitDebugInfoForThunk(const Function *GV, 280 FunctionInfo &FI, 281 const MCSymbol *Fn); 282 283 void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI); 284 285 void emitDebugInfoForGlobals(); 286 287 void emitDebugInfoForRetainedTypes(); 288 289 void 290 emitDebugInfoForUDTs(ArrayRef<std::pair<std::string, const DIType *>> UDTs); 291 292 void emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, 293 const GlobalVariable *GV, MCSymbol *GVSym); 294 295 /// Opens a subsection of the given kind in a .debug$S codeview section. 296 /// Returns an end label for use with endCVSubsection when the subsection is 297 /// finished. 298 MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind); 299 300 void endCVSubsection(MCSymbol *EndLabel); 301 302 void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt, 303 const InlineSite &Site); 304 305 using InlinedEntity = DbgValueHistoryMap::InlinedEntity; 306 307 void collectVariableInfo(const DISubprogram *SP); 308 309 void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed); 310 311 // Construct the lexical block tree for a routine, pruning emptpy lexical 312 // scopes, and populate it with local variables. 313 void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes, 314 SmallVectorImpl<LexicalBlock *> &Blocks, 315 SmallVectorImpl<LocalVariable> &Locals); 316 void collectLexicalBlockInfo(LexicalScope &Scope, 317 SmallVectorImpl<LexicalBlock *> &ParentBlocks, 318 SmallVectorImpl<LocalVariable> &ParentLocals); 319 320 /// Records information about a local variable in the appropriate scope. In 321 /// particular, locals from inlined code live inside the inlining site. 322 void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS); 323 324 /// Emits local variables in the appropriate order. 325 void emitLocalVariableList(const FunctionInfo &FI, 326 ArrayRef<LocalVariable> Locals); 327 328 /// Emits an S_LOCAL record and its associated defined ranges. 329 void emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var); 330 331 /// Emits a sequence of lexical block scopes and their children. 332 void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks, 333 const FunctionInfo& FI); 334 335 /// Emit a lexical block scope and its children. 336 void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI); 337 338 /// Translates the DIType to codeview if necessary and returns a type index 339 /// for it. 340 codeview::TypeIndex getTypeIndex(DITypeRef TypeRef, 341 DITypeRef ClassTyRef = DITypeRef()); 342 343 codeview::TypeIndex getTypeIndexForReferenceTo(DITypeRef TypeRef); 344 345 codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP, 346 const DICompositeType *Class); 347 348 codeview::TypeIndex getScopeIndex(const DIScope *Scope); 349 350 codeview::TypeIndex getVBPTypeIndex(); 351 352 void addToUDTs(const DIType *Ty); 353 354 void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI); 355 356 codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy); 357 codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty); 358 codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty); 359 codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty); 360 codeview::TypeIndex lowerTypePointer( 361 const DIDerivedType *Ty, 362 codeview::PointerOptions PO = codeview::PointerOptions::None); 363 codeview::TypeIndex lowerTypeMemberPointer( 364 const DIDerivedType *Ty, 365 codeview::PointerOptions PO = codeview::PointerOptions::None); 366 codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty); 367 codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty); 368 codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty); 369 codeview::TypeIndex lowerTypeMemberFunction( 370 const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment, 371 bool IsStaticMethod, 372 codeview::FunctionOptions FO = codeview::FunctionOptions::None); 373 codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty); 374 codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty); 375 codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty); 376 377 /// Symbol records should point to complete types, but type records should 378 /// always point to incomplete types to avoid cycles in the type graph. Only 379 /// use this entry point when generating symbol records. The complete and 380 /// incomplete type indices only differ for record types. All other types use 381 /// the same index. 382 codeview::TypeIndex getCompleteTypeIndex(DITypeRef TypeRef); 383 384 codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty); 385 codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty); 386 387 struct TypeLoweringScope; 388 389 void emitDeferredCompleteTypes(); 390 391 void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy); 392 ClassInfo collectClassInfo(const DICompositeType *Ty); 393 394 /// Common record member lowering functionality for record types, which are 395 /// structs, classes, and unions. Returns the field list index and the member 396 /// count. 397 std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool> 398 lowerRecordFieldList(const DICompositeType *Ty); 399 400 /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates. 401 codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node, 402 codeview::TypeIndex TI, 403 const DIType *ClassTy = nullptr); 404 405 unsigned getPointerSizeInBytes(); 406 407 protected: 408 /// Gather pre-function debug information. 409 void beginFunctionImpl(const MachineFunction *MF) override; 410 411 /// Gather post-function debug information. 412 void endFunctionImpl(const MachineFunction *) override; 413 414 public: 415 CodeViewDebug(AsmPrinter *AP); 416 417 void setSymbolSize(const MCSymbol *, uint64_t) override {} 418 419 /// Emit the COFF section that holds the line table information. 420 void endModule() override; 421 422 /// Process beginning of an instruction. 423 void beginInstruction(const MachineInstr *MI) override; 424 }; 425 426 } // end namespace llvm 427 428 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H 429