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