1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- 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 #include "CodeViewDebug.h" 15 #include "llvm/ADT/TinyPtrVector.h" 16 #include "llvm/DebugInfo/CodeView/ByteStream.h" 17 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 18 #include "llvm/DebugInfo/CodeView/CodeView.h" 19 #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h" 20 #include "llvm/DebugInfo/CodeView/Line.h" 21 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 22 #include "llvm/DebugInfo/CodeView/TypeDumper.h" 23 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 24 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 25 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/MC/MCExpr.h" 28 #include "llvm/MC/MCSectionCOFF.h" 29 #include "llvm/MC/MCSymbol.h" 30 #include "llvm/Support/COFF.h" 31 #include "llvm/Support/ScopedPrinter.h" 32 #include "llvm/Target/TargetFrameLowering.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 36 using namespace llvm; 37 using namespace llvm::codeview; 38 39 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 40 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) { 41 // If module doesn't have named metadata anchors or COFF debug section 42 // is not available, skip any debug info related stuff. 43 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || 44 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { 45 Asm = nullptr; 46 return; 47 } 48 49 // Tell MMI that we have debug info. 50 MMI->setDebugInfoAvailability(true); 51 } 52 53 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 54 std::string &Filepath = FileToFilepathMap[File]; 55 if (!Filepath.empty()) 56 return Filepath; 57 58 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 59 60 // Clang emits directory and relative filename info into the IR, but CodeView 61 // operates on full paths. We could change Clang to emit full paths too, but 62 // that would increase the IR size and probably not needed for other users. 63 // For now, just concatenate and canonicalize the path here. 64 if (Filename.find(':') == 1) 65 Filepath = Filename; 66 else 67 Filepath = (Dir + "\\" + Filename).str(); 68 69 // Canonicalize the path. We have to do it textually because we may no longer 70 // have access the file in the filesystem. 71 // First, replace all slashes with backslashes. 72 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 73 74 // Remove all "\.\" with "\". 75 size_t Cursor = 0; 76 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 77 Filepath.erase(Cursor, 2); 78 79 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 80 // path should be well-formatted, e.g. start with a drive letter, etc. 81 Cursor = 0; 82 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 83 // Something's wrong if the path starts with "\..\", abort. 84 if (Cursor == 0) 85 break; 86 87 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 88 if (PrevSlash == std::string::npos) 89 // Something's wrong, abort. 90 break; 91 92 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 93 // The next ".." might be following the one we've just erased. 94 Cursor = PrevSlash; 95 } 96 97 // Remove all duplicate backslashes. 98 Cursor = 0; 99 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 100 Filepath.erase(Cursor, 1); 101 102 return Filepath; 103 } 104 105 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 106 unsigned NextId = FileIdMap.size() + 1; 107 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId)); 108 if (Insertion.second) { 109 // We have to compute the full filepath and emit a .cv_file directive. 110 StringRef FullPath = getFullFilepath(F); 111 NextId = OS.EmitCVFileDirective(NextId, FullPath); 112 assert(NextId == FileIdMap.size() && ".cv_file directive failed"); 113 } 114 return Insertion.first->second; 115 } 116 117 CodeViewDebug::InlineSite & 118 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 119 const DISubprogram *Inlinee) { 120 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 121 InlineSite *Site = &SiteInsertion.first->second; 122 if (SiteInsertion.second) { 123 Site->SiteFuncId = NextFuncId++; 124 Site->Inlinee = Inlinee; 125 InlinedSubprograms.insert(Inlinee); 126 getFuncIdForSubprogram(Inlinee); 127 } 128 return *Site; 129 } 130 131 static const DISubprogram *getQualifiedNameComponents( 132 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { 133 const DISubprogram *ClosestSubprogram = nullptr; 134 while (Scope != nullptr) { 135 if (ClosestSubprogram == nullptr) 136 ClosestSubprogram = dyn_cast<DISubprogram>(Scope); 137 StringRef ScopeName = Scope->getName(); 138 if (!ScopeName.empty()) 139 QualifiedNameComponents.push_back(ScopeName); 140 Scope = Scope->getScope().resolve(); 141 } 142 return ClosestSubprogram; 143 } 144 145 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents, 146 StringRef TypeName) { 147 std::string FullyQualifiedName; 148 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) { 149 FullyQualifiedName.append(QualifiedNameComponent); 150 FullyQualifiedName.append("::"); 151 } 152 FullyQualifiedName.append(TypeName); 153 return FullyQualifiedName; 154 } 155 156 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) { 157 SmallVector<StringRef, 5> QualifiedNameComponents; 158 getQualifiedNameComponents(Scope, QualifiedNameComponents); 159 return getQualifiedName(QualifiedNameComponents, Name); 160 } 161 162 struct CodeViewDebug::TypeLoweringScope { 163 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; } 164 ~TypeLoweringScope() { 165 // Don't decrement TypeEmissionLevel until after emitting deferred types, so 166 // inner TypeLoweringScopes don't attempt to emit deferred types. 167 if (CVD.TypeEmissionLevel == 1) 168 CVD.emitDeferredCompleteTypes(); 169 --CVD.TypeEmissionLevel; 170 } 171 CodeViewDebug &CVD; 172 }; 173 174 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) { 175 // No scope means global scope and that uses the zero index. 176 if (!Scope || isa<DIFile>(Scope)) 177 return TypeIndex(); 178 179 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"); 180 181 // Check if we've already translated this scope. 182 auto I = TypeIndices.find({Scope, nullptr}); 183 if (I != TypeIndices.end()) 184 return I->second; 185 186 // Build the fully qualified name of the scope. 187 std::string ScopeName = 188 getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName()); 189 TypeIndex TI = 190 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName)); 191 return recordTypeIndexForDINode(Scope, TI); 192 } 193 194 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 195 // It's possible to ask for the FuncId of a function which doesn't have a 196 // subprogram: inlining a function with debug info into a function with none. 197 if (!SP) 198 return TypeIndex::None(); 199 200 // Check if we've already translated this subprogram. 201 auto I = TypeIndices.find({SP, nullptr}); 202 if (I != TypeIndices.end()) 203 return I->second; 204 205 // The display name includes function template arguments. Drop them to match 206 // MSVC. 207 StringRef DisplayName = SP->getDisplayName().split('<').first; 208 209 const DIScope *Scope = SP->getScope().resolve(); 210 TypeIndex TI; 211 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) { 212 // If the scope is a DICompositeType, then this must be a method. Member 213 // function types take some special handling, and require access to the 214 // subprogram. 215 TypeIndex ClassType = getTypeIndex(Class); 216 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class), 217 DisplayName); 218 TI = TypeTable.writeMemberFuncId(MFuncId); 219 } else { 220 // Otherwise, this must be a free function. 221 TypeIndex ParentScope = getScopeIndex(Scope); 222 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); 223 TI = TypeTable.writeFuncId(FuncId); 224 } 225 226 return recordTypeIndexForDINode(SP, TI); 227 } 228 229 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP, 230 const DICompositeType *Class) { 231 // Always use the method declaration as the key for the function type. The 232 // method declaration contains the this adjustment. 233 if (SP->getDeclaration()) 234 SP = SP->getDeclaration(); 235 assert(!SP->getDeclaration() && "should use declaration as key"); 236 237 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide 238 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. 239 auto I = TypeIndices.find({SP, Class}); 240 if (I != TypeIndices.end()) 241 return I->second; 242 243 // Make sure complete type info for the class is emitted *after* the member 244 // function type, as the complete class type is likely to reference this 245 // member function type. 246 TypeLoweringScope S(*this); 247 TypeIndex TI = 248 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment()); 249 return recordTypeIndexForDINode(SP, TI, Class); 250 } 251 252 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI, 253 const DIType *ClassTy) { 254 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); 255 (void)InsertResult; 256 assert(InsertResult.second && "DINode was already assigned a type index"); 257 return TI; 258 } 259 260 unsigned CodeViewDebug::getPointerSizeInBytes() { 261 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; 262 } 263 264 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 265 const DILocation *InlinedAt) { 266 if (InlinedAt) { 267 // This variable was inlined. Associate it with the InlineSite. 268 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 269 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 270 Site.InlinedLocals.emplace_back(Var); 271 } else { 272 // This variable goes in the main ProcSym. 273 CurFn->Locals.emplace_back(Var); 274 } 275 } 276 277 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 278 const DILocation *Loc) { 279 auto B = Locs.begin(), E = Locs.end(); 280 if (std::find(B, E, Loc) == E) 281 Locs.push_back(Loc); 282 } 283 284 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, 285 const MachineFunction *MF) { 286 // Skip this instruction if it has the same location as the previous one. 287 if (DL == CurFn->LastLoc) 288 return; 289 290 const DIScope *Scope = DL.get()->getScope(); 291 if (!Scope) 292 return; 293 294 // Skip this line if it is longer than the maximum we can record. 295 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 296 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 297 LI.isNeverStepInto()) 298 return; 299 300 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 301 if (CI.getStartColumn() != DL.getCol()) 302 return; 303 304 if (!CurFn->HaveLineInfo) 305 CurFn->HaveLineInfo = true; 306 unsigned FileId = 0; 307 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 308 FileId = CurFn->LastFileId; 309 else 310 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 311 CurFn->LastLoc = DL; 312 313 unsigned FuncId = CurFn->FuncId; 314 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 315 const DILocation *Loc = DL.get(); 316 317 // If this location was actually inlined from somewhere else, give it the ID 318 // of the inline call site. 319 FuncId = 320 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 321 322 // Ensure we have links in the tree of inline call sites. 323 bool FirstLoc = true; 324 while ((SiteLoc = Loc->getInlinedAt())) { 325 InlineSite &Site = 326 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 327 if (!FirstLoc) 328 addLocIfNotPresent(Site.ChildSites, Loc); 329 FirstLoc = false; 330 Loc = SiteLoc; 331 } 332 addLocIfNotPresent(CurFn->ChildSites, Loc); 333 } 334 335 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 336 /*PrologueEnd=*/false, 337 /*IsStmt=*/false, DL->getFilename()); 338 } 339 340 void CodeViewDebug::emitCodeViewMagicVersion() { 341 OS.EmitValueToAlignment(4); 342 OS.AddComment("Debug section magic"); 343 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 344 } 345 346 void CodeViewDebug::endModule() { 347 if (!Asm || !MMI->hasDebugInfo()) 348 return; 349 350 assert(Asm != nullptr); 351 352 // The COFF .debug$S section consists of several subsections, each starting 353 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 354 // of the payload followed by the payload itself. The subsections are 4-byte 355 // aligned. 356 357 // Use the generic .debug$S section, and make a subsection for all the inlined 358 // subprograms. 359 switchToDebugSectionForSymbol(nullptr); 360 emitInlineeLinesSubsection(); 361 362 // Emit per-function debug information. 363 for (auto &P : FnDebugInfo) 364 if (!P.first->isDeclarationForLinker()) 365 emitDebugInfoForFunction(P.first, P.second); 366 367 // Emit global variable debug information. 368 setCurrentSubprogram(nullptr); 369 emitDebugInfoForGlobals(); 370 371 // Emit retained types. 372 emitDebugInfoForRetainedTypes(); 373 374 // Switch back to the generic .debug$S section after potentially processing 375 // comdat symbol sections. 376 switchToDebugSectionForSymbol(nullptr); 377 378 // Emit UDT records for any types used by global variables. 379 if (!GlobalUDTs.empty()) { 380 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols); 381 emitDebugInfoForUDTs(GlobalUDTs); 382 endCVSubsection(SymbolsEnd); 383 } 384 385 // This subsection holds a file index to offset in string table table. 386 OS.AddComment("File index to string table offset subsection"); 387 OS.EmitCVFileChecksumsDirective(); 388 389 // This subsection holds the string table. 390 OS.AddComment("String table"); 391 OS.EmitCVStringTableDirective(); 392 393 // Emit type information last, so that any types we translate while emitting 394 // function info are included. 395 emitTypeInformation(); 396 397 clear(); 398 } 399 400 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 401 // Microsoft's linker seems to have trouble with symbol names longer than 402 // 0xffd8 bytes. 403 S = S.substr(0, 0xffd8); 404 SmallString<32> NullTerminatedString(S); 405 NullTerminatedString.push_back('\0'); 406 OS.EmitBytes(NullTerminatedString); 407 } 408 409 void CodeViewDebug::emitTypeInformation() { 410 // Do nothing if we have no debug info or if no non-trivial types were emitted 411 // to TypeTable during codegen. 412 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 413 if (!CU_Nodes) 414 return; 415 if (TypeTable.empty()) 416 return; 417 418 // Start the .debug$T section with 0x4. 419 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 420 emitCodeViewMagicVersion(); 421 422 SmallString<8> CommentPrefix; 423 if (OS.isVerboseAsm()) { 424 CommentPrefix += '\t'; 425 CommentPrefix += Asm->MAI->getCommentString(); 426 CommentPrefix += ' '; 427 } 428 429 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false); 430 TypeTable.ForEachRecord( 431 [&](TypeIndex Index, StringRef Record) { 432 if (OS.isVerboseAsm()) { 433 // Emit a block comment describing the type record for readability. 434 SmallString<512> CommentBlock; 435 raw_svector_ostream CommentOS(CommentBlock); 436 ScopedPrinter SP(CommentOS); 437 SP.setPrefix(CommentPrefix); 438 CVTD.setPrinter(&SP); 439 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()}); 440 if (E) { 441 logAllUnhandledErrors(std::move(E), errs(), "error: "); 442 llvm_unreachable("produced malformed type record"); 443 } 444 // emitRawComment will insert its own tab and comment string before 445 // the first line, so strip off our first one. It also prints its own 446 // newline. 447 OS.emitRawComment( 448 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim()); 449 } else { 450 #ifndef NDEBUG 451 // Assert that the type data is valid even if we aren't dumping 452 // comments. The MSVC linker doesn't do much type record validation, 453 // so the first link of an invalid type record can succeed while 454 // subsequent links will fail with LNK1285. 455 ByteStream<> Stream({Record.bytes_begin(), Record.bytes_end()}); 456 CVTypeArray Types; 457 StreamReader Reader(Stream); 458 Error E = Reader.readArray(Types, Reader.getLength()); 459 if (!E) { 460 TypeVisitorCallbacks C; 461 E = CVTypeVisitor(C).visitTypeStream(Types); 462 } 463 if (E) { 464 logAllUnhandledErrors(std::move(E), errs(), "error: "); 465 llvm_unreachable("produced malformed type record"); 466 } 467 #endif 468 } 469 OS.EmitBinaryData(Record); 470 }); 471 } 472 473 void CodeViewDebug::emitInlineeLinesSubsection() { 474 if (InlinedSubprograms.empty()) 475 return; 476 477 OS.AddComment("Inlinee lines subsection"); 478 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines); 479 480 // We don't provide any extra file info. 481 // FIXME: Find out if debuggers use this info. 482 OS.AddComment("Inlinee lines signature"); 483 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 484 485 for (const DISubprogram *SP : InlinedSubprograms) { 486 assert(TypeIndices.count({SP, nullptr})); 487 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 488 489 OS.AddBlankLine(); 490 unsigned FileId = maybeRecordFile(SP->getFile()); 491 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 492 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 493 OS.AddBlankLine(); 494 // The filechecksum table uses 8 byte entries for now, and file ids start at 495 // 1. 496 unsigned FileOffset = (FileId - 1) * 8; 497 OS.AddComment("Type index of inlined function"); 498 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 499 OS.AddComment("Offset into filechecksum table"); 500 OS.EmitIntValue(FileOffset, 4); 501 OS.AddComment("Starting line number"); 502 OS.EmitIntValue(SP->getLine(), 4); 503 } 504 505 endCVSubsection(InlineEnd); 506 } 507 508 void CodeViewDebug::collectInlineSiteChildren( 509 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 510 const InlineSite &Site) { 511 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 512 auto I = FI.InlineSites.find(ChildSiteLoc); 513 const InlineSite &ChildSite = I->second; 514 Children.push_back(ChildSite.SiteFuncId); 515 collectInlineSiteChildren(Children, FI, ChildSite); 516 } 517 } 518 519 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 520 const DILocation *InlinedAt, 521 const InlineSite &Site) { 522 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 523 *InlineEnd = MMI->getContext().createTempSymbol(); 524 525 assert(TypeIndices.count({Site.Inlinee, nullptr})); 526 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 527 528 // SymbolRecord 529 OS.AddComment("Record length"); 530 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 531 OS.EmitLabel(InlineBegin); 532 OS.AddComment("Record kind: S_INLINESITE"); 533 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind 534 535 OS.AddComment("PtrParent"); 536 OS.EmitIntValue(0, 4); 537 OS.AddComment("PtrEnd"); 538 OS.EmitIntValue(0, 4); 539 OS.AddComment("Inlinee type index"); 540 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 541 542 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 543 unsigned StartLineNum = Site.Inlinee->getLine(); 544 SmallVector<unsigned, 3> SecondaryFuncIds; 545 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 546 547 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 548 FI.Begin, FI.End, SecondaryFuncIds); 549 550 OS.EmitLabel(InlineEnd); 551 552 emitLocalVariableList(Site.InlinedLocals); 553 554 // Recurse on child inlined call sites before closing the scope. 555 for (const DILocation *ChildSite : Site.ChildSites) { 556 auto I = FI.InlineSites.find(ChildSite); 557 assert(I != FI.InlineSites.end() && 558 "child site not in function inline site map"); 559 emitInlinedCallSite(FI, ChildSite, I->second); 560 } 561 562 // Close the scope. 563 OS.AddComment("Record length"); 564 OS.EmitIntValue(2, 2); // RecordLength 565 OS.AddComment("Record kind: S_INLINESITE_END"); 566 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind 567 } 568 569 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 570 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 571 // comdat key. A section may be comdat because of -ffunction-sections or 572 // because it is comdat in the IR. 573 MCSectionCOFF *GVSec = 574 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 575 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 576 577 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 578 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 579 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 580 581 OS.SwitchSection(DebugSec); 582 583 // Emit the magic version number if this is the first time we've switched to 584 // this section. 585 if (ComdatDebugSections.insert(DebugSec).second) 586 emitCodeViewMagicVersion(); 587 } 588 589 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 590 FunctionInfo &FI) { 591 // For each function there is a separate subsection 592 // which holds the PC to file:line table. 593 const MCSymbol *Fn = Asm->getSymbol(GV); 594 assert(Fn); 595 596 // Switch to the to a comdat section, if appropriate. 597 switchToDebugSectionForSymbol(Fn); 598 599 std::string FuncName; 600 auto *SP = GV->getSubprogram(); 601 setCurrentSubprogram(SP); 602 603 // If we have a display name, build the fully qualified name by walking the 604 // chain of scopes. 605 if (SP != nullptr && !SP->getDisplayName().empty()) 606 FuncName = 607 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName()); 608 609 // If our DISubprogram name is empty, use the mangled name. 610 if (FuncName.empty()) 611 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 612 613 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 614 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 615 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols); 616 { 617 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 618 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 619 OS.AddComment("Record length"); 620 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 621 OS.EmitLabel(ProcRecordBegin); 622 623 OS.AddComment("Record kind: S_GPROC32_ID"); 624 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2); 625 626 // These fields are filled in by tools like CVPACK which run after the fact. 627 OS.AddComment("PtrParent"); 628 OS.EmitIntValue(0, 4); 629 OS.AddComment("PtrEnd"); 630 OS.EmitIntValue(0, 4); 631 OS.AddComment("PtrNext"); 632 OS.EmitIntValue(0, 4); 633 // This is the important bit that tells the debugger where the function 634 // code is located and what's its size: 635 OS.AddComment("Code size"); 636 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 637 OS.AddComment("Offset after prologue"); 638 OS.EmitIntValue(0, 4); 639 OS.AddComment("Offset before epilogue"); 640 OS.EmitIntValue(0, 4); 641 OS.AddComment("Function type index"); 642 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4); 643 OS.AddComment("Function section relative address"); 644 OS.EmitCOFFSecRel32(Fn); 645 OS.AddComment("Function section index"); 646 OS.EmitCOFFSectionIndex(Fn); 647 OS.AddComment("Flags"); 648 OS.EmitIntValue(0, 1); 649 // Emit the function display name as a null-terminated string. 650 OS.AddComment("Function name"); 651 // Truncate the name so we won't overflow the record length field. 652 emitNullTerminatedSymbolName(OS, FuncName); 653 OS.EmitLabel(ProcRecordEnd); 654 655 emitLocalVariableList(FI.Locals); 656 657 // Emit inlined call site information. Only emit functions inlined directly 658 // into the parent function. We'll emit the other sites recursively as part 659 // of their parent inline site. 660 for (const DILocation *InlinedAt : FI.ChildSites) { 661 auto I = FI.InlineSites.find(InlinedAt); 662 assert(I != FI.InlineSites.end() && 663 "child site not in function inline site map"); 664 emitInlinedCallSite(FI, InlinedAt, I->second); 665 } 666 667 if (SP != nullptr) 668 emitDebugInfoForUDTs(LocalUDTs); 669 670 // We're done with this function. 671 OS.AddComment("Record length"); 672 OS.EmitIntValue(0x0002, 2); 673 OS.AddComment("Record kind: S_PROC_ID_END"); 674 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2); 675 } 676 endCVSubsection(SymbolsEnd); 677 678 // We have an assembler directive that takes care of the whole line table. 679 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 680 } 681 682 CodeViewDebug::LocalVarDefRange 683 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 684 LocalVarDefRange DR; 685 DR.InMemory = -1; 686 DR.DataOffset = Offset; 687 assert(DR.DataOffset == Offset && "truncation"); 688 DR.StructOffset = 0; 689 DR.CVRegister = CVRegister; 690 return DR; 691 } 692 693 CodeViewDebug::LocalVarDefRange 694 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 695 LocalVarDefRange DR; 696 DR.InMemory = 0; 697 DR.DataOffset = 0; 698 DR.StructOffset = 0; 699 DR.CVRegister = CVRegister; 700 return DR; 701 } 702 703 void CodeViewDebug::collectVariableInfoFromMMITable( 704 DenseSet<InlinedVariable> &Processed) { 705 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 706 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 707 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 708 709 for (const MachineModuleInfo::VariableDbgInfo &VI : 710 MMI->getVariableDbgInfo()) { 711 if (!VI.Var) 712 continue; 713 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 714 "Expected inlined-at fields to agree"); 715 716 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 717 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 718 719 // If variable scope is not found then skip this variable. 720 if (!Scope) 721 continue; 722 723 // Get the frame register used and the offset. 724 unsigned FrameReg = 0; 725 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 726 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 727 728 // Calculate the label ranges. 729 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 730 for (const InsnRange &Range : Scope->getRanges()) { 731 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 732 const MCSymbol *End = getLabelAfterInsn(Range.second); 733 End = End ? End : Asm->getFunctionEnd(); 734 DefRange.Ranges.emplace_back(Begin, End); 735 } 736 737 LocalVariable Var; 738 Var.DIVar = VI.Var; 739 Var.DefRanges.emplace_back(std::move(DefRange)); 740 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 741 } 742 } 743 744 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 745 DenseSet<InlinedVariable> Processed; 746 // Grab the variable info that was squirreled away in the MMI side-table. 747 collectVariableInfoFromMMITable(Processed); 748 749 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 750 751 for (const auto &I : DbgValues) { 752 InlinedVariable IV = I.first; 753 if (Processed.count(IV)) 754 continue; 755 const DILocalVariable *DIVar = IV.first; 756 const DILocation *InlinedAt = IV.second; 757 758 // Instruction ranges, specifying where IV is accessible. 759 const auto &Ranges = I.second; 760 761 LexicalScope *Scope = nullptr; 762 if (InlinedAt) 763 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 764 else 765 Scope = LScopes.findLexicalScope(DIVar->getScope()); 766 // If variable scope is not found then skip this variable. 767 if (!Scope) 768 continue; 769 770 LocalVariable Var; 771 Var.DIVar = DIVar; 772 773 // Calculate the definition ranges. 774 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 775 const InsnRange &Range = *I; 776 const MachineInstr *DVInst = Range.first; 777 assert(DVInst->isDebugValue() && "Invalid History entry"); 778 const DIExpression *DIExpr = DVInst->getDebugExpression(); 779 780 // Bail if there is a complex DWARF expression for now. 781 if (DIExpr && DIExpr->getNumElements() > 0) 782 continue; 783 784 // Bail if operand 0 is not a valid register. This means the variable is a 785 // simple constant, or is described by a complex expression. 786 // FIXME: Find a way to represent constant variables, since they are 787 // relatively common. 788 unsigned Reg = 789 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 790 if (Reg == 0) 791 continue; 792 793 // Handle the two cases we can handle: indirect in memory and in register. 794 bool IsIndirect = DVInst->getOperand(1).isImm(); 795 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 796 { 797 LocalVarDefRange DefRange; 798 if (IsIndirect) { 799 int64_t Offset = DVInst->getOperand(1).getImm(); 800 DefRange = createDefRangeMem(CVReg, Offset); 801 } else { 802 DefRange = createDefRangeReg(CVReg); 803 } 804 if (Var.DefRanges.empty() || 805 Var.DefRanges.back().isDifferentLocation(DefRange)) { 806 Var.DefRanges.emplace_back(std::move(DefRange)); 807 } 808 } 809 810 // Compute the label range. 811 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 812 const MCSymbol *End = getLabelAfterInsn(Range.second); 813 if (!End) { 814 if (std::next(I) != E) 815 End = getLabelBeforeInsn(std::next(I)->first); 816 else 817 End = Asm->getFunctionEnd(); 818 } 819 820 // If the last range end is our begin, just extend the last range. 821 // Otherwise make a new range. 822 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 823 Var.DefRanges.back().Ranges; 824 if (!Ranges.empty() && Ranges.back().second == Begin) 825 Ranges.back().second = End; 826 else 827 Ranges.emplace_back(Begin, End); 828 829 // FIXME: Do more range combining. 830 } 831 832 recordLocalVariable(std::move(Var), InlinedAt); 833 } 834 } 835 836 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 837 assert(!CurFn && "Can't process two functions at once!"); 838 839 if (!Asm || !MMI->hasDebugInfo()) 840 return; 841 842 DebugHandlerBase::beginFunction(MF); 843 844 const Function *GV = MF->getFunction(); 845 assert(FnDebugInfo.count(GV) == false); 846 CurFn = &FnDebugInfo[GV]; 847 CurFn->FuncId = NextFuncId++; 848 CurFn->Begin = Asm->getFunctionBegin(); 849 850 // Find the end of the function prolog. First known non-DBG_VALUE and 851 // non-frame setup location marks the beginning of the function body. 852 // FIXME: is there a simpler a way to do this? Can we just search 853 // for the first instruction of the function, not the last of the prolog? 854 DebugLoc PrologEndLoc; 855 bool EmptyPrologue = true; 856 for (const auto &MBB : *MF) { 857 for (const auto &MI : MBB) { 858 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 859 MI.getDebugLoc()) { 860 PrologEndLoc = MI.getDebugLoc(); 861 break; 862 } else if (!MI.isDebugValue()) { 863 EmptyPrologue = false; 864 } 865 } 866 } 867 868 // Record beginning of function if we have a non-empty prologue. 869 if (PrologEndLoc && !EmptyPrologue) { 870 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 871 maybeRecordLocation(FnStartDL, MF); 872 } 873 } 874 875 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) { 876 SmallVector<StringRef, 5> QualifiedNameComponents; 877 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents( 878 Ty->getScope().resolve(), QualifiedNameComponents); 879 880 std::string FullyQualifiedName = 881 getQualifiedName(QualifiedNameComponents, Ty->getName()); 882 883 if (ClosestSubprogram == nullptr) 884 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI); 885 else if (ClosestSubprogram == CurrentSubprogram) 886 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI); 887 888 // TODO: What if the ClosestSubprogram is neither null or the current 889 // subprogram? Currently, the UDT just gets dropped on the floor. 890 // 891 // The current behavior is not desirable. To get maximal fidelity, we would 892 // need to perform all type translation before beginning emission of .debug$S 893 // and then make LocalUDTs a member of FunctionInfo 894 } 895 896 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 897 // Generic dispatch for lowering an unknown type. 898 switch (Ty->getTag()) { 899 case dwarf::DW_TAG_array_type: 900 return lowerTypeArray(cast<DICompositeType>(Ty)); 901 case dwarf::DW_TAG_typedef: 902 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 903 case dwarf::DW_TAG_base_type: 904 return lowerTypeBasic(cast<DIBasicType>(Ty)); 905 case dwarf::DW_TAG_pointer_type: 906 case dwarf::DW_TAG_reference_type: 907 case dwarf::DW_TAG_rvalue_reference_type: 908 return lowerTypePointer(cast<DIDerivedType>(Ty)); 909 case dwarf::DW_TAG_ptr_to_member_type: 910 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 911 case dwarf::DW_TAG_const_type: 912 case dwarf::DW_TAG_volatile_type: 913 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 914 case dwarf::DW_TAG_subroutine_type: 915 if (ClassTy) { 916 // The member function type of a member function pointer has no 917 // ThisAdjustment. 918 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, 919 /*ThisAdjustment=*/0); 920 } 921 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 922 case dwarf::DW_TAG_enumeration_type: 923 return lowerTypeEnum(cast<DICompositeType>(Ty)); 924 case dwarf::DW_TAG_class_type: 925 case dwarf::DW_TAG_structure_type: 926 return lowerTypeClass(cast<DICompositeType>(Ty)); 927 case dwarf::DW_TAG_union_type: 928 return lowerTypeUnion(cast<DICompositeType>(Ty)); 929 default: 930 // Use the null type index. 931 return TypeIndex(); 932 } 933 } 934 935 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 936 DITypeRef UnderlyingTypeRef = Ty->getBaseType(); 937 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef); 938 StringRef TypeName = Ty->getName(); 939 940 addToUDTs(Ty, UnderlyingTypeIndex); 941 942 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 943 TypeName == "HRESULT") 944 return TypeIndex(SimpleTypeKind::HResult); 945 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 946 TypeName == "wchar_t") 947 return TypeIndex(SimpleTypeKind::WideCharacter); 948 949 return UnderlyingTypeIndex; 950 } 951 952 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 953 DITypeRef ElementTypeRef = Ty->getBaseType(); 954 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef); 955 // IndexType is size_t, which depends on the bitness of the target. 956 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8 957 ? TypeIndex(SimpleTypeKind::UInt64Quad) 958 : TypeIndex(SimpleTypeKind::UInt32Long); 959 uint64_t Size = Ty->getSizeInBits() / 8; 960 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName()); 961 return TypeTable.writeArray(Record); 962 } 963 964 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 965 TypeIndex Index; 966 dwarf::TypeKind Kind; 967 uint32_t ByteSize; 968 969 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 970 ByteSize = Ty->getSizeInBits() / 8; 971 972 SimpleTypeKind STK = SimpleTypeKind::None; 973 switch (Kind) { 974 case dwarf::DW_ATE_address: 975 // FIXME: Translate 976 break; 977 case dwarf::DW_ATE_boolean: 978 switch (ByteSize) { 979 case 1: STK = SimpleTypeKind::Boolean8; break; 980 case 2: STK = SimpleTypeKind::Boolean16; break; 981 case 4: STK = SimpleTypeKind::Boolean32; break; 982 case 8: STK = SimpleTypeKind::Boolean64; break; 983 case 16: STK = SimpleTypeKind::Boolean128; break; 984 } 985 break; 986 case dwarf::DW_ATE_complex_float: 987 switch (ByteSize) { 988 case 2: STK = SimpleTypeKind::Complex16; break; 989 case 4: STK = SimpleTypeKind::Complex32; break; 990 case 8: STK = SimpleTypeKind::Complex64; break; 991 case 10: STK = SimpleTypeKind::Complex80; break; 992 case 16: STK = SimpleTypeKind::Complex128; break; 993 } 994 break; 995 case dwarf::DW_ATE_float: 996 switch (ByteSize) { 997 case 2: STK = SimpleTypeKind::Float16; break; 998 case 4: STK = SimpleTypeKind::Float32; break; 999 case 6: STK = SimpleTypeKind::Float48; break; 1000 case 8: STK = SimpleTypeKind::Float64; break; 1001 case 10: STK = SimpleTypeKind::Float80; break; 1002 case 16: STK = SimpleTypeKind::Float128; break; 1003 } 1004 break; 1005 case dwarf::DW_ATE_signed: 1006 switch (ByteSize) { 1007 case 1: STK = SimpleTypeKind::SByte; break; 1008 case 2: STK = SimpleTypeKind::Int16Short; break; 1009 case 4: STK = SimpleTypeKind::Int32; break; 1010 case 8: STK = SimpleTypeKind::Int64Quad; break; 1011 case 16: STK = SimpleTypeKind::Int128Oct; break; 1012 } 1013 break; 1014 case dwarf::DW_ATE_unsigned: 1015 switch (ByteSize) { 1016 case 1: STK = SimpleTypeKind::Byte; break; 1017 case 2: STK = SimpleTypeKind::UInt16Short; break; 1018 case 4: STK = SimpleTypeKind::UInt32; break; 1019 case 8: STK = SimpleTypeKind::UInt64Quad; break; 1020 case 16: STK = SimpleTypeKind::UInt128Oct; break; 1021 } 1022 break; 1023 case dwarf::DW_ATE_UTF: 1024 switch (ByteSize) { 1025 case 2: STK = SimpleTypeKind::Character16; break; 1026 case 4: STK = SimpleTypeKind::Character32; break; 1027 } 1028 break; 1029 case dwarf::DW_ATE_signed_char: 1030 if (ByteSize == 1) 1031 STK = SimpleTypeKind::SignedCharacter; 1032 break; 1033 case dwarf::DW_ATE_unsigned_char: 1034 if (ByteSize == 1) 1035 STK = SimpleTypeKind::UnsignedCharacter; 1036 break; 1037 default: 1038 break; 1039 } 1040 1041 // Apply some fixups based on the source-level type name. 1042 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 1043 STK = SimpleTypeKind::Int32Long; 1044 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 1045 STK = SimpleTypeKind::UInt32Long; 1046 if (STK == SimpleTypeKind::UInt16Short && 1047 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 1048 STK = SimpleTypeKind::WideCharacter; 1049 if ((STK == SimpleTypeKind::SignedCharacter || 1050 STK == SimpleTypeKind::UnsignedCharacter) && 1051 Ty->getName() == "char") 1052 STK = SimpleTypeKind::NarrowCharacter; 1053 1054 return TypeIndex(STK); 1055 } 1056 1057 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) { 1058 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 1059 1060 // While processing the type being pointed to it is possible we already 1061 // created this pointer type. If so, we check here and return the existing 1062 // pointer type. 1063 auto I = TypeIndices.find({Ty, nullptr}); 1064 if (I != TypeIndices.end()) 1065 return I->second; 1066 1067 // Pointers to simple types can use SimpleTypeMode, rather than having a 1068 // dedicated pointer type record. 1069 if (PointeeTI.isSimple() && 1070 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 1071 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 1072 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 1073 ? SimpleTypeMode::NearPointer64 1074 : SimpleTypeMode::NearPointer32; 1075 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 1076 } 1077 1078 PointerKind PK = 1079 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 1080 PointerMode PM = PointerMode::Pointer; 1081 switch (Ty->getTag()) { 1082 default: llvm_unreachable("not a pointer tag type"); 1083 case dwarf::DW_TAG_pointer_type: 1084 PM = PointerMode::Pointer; 1085 break; 1086 case dwarf::DW_TAG_reference_type: 1087 PM = PointerMode::LValueReference; 1088 break; 1089 case dwarf::DW_TAG_rvalue_reference_type: 1090 PM = PointerMode::RValueReference; 1091 break; 1092 } 1093 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method 1094 // 'this' pointer, but not normal contexts. Figure out what we're supposed to 1095 // do. 1096 PointerOptions PO = PointerOptions::None; 1097 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 1098 return TypeTable.writePointer(PR); 1099 } 1100 1101 static PointerToMemberRepresentation 1102 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 1103 // SizeInBytes being zero generally implies that the member pointer type was 1104 // incomplete, which can happen if it is part of a function prototype. In this 1105 // case, use the unknown model instead of the general model. 1106 if (IsPMF) { 1107 switch (Flags & DINode::FlagPtrToMemberRep) { 1108 case 0: 1109 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1110 : PointerToMemberRepresentation::GeneralFunction; 1111 case DINode::FlagSingleInheritance: 1112 return PointerToMemberRepresentation::SingleInheritanceFunction; 1113 case DINode::FlagMultipleInheritance: 1114 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1115 case DINode::FlagVirtualInheritance: 1116 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1117 } 1118 } else { 1119 switch (Flags & DINode::FlagPtrToMemberRep) { 1120 case 0: 1121 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1122 : PointerToMemberRepresentation::GeneralData; 1123 case DINode::FlagSingleInheritance: 1124 return PointerToMemberRepresentation::SingleInheritanceData; 1125 case DINode::FlagMultipleInheritance: 1126 return PointerToMemberRepresentation::MultipleInheritanceData; 1127 case DINode::FlagVirtualInheritance: 1128 return PointerToMemberRepresentation::VirtualInheritanceData; 1129 } 1130 } 1131 llvm_unreachable("invalid ptr to member representation"); 1132 } 1133 1134 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) { 1135 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1136 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1137 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType()); 1138 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64 1139 : PointerKind::Near32; 1140 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1141 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1142 : PointerMode::PointerToDataMember; 1143 PointerOptions PO = PointerOptions::None; // FIXME 1144 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1145 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1146 MemberPointerInfo MPI( 1147 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1148 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1149 return TypeTable.writePointer(PR); 1150 } 1151 1152 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1153 /// have a translation, use the NearC convention. 1154 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1155 switch (DwarfCC) { 1156 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1157 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1158 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1159 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1160 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1161 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 1162 } 1163 return CallingConvention::NearC; 1164 } 1165 1166 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 1167 ModifierOptions Mods = ModifierOptions::None; 1168 bool IsModifier = true; 1169 const DIType *BaseTy = Ty; 1170 while (IsModifier && BaseTy) { 1171 // FIXME: Need to add DWARF tag for __unaligned. 1172 switch (BaseTy->getTag()) { 1173 case dwarf::DW_TAG_const_type: 1174 Mods |= ModifierOptions::Const; 1175 break; 1176 case dwarf::DW_TAG_volatile_type: 1177 Mods |= ModifierOptions::Volatile; 1178 break; 1179 default: 1180 IsModifier = false; 1181 break; 1182 } 1183 if (IsModifier) 1184 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve(); 1185 } 1186 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 1187 1188 // While processing the type being pointed to, it is possible we already 1189 // created this modifier type. If so, we check here and return the existing 1190 // modifier type. 1191 auto I = TypeIndices.find({Ty, nullptr}); 1192 if (I != TypeIndices.end()) 1193 return I->second; 1194 1195 ModifierRecord MR(ModifiedTI, Mods); 1196 return TypeTable.writeModifier(MR); 1197 } 1198 1199 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 1200 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1201 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1202 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1203 1204 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1205 ArrayRef<TypeIndex> ArgTypeIndices = None; 1206 if (!ReturnAndArgTypeIndices.empty()) { 1207 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1208 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1209 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1210 } 1211 1212 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1213 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 1214 1215 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1216 1217 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None, 1218 ArgTypeIndices.size(), ArgListIndex); 1219 return TypeTable.writeProcedure(Procedure); 1220 } 1221 1222 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 1223 const DIType *ClassTy, 1224 int ThisAdjustment) { 1225 // Lower the containing class type. 1226 TypeIndex ClassType = getTypeIndex(ClassTy); 1227 1228 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1229 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1230 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1231 1232 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1233 ArrayRef<TypeIndex> ArgTypeIndices = None; 1234 if (!ReturnAndArgTypeIndices.empty()) { 1235 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1236 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1237 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1238 } 1239 TypeIndex ThisTypeIndex = TypeIndex::Void(); 1240 if (!ArgTypeIndices.empty()) { 1241 ThisTypeIndex = ArgTypeIndices.front(); 1242 ArgTypeIndices = ArgTypeIndices.drop_front(); 1243 } 1244 1245 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1246 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 1247 1248 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1249 1250 // TODO: Need to use the correct values for: 1251 // FunctionOptions 1252 // ThisPointerAdjustment. 1253 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord( 1254 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None, 1255 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment)); 1256 1257 return TI; 1258 } 1259 1260 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 1261 switch (Flags & DINode::FlagAccessibility) { 1262 case DINode::FlagPrivate: return MemberAccess::Private; 1263 case DINode::FlagPublic: return MemberAccess::Public; 1264 case DINode::FlagProtected: return MemberAccess::Protected; 1265 case 0: 1266 // If there was no explicit access control, provide the default for the tag. 1267 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 1268 : MemberAccess::Public; 1269 } 1270 llvm_unreachable("access flags are exclusive"); 1271 } 1272 1273 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 1274 if (SP->isArtificial()) 1275 return MethodOptions::CompilerGenerated; 1276 1277 // FIXME: Handle other MethodOptions. 1278 1279 return MethodOptions::None; 1280 } 1281 1282 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 1283 bool Introduced) { 1284 switch (SP->getVirtuality()) { 1285 case dwarf::DW_VIRTUALITY_none: 1286 break; 1287 case dwarf::DW_VIRTUALITY_virtual: 1288 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 1289 case dwarf::DW_VIRTUALITY_pure_virtual: 1290 return Introduced ? MethodKind::PureIntroducingVirtual 1291 : MethodKind::PureVirtual; 1292 default: 1293 llvm_unreachable("unhandled virtuality case"); 1294 } 1295 1296 // FIXME: Get Clang to mark DISubprogram as static and do something with it. 1297 1298 return MethodKind::Vanilla; 1299 } 1300 1301 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 1302 switch (Ty->getTag()) { 1303 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 1304 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 1305 } 1306 llvm_unreachable("unexpected tag"); 1307 } 1308 1309 /// Return the HasUniqueName option if it should be present in ClassOptions, or 1310 /// None otherwise. 1311 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) { 1312 // MSVC always sets this flag now, even for local types. Clang doesn't always 1313 // appear to give every type a linkage name, which may be problematic for us. 1314 // FIXME: Investigate the consequences of not following them here. 1315 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName 1316 : ClassOptions::None; 1317 } 1318 1319 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 1320 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1321 TypeIndex FTI; 1322 unsigned EnumeratorCount = 0; 1323 1324 if (Ty->isForwardDecl()) { 1325 CO |= ClassOptions::ForwardReference; 1326 } else { 1327 FieldListRecordBuilder Fields; 1328 for (const DINode *Element : Ty->getElements()) { 1329 // We assume that the frontend provides all members in source declaration 1330 // order, which is what MSVC does. 1331 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 1332 Fields.writeEnumerator(EnumeratorRecord( 1333 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()), 1334 Enumerator->getName())); 1335 EnumeratorCount++; 1336 } 1337 } 1338 FTI = TypeTable.writeFieldList(Fields); 1339 } 1340 1341 std::string FullName = 1342 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1343 1344 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName, 1345 Ty->getIdentifier(), 1346 getTypeIndex(Ty->getBaseType()))); 1347 } 1348 1349 //===----------------------------------------------------------------------===// 1350 // ClassInfo 1351 //===----------------------------------------------------------------------===// 1352 1353 struct llvm::ClassInfo { 1354 struct MemberInfo { 1355 const DIDerivedType *MemberTypeNode; 1356 unsigned BaseOffset; 1357 }; 1358 // [MemberInfo] 1359 typedef std::vector<MemberInfo> MemberList; 1360 1361 typedef TinyPtrVector<const DISubprogram *> MethodsList; 1362 // MethodName -> MethodsList 1363 typedef MapVector<MDString *, MethodsList> MethodsMap; 1364 1365 /// Base classes. 1366 std::vector<const DIDerivedType *> Inheritance; 1367 1368 /// Direct members. 1369 MemberList Members; 1370 // Direct overloaded methods gathered by name. 1371 MethodsMap Methods; 1372 }; 1373 1374 void CodeViewDebug::clear() { 1375 assert(CurFn == nullptr); 1376 FileIdMap.clear(); 1377 FnDebugInfo.clear(); 1378 FileToFilepathMap.clear(); 1379 LocalUDTs.clear(); 1380 GlobalUDTs.clear(); 1381 TypeIndices.clear(); 1382 CompleteTypeIndices.clear(); 1383 } 1384 1385 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 1386 const DIDerivedType *DDTy) { 1387 if (!DDTy->getName().empty()) { 1388 Info.Members.push_back({DDTy, 0}); 1389 return; 1390 } 1391 // An unnamed member must represent a nested struct or union. Add all the 1392 // indirect fields to the current record. 1393 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 1394 unsigned Offset = DDTy->getOffsetInBits() / 8; 1395 const DIType *Ty = DDTy->getBaseType().resolve(); 1396 const DICompositeType *DCTy = cast<DICompositeType>(Ty); 1397 ClassInfo NestedInfo = collectClassInfo(DCTy); 1398 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) 1399 Info.Members.push_back( 1400 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); 1401 } 1402 1403 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 1404 ClassInfo Info; 1405 // Add elements to structure type. 1406 DINodeArray Elements = Ty->getElements(); 1407 for (auto *Element : Elements) { 1408 // We assume that the frontend provides all members in source declaration 1409 // order, which is what MSVC does. 1410 if (!Element) 1411 continue; 1412 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 1413 Info.Methods[SP->getRawName()].push_back(SP); 1414 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 1415 if (DDTy->getTag() == dwarf::DW_TAG_member) { 1416 collectMemberInfo(Info, DDTy); 1417 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 1418 Info.Inheritance.push_back(DDTy); 1419 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 1420 // Ignore friend members. It appears that MSVC emitted info about 1421 // friends in the past, but modern versions do not. 1422 } 1423 // FIXME: Get Clang to emit function virtual table here and handle it. 1424 // FIXME: Get clang to emit nested types here and do something with 1425 // them. 1426 } 1427 // Skip other unrecognized kinds of elements. 1428 } 1429 return Info; 1430 } 1431 1432 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 1433 // First, construct the forward decl. Don't look into Ty to compute the 1434 // forward decl options, since it might not be available in all TUs. 1435 TypeRecordKind Kind = getRecordKind(Ty); 1436 ClassOptions CO = 1437 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1438 std::string FullName = 1439 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1440 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord( 1441 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(), 1442 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier())); 1443 if (!Ty->isForwardDecl()) 1444 DeferredCompleteTypes.push_back(Ty); 1445 return FwdDeclTI; 1446 } 1447 1448 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 1449 // Construct the field list and complete type record. 1450 TypeRecordKind Kind = getRecordKind(Ty); 1451 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass. 1452 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1453 TypeIndex FieldTI; 1454 TypeIndex VShapeTI; 1455 unsigned FieldCount; 1456 std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty); 1457 1458 std::string FullName = 1459 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1460 1461 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1462 1463 TypeIndex ClassTI = TypeTable.writeClass(ClassRecord( 1464 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI, 1465 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier())); 1466 1467 TypeTable.writeUdtSourceLine(UdtSourceLineRecord( 1468 ClassTI, TypeTable.writeStringId(StringIdRecord( 1469 TypeIndex(0x0), getFullFilepath(Ty->getFile()))), 1470 Ty->getLine())); 1471 1472 addToUDTs(Ty, ClassTI); 1473 1474 return ClassTI; 1475 } 1476 1477 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 1478 ClassOptions CO = 1479 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1480 std::string FullName = 1481 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1482 TypeIndex FwdDeclTI = 1483 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0, 1484 FullName, Ty->getIdentifier())); 1485 if (!Ty->isForwardDecl()) 1486 DeferredCompleteTypes.push_back(Ty); 1487 return FwdDeclTI; 1488 } 1489 1490 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 1491 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1492 TypeIndex FieldTI; 1493 unsigned FieldCount; 1494 std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty); 1495 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1496 std::string FullName = 1497 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName()); 1498 1499 TypeIndex UnionTI = TypeTable.writeUnion( 1500 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName, 1501 Ty->getIdentifier())); 1502 1503 TypeTable.writeUdtSourceLine(UdtSourceLineRecord( 1504 UnionTI, TypeTable.writeStringId(StringIdRecord( 1505 TypeIndex(0x0), getFullFilepath(Ty->getFile()))), 1506 Ty->getLine())); 1507 1508 addToUDTs(Ty, UnionTI); 1509 1510 return UnionTI; 1511 } 1512 1513 std::tuple<TypeIndex, TypeIndex, unsigned> 1514 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 1515 // Manually count members. MSVC appears to count everything that generates a 1516 // field list record. Each individual overload in a method overload group 1517 // contributes to this count, even though the overload group is a single field 1518 // list record. 1519 unsigned MemberCount = 0; 1520 ClassInfo Info = collectClassInfo(Ty); 1521 FieldListRecordBuilder Fields; 1522 1523 // Create base classes. 1524 for (const DIDerivedType *I : Info.Inheritance) { 1525 if (I->getFlags() & DINode::FlagVirtual) { 1526 // Virtual base. 1527 // FIXME: Emit VBPtrOffset when the frontend provides it. 1528 unsigned VBPtrOffset = 0; 1529 // FIXME: Despite the accessor name, the offset is really in bytes. 1530 unsigned VBTableIndex = I->getOffsetInBits() / 4; 1531 Fields.writeVirtualBaseClass(VirtualBaseClassRecord( 1532 translateAccessFlags(Ty->getTag(), I->getFlags()), 1533 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, 1534 VBTableIndex)); 1535 } else { 1536 assert(I->getOffsetInBits() % 8 == 0 && 1537 "bases must be on byte boundaries"); 1538 Fields.writeBaseClass(BaseClassRecord( 1539 translateAccessFlags(Ty->getTag(), I->getFlags()), 1540 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8)); 1541 } 1542 } 1543 1544 // Create members. 1545 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 1546 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 1547 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 1548 StringRef MemberName = Member->getName(); 1549 MemberAccess Access = 1550 translateAccessFlags(Ty->getTag(), Member->getFlags()); 1551 1552 if (Member->isStaticMember()) { 1553 Fields.writeStaticDataMember( 1554 StaticDataMemberRecord(Access, MemberBaseType, MemberName)); 1555 MemberCount++; 1556 continue; 1557 } 1558 1559 // Data member. 1560 uint64_t MemberOffsetInBits = Member->getOffsetInBits(); 1561 if (Member->isBitField()) { 1562 uint64_t StartBitOffset = MemberOffsetInBits; 1563 if (const auto *CI = 1564 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { 1565 MemberOffsetInBits = CI->getZExtValue(); 1566 } 1567 StartBitOffset -= MemberOffsetInBits; 1568 MemberBaseType = TypeTable.writeBitField(BitFieldRecord( 1569 MemberBaseType, Member->getSizeInBits(), StartBitOffset)); 1570 } 1571 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; 1572 Fields.writeDataMember(DataMemberRecord(Access, MemberBaseType, 1573 MemberOffsetInBytes, MemberName)); 1574 MemberCount++; 1575 } 1576 1577 // Create methods 1578 for (auto &MethodItr : Info.Methods) { 1579 StringRef Name = MethodItr.first->getString(); 1580 1581 std::vector<OneMethodRecord> Methods; 1582 for (const DISubprogram *SP : MethodItr.second) { 1583 TypeIndex MethodType = getMemberFunctionType(SP, Ty); 1584 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; 1585 1586 unsigned VFTableOffset = -1; 1587 if (Introduced) 1588 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 1589 1590 Methods.push_back( 1591 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced), 1592 translateMethodOptionFlags(SP), 1593 translateAccessFlags(Ty->getTag(), SP->getFlags()), 1594 VFTableOffset, Name)); 1595 MemberCount++; 1596 } 1597 assert(Methods.size() > 0 && "Empty methods map entry"); 1598 if (Methods.size() == 1) 1599 Fields.writeOneMethod(Methods[0]); 1600 else { 1601 TypeIndex MethodList = 1602 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods)); 1603 Fields.writeOverloadedMethod( 1604 OverloadedMethodRecord(Methods.size(), MethodList, Name)); 1605 } 1606 } 1607 TypeIndex FieldTI = TypeTable.writeFieldList(Fields); 1608 return std::make_tuple(FieldTI, TypeIndex(), MemberCount); 1609 } 1610 1611 TypeIndex CodeViewDebug::getVBPTypeIndex() { 1612 if (!VBPType.getIndex()) { 1613 // Make a 'const int *' type. 1614 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); 1615 TypeIndex ModifiedTI = TypeTable.writeModifier(MR); 1616 1617 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 1618 : PointerKind::Near32; 1619 PointerMode PM = PointerMode::Pointer; 1620 PointerOptions PO = PointerOptions::None; 1621 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); 1622 1623 VBPType = TypeTable.writePointer(PR); 1624 } 1625 1626 return VBPType; 1627 } 1628 1629 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) { 1630 const DIType *Ty = TypeRef.resolve(); 1631 const DIType *ClassTy = ClassTyRef.resolve(); 1632 1633 // The null DIType is the void type. Don't try to hash it. 1634 if (!Ty) 1635 return TypeIndex::Void(); 1636 1637 // Check if we've already translated this type. Don't try to do a 1638 // get-or-create style insertion that caches the hash lookup across the 1639 // lowerType call. It will update the TypeIndices map. 1640 auto I = TypeIndices.find({Ty, ClassTy}); 1641 if (I != TypeIndices.end()) 1642 return I->second; 1643 1644 TypeLoweringScope S(*this); 1645 TypeIndex TI = lowerType(Ty, ClassTy); 1646 return recordTypeIndexForDINode(Ty, TI, ClassTy); 1647 } 1648 1649 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) { 1650 const DIType *Ty = TypeRef.resolve(); 1651 1652 // The null DIType is the void type. Don't try to hash it. 1653 if (!Ty) 1654 return TypeIndex::Void(); 1655 1656 // If this is a non-record type, the complete type index is the same as the 1657 // normal type index. Just call getTypeIndex. 1658 switch (Ty->getTag()) { 1659 case dwarf::DW_TAG_class_type: 1660 case dwarf::DW_TAG_structure_type: 1661 case dwarf::DW_TAG_union_type: 1662 break; 1663 default: 1664 return getTypeIndex(Ty); 1665 } 1666 1667 // Check if we've already translated the complete record type. Lowering a 1668 // complete type should never trigger lowering another complete type, so we 1669 // can reuse the hash table lookup result. 1670 const auto *CTy = cast<DICompositeType>(Ty); 1671 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 1672 if (!InsertResult.second) 1673 return InsertResult.first->second; 1674 1675 TypeLoweringScope S(*this); 1676 1677 // Make sure the forward declaration is emitted first. It's unclear if this 1678 // is necessary, but MSVC does it, and we should follow suit until we can show 1679 // otherwise. 1680 TypeIndex FwdDeclTI = getTypeIndex(CTy); 1681 1682 // Just use the forward decl if we don't have complete type info. This might 1683 // happen if the frontend is using modules and expects the complete definition 1684 // to be emitted elsewhere. 1685 if (CTy->isForwardDecl()) 1686 return FwdDeclTI; 1687 1688 TypeIndex TI; 1689 switch (CTy->getTag()) { 1690 case dwarf::DW_TAG_class_type: 1691 case dwarf::DW_TAG_structure_type: 1692 TI = lowerCompleteTypeClass(CTy); 1693 break; 1694 case dwarf::DW_TAG_union_type: 1695 TI = lowerCompleteTypeUnion(CTy); 1696 break; 1697 default: 1698 llvm_unreachable("not a record"); 1699 } 1700 1701 InsertResult.first->second = TI; 1702 return TI; 1703 } 1704 1705 /// Emit all the deferred complete record types. Try to do this in FIFO order, 1706 /// and do this until fixpoint, as each complete record type typically references 1707 /// many other record types. 1708 void CodeViewDebug::emitDeferredCompleteTypes() { 1709 SmallVector<const DICompositeType *, 4> TypesToEmit; 1710 while (!DeferredCompleteTypes.empty()) { 1711 std::swap(DeferredCompleteTypes, TypesToEmit); 1712 for (const DICompositeType *RecordTy : TypesToEmit) 1713 getCompleteTypeIndex(RecordTy); 1714 TypesToEmit.clear(); 1715 } 1716 } 1717 1718 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) { 1719 // Get the sorted list of parameters and emit them first. 1720 SmallVector<const LocalVariable *, 6> Params; 1721 for (const LocalVariable &L : Locals) 1722 if (L.DIVar->isParameter()) 1723 Params.push_back(&L); 1724 std::sort(Params.begin(), Params.end(), 1725 [](const LocalVariable *L, const LocalVariable *R) { 1726 return L->DIVar->getArg() < R->DIVar->getArg(); 1727 }); 1728 for (const LocalVariable *L : Params) 1729 emitLocalVariable(*L); 1730 1731 // Next emit all non-parameters in the order that we found them. 1732 for (const LocalVariable &L : Locals) 1733 if (!L.DIVar->isParameter()) 1734 emitLocalVariable(L); 1735 } 1736 1737 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 1738 // LocalSym record, see SymbolRecord.h for more info. 1739 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 1740 *LocalEnd = MMI->getContext().createTempSymbol(); 1741 OS.AddComment("Record length"); 1742 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 1743 OS.EmitLabel(LocalBegin); 1744 1745 OS.AddComment("Record kind: S_LOCAL"); 1746 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2); 1747 1748 LocalSymFlags Flags = LocalSymFlags::None; 1749 if (Var.DIVar->isParameter()) 1750 Flags |= LocalSymFlags::IsParameter; 1751 if (Var.DefRanges.empty()) 1752 Flags |= LocalSymFlags::IsOptimizedOut; 1753 1754 OS.AddComment("TypeIndex"); 1755 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType()); 1756 OS.EmitIntValue(TI.getIndex(), 4); 1757 OS.AddComment("Flags"); 1758 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 1759 // Truncate the name so we won't overflow the record length field. 1760 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 1761 OS.EmitLabel(LocalEnd); 1762 1763 // Calculate the on disk prefix of the appropriate def range record. The 1764 // records and on disk formats are described in SymbolRecords.h. BytePrefix 1765 // should be big enough to hold all forms without memory allocation. 1766 SmallString<20> BytePrefix; 1767 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 1768 BytePrefix.clear(); 1769 // FIXME: Handle bitpieces. 1770 if (DefRange.StructOffset != 0) 1771 continue; 1772 1773 if (DefRange.InMemory) { 1774 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0, 1775 0, 0, ArrayRef<LocalVariableAddrGap>()); 1776 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 1777 BytePrefix += 1778 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1779 BytePrefix += 1780 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1781 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1782 } else { 1783 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 1784 // Unclear what matters here. 1785 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0, 1786 ArrayRef<LocalVariableAddrGap>()); 1787 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 1788 BytePrefix += 1789 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1790 BytePrefix += 1791 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1792 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1793 } 1794 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 1795 } 1796 } 1797 1798 void CodeViewDebug::endFunction(const MachineFunction *MF) { 1799 if (!Asm || !CurFn) // We haven't created any debug info for this function. 1800 return; 1801 1802 const Function *GV = MF->getFunction(); 1803 assert(FnDebugInfo.count(GV)); 1804 assert(CurFn == &FnDebugInfo[GV]); 1805 1806 collectVariableInfo(GV->getSubprogram()); 1807 1808 DebugHandlerBase::endFunction(MF); 1809 1810 // Don't emit anything if we don't have any line tables. 1811 if (!CurFn->HaveLineInfo) { 1812 FnDebugInfo.erase(GV); 1813 CurFn = nullptr; 1814 return; 1815 } 1816 1817 CurFn->End = Asm->getFunctionEnd(); 1818 1819 CurFn = nullptr; 1820 } 1821 1822 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 1823 DebugHandlerBase::beginInstruction(MI); 1824 1825 // Ignore DBG_VALUE locations and function prologue. 1826 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 1827 return; 1828 DebugLoc DL = MI->getDebugLoc(); 1829 if (DL == PrevInstLoc || !DL) 1830 return; 1831 maybeRecordLocation(DL, Asm->MF); 1832 } 1833 1834 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) { 1835 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 1836 *EndLabel = MMI->getContext().createTempSymbol(); 1837 OS.EmitIntValue(unsigned(Kind), 4); 1838 OS.AddComment("Subsection size"); 1839 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 1840 OS.EmitLabel(BeginLabel); 1841 return EndLabel; 1842 } 1843 1844 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 1845 OS.EmitLabel(EndLabel); 1846 // Every subsection must be aligned to a 4-byte boundary. 1847 OS.EmitValueToAlignment(4); 1848 } 1849 1850 void CodeViewDebug::emitDebugInfoForUDTs( 1851 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) { 1852 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) { 1853 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(), 1854 *UDTRecordEnd = MMI->getContext().createTempSymbol(); 1855 OS.AddComment("Record length"); 1856 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2); 1857 OS.EmitLabel(UDTRecordBegin); 1858 1859 OS.AddComment("Record kind: S_UDT"); 1860 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2); 1861 1862 OS.AddComment("Type"); 1863 OS.EmitIntValue(UDT.second.getIndex(), 4); 1864 1865 emitNullTerminatedSymbolName(OS, UDT.first); 1866 OS.EmitLabel(UDTRecordEnd); 1867 } 1868 } 1869 1870 void CodeViewDebug::emitDebugInfoForGlobals() { 1871 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 1872 for (const MDNode *Node : CUs->operands()) { 1873 const auto *CU = cast<DICompileUnit>(Node); 1874 1875 // First, emit all globals that are not in a comdat in a single symbol 1876 // substream. MSVC doesn't like it if the substream is empty, so only open 1877 // it if we have at least one global to emit. 1878 switchToDebugSectionForSymbol(nullptr); 1879 MCSymbol *EndLabel = nullptr; 1880 for (const DIGlobalVariable *G : CU->getGlobalVariables()) { 1881 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) { 1882 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) { 1883 if (!EndLabel) { 1884 OS.AddComment("Symbol subsection for globals"); 1885 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols); 1886 } 1887 emitDebugInfoForGlobal(G, Asm->getSymbol(GV)); 1888 } 1889 } 1890 } 1891 if (EndLabel) 1892 endCVSubsection(EndLabel); 1893 1894 // Second, emit each global that is in a comdat into its own .debug$S 1895 // section along with its own symbol substream. 1896 for (const DIGlobalVariable *G : CU->getGlobalVariables()) { 1897 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) { 1898 if (GV->hasComdat()) { 1899 MCSymbol *GVSym = Asm->getSymbol(GV); 1900 OS.AddComment("Symbol subsection for " + 1901 Twine(GlobalValue::getRealLinkageName(GV->getName()))); 1902 switchToDebugSectionForSymbol(GVSym); 1903 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols); 1904 emitDebugInfoForGlobal(G, GVSym); 1905 endCVSubsection(EndLabel); 1906 } 1907 } 1908 } 1909 } 1910 } 1911 1912 void CodeViewDebug::emitDebugInfoForRetainedTypes() { 1913 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 1914 for (const MDNode *Node : CUs->operands()) { 1915 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { 1916 if (DIType *RT = dyn_cast<DIType>(Ty)) { 1917 getTypeIndex(RT); 1918 // FIXME: Add to global/local DTU list. 1919 } 1920 } 1921 } 1922 } 1923 1924 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, 1925 MCSymbol *GVSym) { 1926 // DataSym record, see SymbolRecord.h for more info. 1927 // FIXME: Thread local data, etc 1928 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(), 1929 *DataEnd = MMI->getContext().createTempSymbol(); 1930 OS.AddComment("Record length"); 1931 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2); 1932 OS.EmitLabel(DataBegin); 1933 OS.AddComment("Record kind: S_GDATA32"); 1934 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2); 1935 OS.AddComment("Type"); 1936 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4); 1937 OS.AddComment("DataOffset"); 1938 OS.EmitCOFFSecRel32(GVSym); 1939 OS.AddComment("Segment"); 1940 OS.EmitCOFFSectionIndex(GVSym); 1941 OS.AddComment("Name"); 1942 emitNullTerminatedSymbolName(OS, DIGV->getName()); 1943 OS.EmitLabel(DataEnd); 1944 } 1945