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