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