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