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