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