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