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