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