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