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