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