1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for writing Microsoft CodeView debug info. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeViewDebug.h" 14 #include "llvm/ADT/APSInt.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallBitVector.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/TinyPtrVector.h" 20 #include "llvm/ADT/Twine.h" 21 #include "llvm/BinaryFormat/COFF.h" 22 #include "llvm/BinaryFormat/Dwarf.h" 23 #include "llvm/CodeGen/AsmPrinter.h" 24 #include "llvm/CodeGen/LexicalScopes.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineInstr.h" 28 #include "llvm/CodeGen/MachineModuleInfo.h" 29 #include "llvm/CodeGen/TargetFrameLowering.h" 30 #include "llvm/CodeGen/TargetLowering.h" 31 #include "llvm/CodeGen/TargetRegisterInfo.h" 32 #include "llvm/CodeGen/TargetSubtargetInfo.h" 33 #include "llvm/Config/llvm-config.h" 34 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 35 #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h" 36 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h" 37 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h" 38 #include "llvm/DebugInfo/CodeView/EnumTables.h" 39 #include "llvm/DebugInfo/CodeView/Line.h" 40 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 41 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 42 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h" 43 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/DebugInfoMetadata.h" 47 #include "llvm/IR/Function.h" 48 #include "llvm/IR/GlobalValue.h" 49 #include "llvm/IR/GlobalVariable.h" 50 #include "llvm/IR/Metadata.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/MC/MCAsmInfo.h" 53 #include "llvm/MC/MCContext.h" 54 #include "llvm/MC/MCSectionCOFF.h" 55 #include "llvm/MC/MCStreamer.h" 56 #include "llvm/MC/MCSymbol.h" 57 #include "llvm/Support/BinaryStreamWriter.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/Error.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/FormatVariadic.h" 62 #include "llvm/Support/Path.h" 63 #include "llvm/Support/Program.h" 64 #include "llvm/Support/SMLoc.h" 65 #include "llvm/Support/ScopedPrinter.h" 66 #include "llvm/Target/TargetLoweringObjectFile.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/TargetParser/Triple.h" 69 #include <algorithm> 70 #include <cassert> 71 #include <cctype> 72 #include <cstddef> 73 #include <iterator> 74 #include <limits> 75 76 using namespace llvm; 77 using namespace llvm::codeview; 78 79 namespace { 80 class CVMCAdapter : public CodeViewRecordStreamer { 81 public: 82 CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable) 83 : OS(&OS), TypeTable(TypeTable) {} 84 85 void emitBytes(StringRef Data) override { OS->emitBytes(Data); } 86 87 void emitIntValue(uint64_t Value, unsigned Size) override { 88 OS->emitIntValueInHex(Value, Size); 89 } 90 91 void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); } 92 93 void AddComment(const Twine &T) override { OS->AddComment(T); } 94 95 void AddRawComment(const Twine &T) override { OS->emitRawComment(T); } 96 97 bool isVerboseAsm() override { return OS->isVerboseAsm(); } 98 99 std::string getTypeName(TypeIndex TI) override { 100 std::string TypeName; 101 if (!TI.isNoneType()) { 102 if (TI.isSimple()) 103 TypeName = std::string(TypeIndex::simpleTypeName(TI)); 104 else 105 TypeName = std::string(TypeTable.getTypeName(TI)); 106 } 107 return TypeName; 108 } 109 110 private: 111 MCStreamer *OS = nullptr; 112 TypeCollection &TypeTable; 113 }; 114 } // namespace 115 116 static CPUType mapArchToCVCPUType(Triple::ArchType Type) { 117 switch (Type) { 118 case Triple::ArchType::x86: 119 return CPUType::Pentium3; 120 case Triple::ArchType::x86_64: 121 return CPUType::X64; 122 case Triple::ArchType::thumb: 123 // LLVM currently doesn't support Windows CE and so thumb 124 // here is indiscriminately mapped to ARMNT specifically. 125 return CPUType::ARMNT; 126 case Triple::ArchType::aarch64: 127 return CPUType::ARM64; 128 default: 129 report_fatal_error("target architecture doesn't map to a CodeView CPUType"); 130 } 131 } 132 133 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 134 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {} 135 136 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 137 std::string &Filepath = FileToFilepathMap[File]; 138 if (!Filepath.empty()) 139 return Filepath; 140 141 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 142 143 // If this is a Unix-style path, just use it as is. Don't try to canonicalize 144 // it textually because one of the path components could be a symlink. 145 if (Dir.startswith("/") || Filename.startswith("/")) { 146 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix)) 147 return Filename; 148 Filepath = std::string(Dir); 149 if (Dir.back() != '/') 150 Filepath += '/'; 151 Filepath += Filename; 152 return Filepath; 153 } 154 155 // Clang emits directory and relative filename info into the IR, but CodeView 156 // operates on full paths. We could change Clang to emit full paths too, but 157 // that would increase the IR size and probably not needed for other users. 158 // For now, just concatenate and canonicalize the path here. 159 if (Filename.find(':') == 1) 160 Filepath = std::string(Filename); 161 else 162 Filepath = (Dir + "\\" + Filename).str(); 163 164 // Canonicalize the path. We have to do it textually because we may no longer 165 // have access the file in the filesystem. 166 // First, replace all slashes with backslashes. 167 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 168 169 // Remove all "\.\" with "\". 170 size_t Cursor = 0; 171 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 172 Filepath.erase(Cursor, 2); 173 174 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 175 // path should be well-formatted, e.g. start with a drive letter, etc. 176 Cursor = 0; 177 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 178 // Something's wrong if the path starts with "\..\", abort. 179 if (Cursor == 0) 180 break; 181 182 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 183 if (PrevSlash == std::string::npos) 184 // Something's wrong, abort. 185 break; 186 187 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 188 // The next ".." might be following the one we've just erased. 189 Cursor = PrevSlash; 190 } 191 192 // Remove all duplicate backslashes. 193 Cursor = 0; 194 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 195 Filepath.erase(Cursor, 1); 196 197 return Filepath; 198 } 199 200 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 201 StringRef FullPath = getFullFilepath(F); 202 unsigned NextId = FileIdMap.size() + 1; 203 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId)); 204 if (Insertion.second) { 205 // We have to compute the full filepath and emit a .cv_file directive. 206 ArrayRef<uint8_t> ChecksumAsBytes; 207 FileChecksumKind CSKind = FileChecksumKind::None; 208 if (F->getChecksum()) { 209 std::string Checksum = fromHex(F->getChecksum()->Value); 210 void *CKMem = OS.getContext().allocate(Checksum.size(), 1); 211 memcpy(CKMem, Checksum.data(), Checksum.size()); 212 ChecksumAsBytes = ArrayRef<uint8_t>( 213 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size()); 214 switch (F->getChecksum()->Kind) { 215 case DIFile::CSK_MD5: 216 CSKind = FileChecksumKind::MD5; 217 break; 218 case DIFile::CSK_SHA1: 219 CSKind = FileChecksumKind::SHA1; 220 break; 221 case DIFile::CSK_SHA256: 222 CSKind = FileChecksumKind::SHA256; 223 break; 224 } 225 } 226 bool Success = OS.emitCVFileDirective(NextId, FullPath, ChecksumAsBytes, 227 static_cast<unsigned>(CSKind)); 228 (void)Success; 229 assert(Success && ".cv_file directive failed"); 230 } 231 return Insertion.first->second; 232 } 233 234 CodeViewDebug::InlineSite & 235 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 236 const DISubprogram *Inlinee) { 237 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 238 InlineSite *Site = &SiteInsertion.first->second; 239 if (SiteInsertion.second) { 240 unsigned ParentFuncId = CurFn->FuncId; 241 if (const DILocation *OuterIA = InlinedAt->getInlinedAt()) 242 ParentFuncId = 243 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram()) 244 .SiteFuncId; 245 246 Site->SiteFuncId = NextFuncId++; 247 OS.emitCVInlineSiteIdDirective( 248 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()), 249 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc()); 250 Site->Inlinee = Inlinee; 251 InlinedSubprograms.insert(Inlinee); 252 auto InlineeIdx = getFuncIdForSubprogram(Inlinee); 253 254 if (InlinedAt->getInlinedAt() == nullptr) 255 CurFn->Inlinees.insert(InlineeIdx); 256 } 257 return *Site; 258 } 259 260 static StringRef getPrettyScopeName(const DIScope *Scope) { 261 StringRef ScopeName = Scope->getName(); 262 if (!ScopeName.empty()) 263 return ScopeName; 264 265 switch (Scope->getTag()) { 266 case dwarf::DW_TAG_enumeration_type: 267 case dwarf::DW_TAG_class_type: 268 case dwarf::DW_TAG_structure_type: 269 case dwarf::DW_TAG_union_type: 270 return "<unnamed-tag>"; 271 case dwarf::DW_TAG_namespace: 272 return "`anonymous namespace'"; 273 default: 274 return StringRef(); 275 } 276 } 277 278 const DISubprogram *CodeViewDebug::collectParentScopeNames( 279 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { 280 const DISubprogram *ClosestSubprogram = nullptr; 281 while (Scope != nullptr) { 282 if (ClosestSubprogram == nullptr) 283 ClosestSubprogram = dyn_cast<DISubprogram>(Scope); 284 285 // If a type appears in a scope chain, make sure it gets emitted. The 286 // frontend will be responsible for deciding if this should be a forward 287 // declaration or a complete type. 288 if (const auto *Ty = dyn_cast<DICompositeType>(Scope)) 289 DeferredCompleteTypes.push_back(Ty); 290 291 StringRef ScopeName = getPrettyScopeName(Scope); 292 if (!ScopeName.empty()) 293 QualifiedNameComponents.push_back(ScopeName); 294 Scope = Scope->getScope(); 295 } 296 return ClosestSubprogram; 297 } 298 299 static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents, 300 StringRef TypeName) { 301 std::string FullyQualifiedName; 302 for (StringRef QualifiedNameComponent : 303 llvm::reverse(QualifiedNameComponents)) { 304 FullyQualifiedName.append(std::string(QualifiedNameComponent)); 305 FullyQualifiedName.append("::"); 306 } 307 FullyQualifiedName.append(std::string(TypeName)); 308 return FullyQualifiedName; 309 } 310 311 struct CodeViewDebug::TypeLoweringScope { 312 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; } 313 ~TypeLoweringScope() { 314 // Don't decrement TypeEmissionLevel until after emitting deferred types, so 315 // inner TypeLoweringScopes don't attempt to emit deferred types. 316 if (CVD.TypeEmissionLevel == 1) 317 CVD.emitDeferredCompleteTypes(); 318 --CVD.TypeEmissionLevel; 319 } 320 CodeViewDebug &CVD; 321 }; 322 323 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope, 324 StringRef Name) { 325 // Ensure types in the scope chain are emitted as soon as possible. 326 // This can create otherwise a situation where S_UDTs are emitted while 327 // looping in emitDebugInfoForUDTs. 328 TypeLoweringScope S(*this); 329 SmallVector<StringRef, 5> QualifiedNameComponents; 330 collectParentScopeNames(Scope, QualifiedNameComponents); 331 return formatNestedName(QualifiedNameComponents, Name); 332 } 333 334 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) { 335 const DIScope *Scope = Ty->getScope(); 336 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty)); 337 } 338 339 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) { 340 // No scope means global scope and that uses the zero index. 341 // 342 // We also use zero index when the scope is a DISubprogram 343 // to suppress the emission of LF_STRING_ID for the function, 344 // which can trigger a link-time error with the linker in 345 // VS2019 version 16.11.2 or newer. 346 // Note, however, skipping the debug info emission for the DISubprogram 347 // is a temporary fix. The root issue here is that we need to figure out 348 // the proper way to encode a function nested in another function 349 // (as introduced by the Fortran 'contains' keyword) in CodeView. 350 if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope)) 351 return TypeIndex(); 352 353 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"); 354 355 // Check if we've already translated this scope. 356 auto I = TypeIndices.find({Scope, nullptr}); 357 if (I != TypeIndices.end()) 358 return I->second; 359 360 // Build the fully qualified name of the scope. 361 std::string ScopeName = getFullyQualifiedName(Scope); 362 StringIdRecord SID(TypeIndex(), ScopeName); 363 auto TI = TypeTable.writeLeafType(SID); 364 return recordTypeIndexForDINode(Scope, TI); 365 } 366 367 static StringRef removeTemplateArgs(StringRef Name) { 368 // Remove template args from the display name. Assume that the template args 369 // are the last thing in the name. 370 if (Name.empty() || Name.back() != '>') 371 return Name; 372 373 int OpenBrackets = 0; 374 for (int i = Name.size() - 1; i >= 0; --i) { 375 if (Name[i] == '>') 376 ++OpenBrackets; 377 else if (Name[i] == '<') { 378 --OpenBrackets; 379 if (OpenBrackets == 0) 380 return Name.substr(0, i); 381 } 382 } 383 return Name; 384 } 385 386 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 387 assert(SP); 388 389 // Check if we've already translated this subprogram. 390 auto I = TypeIndices.find({SP, nullptr}); 391 if (I != TypeIndices.end()) 392 return I->second; 393 394 // The display name includes function template arguments. Drop them to match 395 // MSVC. We need to have the template arguments in the DISubprogram name 396 // because they are used in other symbol records, such as S_GPROC32_IDs. 397 StringRef DisplayName = removeTemplateArgs(SP->getName()); 398 399 const DIScope *Scope = SP->getScope(); 400 TypeIndex TI; 401 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) { 402 // If the scope is a DICompositeType, then this must be a method. Member 403 // function types take some special handling, and require access to the 404 // subprogram. 405 TypeIndex ClassType = getTypeIndex(Class); 406 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class), 407 DisplayName); 408 TI = TypeTable.writeLeafType(MFuncId); 409 } else { 410 // Otherwise, this must be a free function. 411 TypeIndex ParentScope = getScopeIndex(Scope); 412 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); 413 TI = TypeTable.writeLeafType(FuncId); 414 } 415 416 return recordTypeIndexForDINode(SP, TI); 417 } 418 419 static bool isNonTrivial(const DICompositeType *DCTy) { 420 return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial); 421 } 422 423 static FunctionOptions 424 getFunctionOptions(const DISubroutineType *Ty, 425 const DICompositeType *ClassTy = nullptr, 426 StringRef SPName = StringRef("")) { 427 FunctionOptions FO = FunctionOptions::None; 428 const DIType *ReturnTy = nullptr; 429 if (auto TypeArray = Ty->getTypeArray()) { 430 if (TypeArray.size()) 431 ReturnTy = TypeArray[0]; 432 } 433 434 // Add CxxReturnUdt option to functions that return nontrivial record types 435 // or methods that return record types. 436 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) 437 if (isNonTrivial(ReturnDCTy) || ClassTy) 438 FO |= FunctionOptions::CxxReturnUdt; 439 440 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison. 441 if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) { 442 FO |= FunctionOptions::Constructor; 443 444 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag. 445 446 } 447 return FO; 448 } 449 450 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP, 451 const DICompositeType *Class) { 452 // Always use the method declaration as the key for the function type. The 453 // method declaration contains the this adjustment. 454 if (SP->getDeclaration()) 455 SP = SP->getDeclaration(); 456 assert(!SP->getDeclaration() && "should use declaration as key"); 457 458 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide 459 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. 460 auto I = TypeIndices.find({SP, Class}); 461 if (I != TypeIndices.end()) 462 return I->second; 463 464 // Make sure complete type info for the class is emitted *after* the member 465 // function type, as the complete class type is likely to reference this 466 // member function type. 467 TypeLoweringScope S(*this); 468 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0; 469 470 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName()); 471 TypeIndex TI = lowerTypeMemberFunction( 472 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO); 473 return recordTypeIndexForDINode(SP, TI, Class); 474 } 475 476 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, 477 TypeIndex TI, 478 const DIType *ClassTy) { 479 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); 480 (void)InsertResult; 481 assert(InsertResult.second && "DINode was already assigned a type index"); 482 return TI; 483 } 484 485 unsigned CodeViewDebug::getPointerSizeInBytes() { 486 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; 487 } 488 489 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 490 const LexicalScope *LS) { 491 if (const DILocation *InlinedAt = LS->getInlinedAt()) { 492 // This variable was inlined. Associate it with the InlineSite. 493 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 494 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 495 Site.InlinedLocals.emplace_back(std::move(Var)); 496 } else { 497 // This variable goes into the corresponding lexical scope. 498 ScopeVariables[LS].emplace_back(std::move(Var)); 499 } 500 } 501 502 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 503 const DILocation *Loc) { 504 if (!llvm::is_contained(Locs, Loc)) 505 Locs.push_back(Loc); 506 } 507 508 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, 509 const MachineFunction *MF) { 510 // Skip this instruction if it has the same location as the previous one. 511 if (!DL || DL == PrevInstLoc) 512 return; 513 514 const DIScope *Scope = DL->getScope(); 515 if (!Scope) 516 return; 517 518 // Skip this line if it is longer than the maximum we can record. 519 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 520 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 521 LI.isNeverStepInto()) 522 return; 523 524 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 525 if (CI.getStartColumn() != DL.getCol()) 526 return; 527 528 if (!CurFn->HaveLineInfo) 529 CurFn->HaveLineInfo = true; 530 unsigned FileId = 0; 531 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile()) 532 FileId = CurFn->LastFileId; 533 else 534 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 535 PrevInstLoc = DL; 536 537 unsigned FuncId = CurFn->FuncId; 538 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 539 const DILocation *Loc = DL.get(); 540 541 // If this location was actually inlined from somewhere else, give it the ID 542 // of the inline call site. 543 FuncId = 544 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 545 546 // Ensure we have links in the tree of inline call sites. 547 bool FirstLoc = true; 548 while ((SiteLoc = Loc->getInlinedAt())) { 549 InlineSite &Site = 550 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 551 if (!FirstLoc) 552 addLocIfNotPresent(Site.ChildSites, Loc); 553 FirstLoc = false; 554 Loc = SiteLoc; 555 } 556 addLocIfNotPresent(CurFn->ChildSites, Loc); 557 } 558 559 OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 560 /*PrologueEnd=*/false, /*IsStmt=*/false, 561 DL->getFilename(), SMLoc()); 562 } 563 564 void CodeViewDebug::emitCodeViewMagicVersion() { 565 OS.emitValueToAlignment(Align(4)); 566 OS.AddComment("Debug section magic"); 567 OS.emitInt32(COFF::DEBUG_SECTION_MAGIC); 568 } 569 570 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) { 571 switch (DWLang) { 572 case dwarf::DW_LANG_C: 573 case dwarf::DW_LANG_C89: 574 case dwarf::DW_LANG_C99: 575 case dwarf::DW_LANG_C11: 576 return SourceLanguage::C; 577 case dwarf::DW_LANG_C_plus_plus: 578 case dwarf::DW_LANG_C_plus_plus_03: 579 case dwarf::DW_LANG_C_plus_plus_11: 580 case dwarf::DW_LANG_C_plus_plus_14: 581 return SourceLanguage::Cpp; 582 case dwarf::DW_LANG_Fortran77: 583 case dwarf::DW_LANG_Fortran90: 584 case dwarf::DW_LANG_Fortran95: 585 case dwarf::DW_LANG_Fortran03: 586 case dwarf::DW_LANG_Fortran08: 587 return SourceLanguage::Fortran; 588 case dwarf::DW_LANG_Pascal83: 589 return SourceLanguage::Pascal; 590 case dwarf::DW_LANG_Cobol74: 591 case dwarf::DW_LANG_Cobol85: 592 return SourceLanguage::Cobol; 593 case dwarf::DW_LANG_Java: 594 return SourceLanguage::Java; 595 case dwarf::DW_LANG_D: 596 return SourceLanguage::D; 597 case dwarf::DW_LANG_Swift: 598 return SourceLanguage::Swift; 599 case dwarf::DW_LANG_Rust: 600 return SourceLanguage::Rust; 601 case dwarf::DW_LANG_ObjC: 602 return SourceLanguage::ObjC; 603 case dwarf::DW_LANG_ObjC_plus_plus: 604 return SourceLanguage::ObjCpp; 605 default: 606 // There's no CodeView representation for this language, and CV doesn't 607 // have an "unknown" option for the language field, so we'll use MASM, 608 // as it's very low level. 609 return SourceLanguage::Masm; 610 } 611 } 612 613 void CodeViewDebug::beginModule(Module *M) { 614 // If module doesn't have named metadata anchors or COFF debug section 615 // is not available, skip any debug info related stuff. 616 if (!MMI->hasDebugInfo() || 617 !Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) { 618 Asm = nullptr; 619 return; 620 } 621 622 TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch()); 623 624 // Get the current source language. 625 const MDNode *Node = *M->debug_compile_units_begin(); 626 const auto *CU = cast<DICompileUnit>(Node); 627 628 CurrentSourceLanguage = MapDWLangToCVLang(CU->getSourceLanguage()); 629 630 collectGlobalVariableInfo(); 631 632 // Check if we should emit type record hashes. 633 ConstantInt *GH = 634 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash")); 635 EmitDebugGlobalHashes = GH && !GH->isZero(); 636 } 637 638 void CodeViewDebug::endModule() { 639 if (!Asm || !MMI->hasDebugInfo()) 640 return; 641 642 // The COFF .debug$S section consists of several subsections, each starting 643 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 644 // of the payload followed by the payload itself. The subsections are 4-byte 645 // aligned. 646 647 // Use the generic .debug$S section, and make a subsection for all the inlined 648 // subprograms. 649 switchToDebugSectionForSymbol(nullptr); 650 651 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols); 652 emitObjName(); 653 emitCompilerInformation(); 654 endCVSubsection(CompilerInfo); 655 656 emitInlineeLinesSubsection(); 657 658 // Emit per-function debug information. 659 for (auto &P : FnDebugInfo) 660 if (!P.first->isDeclarationForLinker()) 661 emitDebugInfoForFunction(P.first, *P.second); 662 663 // Get types used by globals without emitting anything. 664 // This is meant to collect all static const data members so they can be 665 // emitted as globals. 666 collectDebugInfoForGlobals(); 667 668 // Emit retained types. 669 emitDebugInfoForRetainedTypes(); 670 671 // Emit global variable debug information. 672 setCurrentSubprogram(nullptr); 673 emitDebugInfoForGlobals(); 674 675 // Switch back to the generic .debug$S section after potentially processing 676 // comdat symbol sections. 677 switchToDebugSectionForSymbol(nullptr); 678 679 // Emit UDT records for any types used by global variables. 680 if (!GlobalUDTs.empty()) { 681 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 682 emitDebugInfoForUDTs(GlobalUDTs); 683 endCVSubsection(SymbolsEnd); 684 } 685 686 // This subsection holds a file index to offset in string table table. 687 OS.AddComment("File index to string table offset subsection"); 688 OS.emitCVFileChecksumsDirective(); 689 690 // This subsection holds the string table. 691 OS.AddComment("String table"); 692 OS.emitCVStringTableDirective(); 693 694 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol 695 // subsection in the generic .debug$S section at the end. There is no 696 // particular reason for this ordering other than to match MSVC. 697 emitBuildInfo(); 698 699 // Emit type information and hashes last, so that any types we translate while 700 // emitting function info are included. 701 emitTypeInformation(); 702 703 if (EmitDebugGlobalHashes) 704 emitTypeGlobalHashes(); 705 706 clear(); 707 } 708 709 static void 710 emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, 711 unsigned MaxFixedRecordLength = 0xF00) { 712 // The maximum CV record length is 0xFF00. Most of the strings we emit appear 713 // after a fixed length portion of the record. The fixed length portion should 714 // always be less than 0xF00 (3840) bytes, so truncate the string so that the 715 // overall record size is less than the maximum allowed. 716 SmallString<32> NullTerminatedString( 717 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1)); 718 NullTerminatedString.push_back('\0'); 719 OS.emitBytes(NullTerminatedString); 720 } 721 722 void CodeViewDebug::emitTypeInformation() { 723 if (TypeTable.empty()) 724 return; 725 726 // Start the .debug$T or .debug$P section with 0x4. 727 OS.switchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 728 emitCodeViewMagicVersion(); 729 730 TypeTableCollection Table(TypeTable.records()); 731 TypeVisitorCallbackPipeline Pipeline; 732 733 // To emit type record using Codeview MCStreamer adapter 734 CVMCAdapter CVMCOS(OS, Table); 735 TypeRecordMapping typeMapping(CVMCOS); 736 Pipeline.addCallbackToPipeline(typeMapping); 737 738 std::optional<TypeIndex> B = Table.getFirst(); 739 while (B) { 740 // This will fail if the record data is invalid. 741 CVType Record = Table.getType(*B); 742 743 Error E = codeview::visitTypeRecord(Record, *B, Pipeline); 744 745 if (E) { 746 logAllUnhandledErrors(std::move(E), errs(), "error: "); 747 llvm_unreachable("produced malformed type record"); 748 } 749 750 B = Table.getNext(*B); 751 } 752 } 753 754 void CodeViewDebug::emitTypeGlobalHashes() { 755 if (TypeTable.empty()) 756 return; 757 758 // Start the .debug$H section with the version and hash algorithm, currently 759 // hardcoded to version 0, SHA1. 760 OS.switchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection()); 761 762 OS.emitValueToAlignment(Align(4)); 763 OS.AddComment("Magic"); 764 OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC); 765 OS.AddComment("Section Version"); 766 OS.emitInt16(0); 767 OS.AddComment("Hash Algorithm"); 768 OS.emitInt16(uint16_t(GlobalTypeHashAlg::BLAKE3)); 769 770 TypeIndex TI(TypeIndex::FirstNonSimpleIndex); 771 for (const auto &GHR : TypeTable.hashes()) { 772 if (OS.isVerboseAsm()) { 773 // Emit an EOL-comment describing which TypeIndex this hash corresponds 774 // to, as well as the stringified SHA1 hash. 775 SmallString<32> Comment; 776 raw_svector_ostream CommentOS(Comment); 777 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR); 778 OS.AddComment(Comment); 779 ++TI; 780 } 781 assert(GHR.Hash.size() == 8); 782 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()), 783 GHR.Hash.size()); 784 OS.emitBinaryData(S); 785 } 786 } 787 788 void CodeViewDebug::emitObjName() { 789 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME); 790 791 StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug); 792 llvm::SmallString<256> PathStore(PathRef); 793 794 if (PathRef.empty() || PathRef == "-") { 795 // Don't emit the filename if we're writing to stdout or to /dev/null. 796 PathRef = {}; 797 } else { 798 PathRef = PathStore; 799 } 800 801 OS.AddComment("Signature"); 802 OS.emitIntValue(0, 4); 803 804 OS.AddComment("Object name"); 805 emitNullTerminatedSymbolName(OS, PathRef); 806 807 endSymbolRecord(CompilerEnd); 808 } 809 810 namespace { 811 struct Version { 812 int Part[4]; 813 }; 814 } // end anonymous namespace 815 816 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out 817 // the version number. 818 static Version parseVersion(StringRef Name) { 819 Version V = {{0}}; 820 int N = 0; 821 for (const char C : Name) { 822 if (isdigit(C)) { 823 V.Part[N] *= 10; 824 V.Part[N] += C - '0'; 825 V.Part[N] = 826 std::min<int>(V.Part[N], std::numeric_limits<uint16_t>::max()); 827 } else if (C == '.') { 828 ++N; 829 if (N >= 4) 830 return V; 831 } else if (N > 0) 832 return V; 833 } 834 return V; 835 } 836 837 void CodeViewDebug::emitCompilerInformation() { 838 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3); 839 uint32_t Flags = 0; 840 841 // The low byte of the flags indicates the source language. 842 Flags = CurrentSourceLanguage; 843 // TODO: Figure out which other flags need to be set. 844 if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) { 845 Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO); 846 } 847 using ArchType = llvm::Triple::ArchType; 848 ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch(); 849 if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb || 850 Arch == ArchType::aarch64) { 851 Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch); 852 } 853 854 OS.AddComment("Flags and language"); 855 OS.emitInt32(Flags); 856 857 OS.AddComment("CPUType"); 858 OS.emitInt16(static_cast<uint64_t>(TheCPU)); 859 860 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 861 const MDNode *Node = *CUs->operands().begin(); 862 const auto *CU = cast<DICompileUnit>(Node); 863 864 StringRef CompilerVersion = CU->getProducer(); 865 Version FrontVer = parseVersion(CompilerVersion); 866 OS.AddComment("Frontend version"); 867 for (int N : FrontVer.Part) { 868 OS.emitInt16(N); 869 } 870 871 // Some Microsoft tools, like Binscope, expect a backend version number of at 872 // least 8.something, so we'll coerce the LLVM version into a form that 873 // guarantees it'll be big enough without really lying about the version. 874 int Major = 1000 * LLVM_VERSION_MAJOR + 875 10 * LLVM_VERSION_MINOR + 876 LLVM_VERSION_PATCH; 877 // Clamp it for builds that use unusually large version numbers. 878 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max()); 879 Version BackVer = {{ Major, 0, 0, 0 }}; 880 OS.AddComment("Backend version"); 881 for (int N : BackVer.Part) 882 OS.emitInt16(N); 883 884 OS.AddComment("Null-terminated compiler version string"); 885 emitNullTerminatedSymbolName(OS, CompilerVersion); 886 887 endSymbolRecord(CompilerEnd); 888 } 889 890 static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, 891 StringRef S) { 892 StringIdRecord SIR(TypeIndex(0x0), S); 893 return TypeTable.writeLeafType(SIR); 894 } 895 896 static std::string flattenCommandLine(ArrayRef<std::string> Args, 897 StringRef MainFilename) { 898 std::string FlatCmdLine; 899 raw_string_ostream OS(FlatCmdLine); 900 bool PrintedOneArg = false; 901 if (!StringRef(Args[0]).contains("-cc1")) { 902 llvm::sys::printArg(OS, "-cc1", /*Quote=*/true); 903 PrintedOneArg = true; 904 } 905 for (unsigned i = 0; i < Args.size(); i++) { 906 StringRef Arg = Args[i]; 907 if (Arg.empty()) 908 continue; 909 if (Arg == "-main-file-name" || Arg == "-o") { 910 i++; // Skip this argument and next one. 911 continue; 912 } 913 if (Arg.startswith("-object-file-name") || Arg == MainFilename) 914 continue; 915 // Skip fmessage-length for reproduciability. 916 if (Arg.startswith("-fmessage-length")) 917 continue; 918 if (PrintedOneArg) 919 OS << " "; 920 llvm::sys::printArg(OS, Arg, /*Quote=*/true); 921 PrintedOneArg = true; 922 } 923 OS.flush(); 924 return FlatCmdLine; 925 } 926 927 void CodeViewDebug::emitBuildInfo() { 928 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of 929 // build info. The known prefix is: 930 // - Absolute path of current directory 931 // - Compiler path 932 // - Main source file path, relative to CWD or absolute 933 // - Type server PDB file 934 // - Canonical compiler command line 935 // If frontend and backend compilation are separated (think llc or LTO), it's 936 // not clear if the compiler path should refer to the executable for the 937 // frontend or the backend. Leave it blank for now. 938 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {}; 939 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 940 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs. 941 const auto *CU = cast<DICompileUnit>(Node); 942 const DIFile *MainSourceFile = CU->getFile(); 943 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] = 944 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory()); 945 BuildInfoArgs[BuildInfoRecord::SourceFile] = 946 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename()); 947 // FIXME: PDB is intentionally blank unless we implement /Zi type servers. 948 BuildInfoArgs[BuildInfoRecord::TypeServerPDB] = 949 getStringIdTypeIdx(TypeTable, ""); 950 if (Asm->TM.Options.MCOptions.Argv0 != nullptr) { 951 BuildInfoArgs[BuildInfoRecord::BuildTool] = 952 getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0); 953 BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx( 954 TypeTable, flattenCommandLine(Asm->TM.Options.MCOptions.CommandLineArgs, 955 MainSourceFile->getFilename())); 956 } 957 BuildInfoRecord BIR(BuildInfoArgs); 958 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR); 959 960 // Make a new .debug$S subsection for the S_BUILDINFO record, which points 961 // from the module symbols into the type stream. 962 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 963 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO); 964 OS.AddComment("LF_BUILDINFO index"); 965 OS.emitInt32(BuildInfoIndex.getIndex()); 966 endSymbolRecord(BIEnd); 967 endCVSubsection(BISubsecEnd); 968 } 969 970 void CodeViewDebug::emitInlineeLinesSubsection() { 971 if (InlinedSubprograms.empty()) 972 return; 973 974 OS.AddComment("Inlinee lines subsection"); 975 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines); 976 977 // We emit the checksum info for files. This is used by debuggers to 978 // determine if a pdb matches the source before loading it. Visual Studio, 979 // for instance, will display a warning that the breakpoints are not valid if 980 // the pdb does not match the source. 981 OS.AddComment("Inlinee lines signature"); 982 OS.emitInt32(unsigned(InlineeLinesSignature::Normal)); 983 984 for (const DISubprogram *SP : InlinedSubprograms) { 985 assert(TypeIndices.count({SP, nullptr})); 986 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 987 988 OS.addBlankLine(); 989 unsigned FileId = maybeRecordFile(SP->getFile()); 990 OS.AddComment("Inlined function " + SP->getName() + " starts at " + 991 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 992 OS.addBlankLine(); 993 OS.AddComment("Type index of inlined function"); 994 OS.emitInt32(InlineeIdx.getIndex()); 995 OS.AddComment("Offset into filechecksum table"); 996 OS.emitCVFileChecksumOffsetDirective(FileId); 997 OS.AddComment("Starting line number"); 998 OS.emitInt32(SP->getLine()); 999 } 1000 1001 endCVSubsection(InlineEnd); 1002 } 1003 1004 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 1005 const DILocation *InlinedAt, 1006 const InlineSite &Site) { 1007 assert(TypeIndices.count({Site.Inlinee, nullptr})); 1008 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 1009 1010 // SymbolRecord 1011 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE); 1012 1013 OS.AddComment("PtrParent"); 1014 OS.emitInt32(0); 1015 OS.AddComment("PtrEnd"); 1016 OS.emitInt32(0); 1017 OS.AddComment("Inlinee type index"); 1018 OS.emitInt32(InlineeIdx.getIndex()); 1019 1020 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 1021 unsigned StartLineNum = Site.Inlinee->getLine(); 1022 1023 OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 1024 FI.Begin, FI.End); 1025 1026 endSymbolRecord(InlineEnd); 1027 1028 emitLocalVariableList(FI, Site.InlinedLocals); 1029 1030 // Recurse on child inlined call sites before closing the scope. 1031 for (const DILocation *ChildSite : Site.ChildSites) { 1032 auto I = FI.InlineSites.find(ChildSite); 1033 assert(I != FI.InlineSites.end() && 1034 "child site not in function inline site map"); 1035 emitInlinedCallSite(FI, ChildSite, I->second); 1036 } 1037 1038 // Close the scope. 1039 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END); 1040 } 1041 1042 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 1043 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 1044 // comdat key. A section may be comdat because of -ffunction-sections or 1045 // because it is comdat in the IR. 1046 MCSectionCOFF *GVSec = 1047 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 1048 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 1049 1050 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 1051 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 1052 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 1053 1054 OS.switchSection(DebugSec); 1055 1056 // Emit the magic version number if this is the first time we've switched to 1057 // this section. 1058 if (ComdatDebugSections.insert(DebugSec).second) 1059 emitCodeViewMagicVersion(); 1060 } 1061 1062 // Emit an S_THUNK32/S_END symbol pair for a thunk routine. 1063 // The only supported thunk ordinal is currently the standard type. 1064 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV, 1065 FunctionInfo &FI, 1066 const MCSymbol *Fn) { 1067 std::string FuncName = 1068 std::string(GlobalValue::dropLLVMManglingEscape(GV->getName())); 1069 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind. 1070 1071 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 1072 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 1073 1074 // Emit S_THUNK32 1075 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32); 1076 OS.AddComment("PtrParent"); 1077 OS.emitInt32(0); 1078 OS.AddComment("PtrEnd"); 1079 OS.emitInt32(0); 1080 OS.AddComment("PtrNext"); 1081 OS.emitInt32(0); 1082 OS.AddComment("Thunk section relative address"); 1083 OS.emitCOFFSecRel32(Fn, /*Offset=*/0); 1084 OS.AddComment("Thunk section index"); 1085 OS.emitCOFFSectionIndex(Fn); 1086 OS.AddComment("Code size"); 1087 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2); 1088 OS.AddComment("Ordinal"); 1089 OS.emitInt8(unsigned(ordinal)); 1090 OS.AddComment("Function name"); 1091 emitNullTerminatedSymbolName(OS, FuncName); 1092 // Additional fields specific to the thunk ordinal would go here. 1093 endSymbolRecord(ThunkRecordEnd); 1094 1095 // Local variables/inlined routines are purposely omitted here. The point of 1096 // marking this as a thunk is so Visual Studio will NOT stop in this routine. 1097 1098 // Emit S_PROC_ID_END 1099 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); 1100 1101 endCVSubsection(SymbolsEnd); 1102 } 1103 1104 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 1105 FunctionInfo &FI) { 1106 // For each function there is a separate subsection which holds the PC to 1107 // file:line table. 1108 const MCSymbol *Fn = Asm->getSymbol(GV); 1109 assert(Fn); 1110 1111 // Switch to the to a comdat section, if appropriate. 1112 switchToDebugSectionForSymbol(Fn); 1113 1114 std::string FuncName; 1115 auto *SP = GV->getSubprogram(); 1116 assert(SP); 1117 setCurrentSubprogram(SP); 1118 1119 if (SP->isThunk()) { 1120 emitDebugInfoForThunk(GV, FI, Fn); 1121 return; 1122 } 1123 1124 // If we have a display name, build the fully qualified name by walking the 1125 // chain of scopes. 1126 if (!SP->getName().empty()) 1127 FuncName = getFullyQualifiedName(SP->getScope(), SP->getName()); 1128 1129 // If our DISubprogram name is empty, use the mangled name. 1130 if (FuncName.empty()) 1131 FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName())); 1132 1133 // Emit FPO data, but only on 32-bit x86. No other platforms use it. 1134 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86) 1135 OS.emitCVFPOData(Fn); 1136 1137 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 1138 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 1139 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 1140 { 1141 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID 1142 : SymbolKind::S_GPROC32_ID; 1143 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind); 1144 1145 // These fields are filled in by tools like CVPACK which run after the fact. 1146 OS.AddComment("PtrParent"); 1147 OS.emitInt32(0); 1148 OS.AddComment("PtrEnd"); 1149 OS.emitInt32(0); 1150 OS.AddComment("PtrNext"); 1151 OS.emitInt32(0); 1152 // This is the important bit that tells the debugger where the function 1153 // code is located and what's its size: 1154 OS.AddComment("Code size"); 1155 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 1156 OS.AddComment("Offset after prologue"); 1157 OS.emitInt32(0); 1158 OS.AddComment("Offset before epilogue"); 1159 OS.emitInt32(0); 1160 OS.AddComment("Function type index"); 1161 OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex()); 1162 OS.AddComment("Function section relative address"); 1163 OS.emitCOFFSecRel32(Fn, /*Offset=*/0); 1164 OS.AddComment("Function section index"); 1165 OS.emitCOFFSectionIndex(Fn); 1166 OS.AddComment("Flags"); 1167 ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo; 1168 if (FI.HasFramePointer) 1169 ProcFlags |= ProcSymFlags::HasFP; 1170 if (GV->hasFnAttribute(Attribute::NoReturn)) 1171 ProcFlags |= ProcSymFlags::IsNoReturn; 1172 if (GV->hasFnAttribute(Attribute::NoInline)) 1173 ProcFlags |= ProcSymFlags::IsNoInline; 1174 OS.emitInt8(static_cast<uint8_t>(ProcFlags)); 1175 // Emit the function display name as a null-terminated string. 1176 OS.AddComment("Function name"); 1177 // Truncate the name so we won't overflow the record length field. 1178 emitNullTerminatedSymbolName(OS, FuncName); 1179 endSymbolRecord(ProcRecordEnd); 1180 1181 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC); 1182 // Subtract out the CSR size since MSVC excludes that and we include it. 1183 OS.AddComment("FrameSize"); 1184 OS.emitInt32(FI.FrameSize - FI.CSRSize); 1185 OS.AddComment("Padding"); 1186 OS.emitInt32(0); 1187 OS.AddComment("Offset of padding"); 1188 OS.emitInt32(0); 1189 OS.AddComment("Bytes of callee saved registers"); 1190 OS.emitInt32(FI.CSRSize); 1191 OS.AddComment("Exception handler offset"); 1192 OS.emitInt32(0); 1193 OS.AddComment("Exception handler section"); 1194 OS.emitInt16(0); 1195 OS.AddComment("Flags (defines frame register)"); 1196 OS.emitInt32(uint32_t(FI.FrameProcOpts)); 1197 endSymbolRecord(FrameProcEnd); 1198 1199 emitInlinees(FI.Inlinees); 1200 emitLocalVariableList(FI, FI.Locals); 1201 emitGlobalVariableList(FI.Globals); 1202 emitLexicalBlockList(FI.ChildBlocks, FI); 1203 1204 // Emit inlined call site information. Only emit functions inlined directly 1205 // into the parent function. We'll emit the other sites recursively as part 1206 // of their parent inline site. 1207 for (const DILocation *InlinedAt : FI.ChildSites) { 1208 auto I = FI.InlineSites.find(InlinedAt); 1209 assert(I != FI.InlineSites.end() && 1210 "child site not in function inline site map"); 1211 emitInlinedCallSite(FI, InlinedAt, I->second); 1212 } 1213 1214 for (auto Annot : FI.Annotations) { 1215 MCSymbol *Label = Annot.first; 1216 MDTuple *Strs = cast<MDTuple>(Annot.second); 1217 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION); 1218 OS.emitCOFFSecRel32(Label, /*Offset=*/0); 1219 // FIXME: Make sure we don't overflow the max record size. 1220 OS.emitCOFFSectionIndex(Label); 1221 OS.emitInt16(Strs->getNumOperands()); 1222 for (Metadata *MD : Strs->operands()) { 1223 // MDStrings are null terminated, so we can do EmitBytes and get the 1224 // nice .asciz directive. 1225 StringRef Str = cast<MDString>(MD)->getString(); 1226 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString"); 1227 OS.emitBytes(StringRef(Str.data(), Str.size() + 1)); 1228 } 1229 endSymbolRecord(AnnotEnd); 1230 } 1231 1232 for (auto HeapAllocSite : FI.HeapAllocSites) { 1233 const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite); 1234 const MCSymbol *EndLabel = std::get<1>(HeapAllocSite); 1235 const DIType *DITy = std::get<2>(HeapAllocSite); 1236 MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE); 1237 OS.AddComment("Call site offset"); 1238 OS.emitCOFFSecRel32(BeginLabel, /*Offset=*/0); 1239 OS.AddComment("Call site section index"); 1240 OS.emitCOFFSectionIndex(BeginLabel); 1241 OS.AddComment("Call instruction length"); 1242 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); 1243 OS.AddComment("Type index"); 1244 OS.emitInt32(getCompleteTypeIndex(DITy).getIndex()); 1245 endSymbolRecord(HeapAllocEnd); 1246 } 1247 1248 if (SP != nullptr) 1249 emitDebugInfoForUDTs(LocalUDTs); 1250 1251 emitDebugInfoForJumpTables(FI); 1252 1253 // We're done with this function. 1254 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); 1255 } 1256 endCVSubsection(SymbolsEnd); 1257 1258 // We have an assembler directive that takes care of the whole line table. 1259 OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End); 1260 } 1261 1262 CodeViewDebug::LocalVarDef 1263 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 1264 LocalVarDef DR; 1265 DR.InMemory = -1; 1266 DR.DataOffset = Offset; 1267 assert(DR.DataOffset == Offset && "truncation"); 1268 DR.IsSubfield = 0; 1269 DR.StructOffset = 0; 1270 DR.CVRegister = CVRegister; 1271 return DR; 1272 } 1273 1274 void CodeViewDebug::collectVariableInfoFromMFTable( 1275 DenseSet<InlinedEntity> &Processed) { 1276 const MachineFunction &MF = *Asm->MF; 1277 const TargetSubtargetInfo &TSI = MF.getSubtarget(); 1278 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 1279 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 1280 1281 for (const MachineFunction::VariableDbgInfo &VI : 1282 MF.getInStackSlotVariableDbgInfo()) { 1283 if (!VI.Var) 1284 continue; 1285 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1286 "Expected inlined-at fields to agree"); 1287 1288 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt())); 1289 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1290 1291 // If variable scope is not found then skip this variable. 1292 if (!Scope) 1293 continue; 1294 1295 // If the variable has an attached offset expression, extract it. 1296 // FIXME: Try to handle DW_OP_deref as well. 1297 int64_t ExprOffset = 0; 1298 bool Deref = false; 1299 if (VI.Expr) { 1300 // If there is one DW_OP_deref element, use offset of 0 and keep going. 1301 if (VI.Expr->getNumElements() == 1 && 1302 VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref) 1303 Deref = true; 1304 else if (!VI.Expr->extractIfOffset(ExprOffset)) 1305 continue; 1306 } 1307 1308 // Get the frame register used and the offset. 1309 Register FrameReg; 1310 StackOffset FrameOffset = 1311 TFI->getFrameIndexReference(*Asm->MF, VI.getStackSlot(), FrameReg); 1312 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 1313 1314 assert(!FrameOffset.getScalable() && 1315 "Frame offsets with a scalable component are not supported"); 1316 1317 // Calculate the label ranges. 1318 LocalVarDef DefRange = 1319 createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset); 1320 1321 LocalVariable Var; 1322 Var.DIVar = VI.Var; 1323 1324 for (const InsnRange &Range : Scope->getRanges()) { 1325 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 1326 const MCSymbol *End = getLabelAfterInsn(Range.second); 1327 End = End ? End : Asm->getFunctionEnd(); 1328 Var.DefRanges[DefRange].emplace_back(Begin, End); 1329 } 1330 1331 if (Deref) 1332 Var.UseReferenceType = true; 1333 1334 recordLocalVariable(std::move(Var), Scope); 1335 } 1336 } 1337 1338 static bool canUseReferenceType(const DbgVariableLocation &Loc) { 1339 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0; 1340 } 1341 1342 static bool needsReferenceType(const DbgVariableLocation &Loc) { 1343 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0; 1344 } 1345 1346 void CodeViewDebug::calculateRanges( 1347 LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) { 1348 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 1349 1350 // Calculate the definition ranges. 1351 for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) { 1352 const auto &Entry = *I; 1353 if (!Entry.isDbgValue()) 1354 continue; 1355 const MachineInstr *DVInst = Entry.getInstr(); 1356 assert(DVInst->isDebugValue() && "Invalid History entry"); 1357 // FIXME: Find a way to represent constant variables, since they are 1358 // relatively common. 1359 std::optional<DbgVariableLocation> Location = 1360 DbgVariableLocation::extractFromMachineInstruction(*DVInst); 1361 if (!Location) 1362 { 1363 // When we don't have a location this is usually because LLVM has 1364 // transformed it into a constant and we only have an llvm.dbg.value. We 1365 // can't represent these well in CodeView since S_LOCAL only works on 1366 // registers and memory locations. Instead, we will pretend this to be a 1367 // constant value to at least have it show up in the debugger. 1368 auto Op = DVInst->getDebugOperand(0); 1369 if (Op.isImm()) 1370 Var.ConstantValue = APSInt(APInt(64, Op.getImm()), false); 1371 continue; 1372 } 1373 1374 // CodeView can only express variables in register and variables in memory 1375 // at a constant offset from a register. However, for variables passed 1376 // indirectly by pointer, it is common for that pointer to be spilled to a 1377 // stack location. For the special case of one offseted load followed by a 1378 // zero offset load (a pointer spilled to the stack), we change the type of 1379 // the local variable from a value type to a reference type. This tricks the 1380 // debugger into doing the load for us. 1381 if (Var.UseReferenceType) { 1382 // We're using a reference type. Drop the last zero offset load. 1383 if (canUseReferenceType(*Location)) 1384 Location->LoadChain.pop_back(); 1385 else 1386 continue; 1387 } else if (needsReferenceType(*Location)) { 1388 // This location can't be expressed without switching to a reference type. 1389 // Start over using that. 1390 Var.UseReferenceType = true; 1391 Var.DefRanges.clear(); 1392 calculateRanges(Var, Entries); 1393 return; 1394 } 1395 1396 // We can only handle a register or an offseted load of a register. 1397 if (Location->Register == 0 || Location->LoadChain.size() > 1) 1398 continue; 1399 1400 LocalVarDef DR; 1401 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register); 1402 DR.InMemory = !Location->LoadChain.empty(); 1403 DR.DataOffset = 1404 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0; 1405 if (Location->FragmentInfo) { 1406 DR.IsSubfield = true; 1407 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8; 1408 } else { 1409 DR.IsSubfield = false; 1410 DR.StructOffset = 0; 1411 } 1412 1413 // Compute the label range. 1414 const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr()); 1415 const MCSymbol *End; 1416 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) { 1417 auto &EndingEntry = Entries[Entry.getEndIndex()]; 1418 End = EndingEntry.isDbgValue() 1419 ? getLabelBeforeInsn(EndingEntry.getInstr()) 1420 : getLabelAfterInsn(EndingEntry.getInstr()); 1421 } else 1422 End = Asm->getFunctionEnd(); 1423 1424 // If the last range end is our begin, just extend the last range. 1425 // Otherwise make a new range. 1426 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R = 1427 Var.DefRanges[DR]; 1428 if (!R.empty() && R.back().second == Begin) 1429 R.back().second = End; 1430 else 1431 R.emplace_back(Begin, End); 1432 1433 // FIXME: Do more range combining. 1434 } 1435 } 1436 1437 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 1438 DenseSet<InlinedEntity> Processed; 1439 // Grab the variable info that was squirreled away in the MMI side-table. 1440 collectVariableInfoFromMFTable(Processed); 1441 1442 for (const auto &I : DbgValues) { 1443 InlinedEntity IV = I.first; 1444 if (Processed.count(IV)) 1445 continue; 1446 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first); 1447 const DILocation *InlinedAt = IV.second; 1448 1449 // Instruction ranges, specifying where IV is accessible. 1450 const auto &Entries = I.second; 1451 1452 LexicalScope *Scope = nullptr; 1453 if (InlinedAt) 1454 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 1455 else 1456 Scope = LScopes.findLexicalScope(DIVar->getScope()); 1457 // If variable scope is not found then skip this variable. 1458 if (!Scope) 1459 continue; 1460 1461 LocalVariable Var; 1462 Var.DIVar = DIVar; 1463 1464 calculateRanges(Var, Entries); 1465 recordLocalVariable(std::move(Var), Scope); 1466 } 1467 } 1468 1469 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) { 1470 const TargetSubtargetInfo &TSI = MF->getSubtarget(); 1471 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 1472 const MachineFrameInfo &MFI = MF->getFrameInfo(); 1473 const Function &GV = MF->getFunction(); 1474 auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()}); 1475 assert(Insertion.second && "function already has info"); 1476 CurFn = Insertion.first->second.get(); 1477 CurFn->FuncId = NextFuncId++; 1478 CurFn->Begin = Asm->getFunctionBegin(); 1479 1480 // The S_FRAMEPROC record reports the stack size, and how many bytes of 1481 // callee-saved registers were used. For targets that don't use a PUSH 1482 // instruction (AArch64), this will be zero. 1483 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters(); 1484 CurFn->FrameSize = MFI.getStackSize(); 1485 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment(); 1486 CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF); 1487 1488 // For this function S_FRAMEPROC record, figure out which codeview register 1489 // will be the frame pointer. 1490 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None. 1491 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None. 1492 if (CurFn->FrameSize > 0) { 1493 if (!TSI.getFrameLowering()->hasFP(*MF)) { 1494 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; 1495 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr; 1496 } else { 1497 CurFn->HasFramePointer = true; 1498 // If there is an FP, parameters are always relative to it. 1499 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr; 1500 if (CurFn->HasStackRealignment) { 1501 // If the stack needs realignment, locals are relative to SP or VFRAME. 1502 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; 1503 } else { 1504 // Otherwise, locals are relative to EBP, and we probably have VLAs or 1505 // other stack adjustments. 1506 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr; 1507 } 1508 } 1509 } 1510 1511 // Compute other frame procedure options. 1512 FrameProcedureOptions FPO = FrameProcedureOptions::None; 1513 if (MFI.hasVarSizedObjects()) 1514 FPO |= FrameProcedureOptions::HasAlloca; 1515 if (MF->exposesReturnsTwice()) 1516 FPO |= FrameProcedureOptions::HasSetJmp; 1517 // FIXME: Set HasLongJmp if we ever track that info. 1518 if (MF->hasInlineAsm()) 1519 FPO |= FrameProcedureOptions::HasInlineAssembly; 1520 if (GV.hasPersonalityFn()) { 1521 if (isAsynchronousEHPersonality( 1522 classifyEHPersonality(GV.getPersonalityFn()))) 1523 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling; 1524 else 1525 FPO |= FrameProcedureOptions::HasExceptionHandling; 1526 } 1527 if (GV.hasFnAttribute(Attribute::InlineHint)) 1528 FPO |= FrameProcedureOptions::MarkedInline; 1529 if (GV.hasFnAttribute(Attribute::Naked)) 1530 FPO |= FrameProcedureOptions::Naked; 1531 if (MFI.hasStackProtectorIndex()) { 1532 FPO |= FrameProcedureOptions::SecurityChecks; 1533 if (GV.hasFnAttribute(Attribute::StackProtectStrong) || 1534 GV.hasFnAttribute(Attribute::StackProtectReq)) { 1535 FPO |= FrameProcedureOptions::StrictSecurityChecks; 1536 } 1537 } else if (!GV.hasStackProtectorFnAttr()) { 1538 // __declspec(safebuffers) disables stack guards. 1539 FPO |= FrameProcedureOptions::SafeBuffers; 1540 } 1541 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U); 1542 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U); 1543 if (Asm->TM.getOptLevel() != CodeGenOptLevel::None && !GV.hasOptSize() && 1544 !GV.hasOptNone()) 1545 FPO |= FrameProcedureOptions::OptimizedForSpeed; 1546 if (GV.hasProfileData()) { 1547 FPO |= FrameProcedureOptions::ValidProfileCounts; 1548 FPO |= FrameProcedureOptions::ProfileGuidedOptimization; 1549 } 1550 // FIXME: Set GuardCfg when it is implemented. 1551 CurFn->FrameProcOpts = FPO; 1552 1553 OS.emitCVFuncIdDirective(CurFn->FuncId); 1554 1555 // Find the end of the function prolog. First known non-DBG_VALUE and 1556 // non-frame setup location marks the beginning of the function body. 1557 // FIXME: is there a simpler a way to do this? Can we just search 1558 // for the first instruction of the function, not the last of the prolog? 1559 DebugLoc PrologEndLoc; 1560 bool EmptyPrologue = true; 1561 for (const auto &MBB : *MF) { 1562 for (const auto &MI : MBB) { 1563 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1564 MI.getDebugLoc()) { 1565 PrologEndLoc = MI.getDebugLoc(); 1566 break; 1567 } else if (!MI.isMetaInstruction()) { 1568 EmptyPrologue = false; 1569 } 1570 } 1571 } 1572 1573 // Record beginning of function if we have a non-empty prologue. 1574 if (PrologEndLoc && !EmptyPrologue) { 1575 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 1576 maybeRecordLocation(FnStartDL, MF); 1577 } 1578 1579 // Find heap alloc sites and emit labels around them. 1580 for (const auto &MBB : *MF) { 1581 for (const auto &MI : MBB) { 1582 if (MI.getHeapAllocMarker()) { 1583 requestLabelBeforeInsn(&MI); 1584 requestLabelAfterInsn(&MI); 1585 } 1586 } 1587 } 1588 1589 // Mark branches that may potentially be using jump tables with labels. 1590 bool isThumb = Triple(MMI->getModule()->getTargetTriple()).getArch() == 1591 llvm::Triple::ArchType::thumb; 1592 discoverJumpTableBranches(MF, isThumb); 1593 } 1594 1595 static bool shouldEmitUdt(const DIType *T) { 1596 if (!T) 1597 return false; 1598 1599 // MSVC does not emit UDTs for typedefs that are scoped to classes. 1600 if (T->getTag() == dwarf::DW_TAG_typedef) { 1601 if (DIScope *Scope = T->getScope()) { 1602 switch (Scope->getTag()) { 1603 case dwarf::DW_TAG_structure_type: 1604 case dwarf::DW_TAG_class_type: 1605 case dwarf::DW_TAG_union_type: 1606 return false; 1607 default: 1608 // do nothing. 1609 ; 1610 } 1611 } 1612 } 1613 1614 while (true) { 1615 if (!T || T->isForwardDecl()) 1616 return false; 1617 1618 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T); 1619 if (!DT) 1620 return true; 1621 T = DT->getBaseType(); 1622 } 1623 return true; 1624 } 1625 1626 void CodeViewDebug::addToUDTs(const DIType *Ty) { 1627 // Don't record empty UDTs. 1628 if (Ty->getName().empty()) 1629 return; 1630 if (!shouldEmitUdt(Ty)) 1631 return; 1632 1633 SmallVector<StringRef, 5> ParentScopeNames; 1634 const DISubprogram *ClosestSubprogram = 1635 collectParentScopeNames(Ty->getScope(), ParentScopeNames); 1636 1637 std::string FullyQualifiedName = 1638 formatNestedName(ParentScopeNames, getPrettyScopeName(Ty)); 1639 1640 if (ClosestSubprogram == nullptr) { 1641 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); 1642 } else if (ClosestSubprogram == CurrentSubprogram) { 1643 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); 1644 } 1645 1646 // TODO: What if the ClosestSubprogram is neither null or the current 1647 // subprogram? Currently, the UDT just gets dropped on the floor. 1648 // 1649 // The current behavior is not desirable. To get maximal fidelity, we would 1650 // need to perform all type translation before beginning emission of .debug$S 1651 // and then make LocalUDTs a member of FunctionInfo 1652 } 1653 1654 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 1655 // Generic dispatch for lowering an unknown type. 1656 switch (Ty->getTag()) { 1657 case dwarf::DW_TAG_array_type: 1658 return lowerTypeArray(cast<DICompositeType>(Ty)); 1659 case dwarf::DW_TAG_typedef: 1660 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 1661 case dwarf::DW_TAG_base_type: 1662 return lowerTypeBasic(cast<DIBasicType>(Ty)); 1663 case dwarf::DW_TAG_pointer_type: 1664 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type") 1665 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty)); 1666 [[fallthrough]]; 1667 case dwarf::DW_TAG_reference_type: 1668 case dwarf::DW_TAG_rvalue_reference_type: 1669 return lowerTypePointer(cast<DIDerivedType>(Ty)); 1670 case dwarf::DW_TAG_ptr_to_member_type: 1671 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 1672 case dwarf::DW_TAG_restrict_type: 1673 case dwarf::DW_TAG_const_type: 1674 case dwarf::DW_TAG_volatile_type: 1675 // TODO: add support for DW_TAG_atomic_type here 1676 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 1677 case dwarf::DW_TAG_subroutine_type: 1678 if (ClassTy) { 1679 // The member function type of a member function pointer has no 1680 // ThisAdjustment. 1681 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, 1682 /*ThisAdjustment=*/0, 1683 /*IsStaticMethod=*/false); 1684 } 1685 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 1686 case dwarf::DW_TAG_enumeration_type: 1687 return lowerTypeEnum(cast<DICompositeType>(Ty)); 1688 case dwarf::DW_TAG_class_type: 1689 case dwarf::DW_TAG_structure_type: 1690 return lowerTypeClass(cast<DICompositeType>(Ty)); 1691 case dwarf::DW_TAG_union_type: 1692 return lowerTypeUnion(cast<DICompositeType>(Ty)); 1693 case dwarf::DW_TAG_string_type: 1694 return lowerTypeString(cast<DIStringType>(Ty)); 1695 case dwarf::DW_TAG_unspecified_type: 1696 if (Ty->getName() == "decltype(nullptr)") 1697 return TypeIndex::NullptrT(); 1698 return TypeIndex::None(); 1699 default: 1700 // Use the null type index. 1701 return TypeIndex(); 1702 } 1703 } 1704 1705 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 1706 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType()); 1707 StringRef TypeName = Ty->getName(); 1708 1709 addToUDTs(Ty); 1710 1711 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 1712 TypeName == "HRESULT") 1713 return TypeIndex(SimpleTypeKind::HResult); 1714 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 1715 TypeName == "wchar_t") 1716 return TypeIndex(SimpleTypeKind::WideCharacter); 1717 1718 return UnderlyingTypeIndex; 1719 } 1720 1721 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 1722 const DIType *ElementType = Ty->getBaseType(); 1723 TypeIndex ElementTypeIndex = getTypeIndex(ElementType); 1724 // IndexType is size_t, which depends on the bitness of the target. 1725 TypeIndex IndexType = getPointerSizeInBytes() == 8 1726 ? TypeIndex(SimpleTypeKind::UInt64Quad) 1727 : TypeIndex(SimpleTypeKind::UInt32Long); 1728 1729 uint64_t ElementSize = getBaseTypeSize(ElementType) / 8; 1730 1731 // Add subranges to array type. 1732 DINodeArray Elements = Ty->getElements(); 1733 for (int i = Elements.size() - 1; i >= 0; --i) { 1734 const DINode *Element = Elements[i]; 1735 assert(Element->getTag() == dwarf::DW_TAG_subrange_type); 1736 1737 const DISubrange *Subrange = cast<DISubrange>(Element); 1738 int64_t Count = -1; 1739 1740 // If Subrange has a Count field, use it. 1741 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1), 1742 // where lowerbound is from the LowerBound field of the Subrange, 1743 // or the language default lowerbound if that field is unspecified. 1744 if (auto *CI = dyn_cast_if_present<ConstantInt *>(Subrange->getCount())) 1745 Count = CI->getSExtValue(); 1746 else if (auto *UI = dyn_cast_if_present<ConstantInt *>( 1747 Subrange->getUpperBound())) { 1748 // Fortran uses 1 as the default lowerbound; other languages use 0. 1749 int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0; 1750 auto *LI = dyn_cast_if_present<ConstantInt *>(Subrange->getLowerBound()); 1751 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound; 1752 Count = UI->getSExtValue() - Lowerbound + 1; 1753 } 1754 1755 // Forward declarations of arrays without a size and VLAs use a count of -1. 1756 // Emit a count of zero in these cases to match what MSVC does for arrays 1757 // without a size. MSVC doesn't support VLAs, so it's not clear what we 1758 // should do for them even if we could distinguish them. 1759 if (Count == -1) 1760 Count = 0; 1761 1762 // Update the element size and element type index for subsequent subranges. 1763 ElementSize *= Count; 1764 1765 // If this is the outermost array, use the size from the array. It will be 1766 // more accurate if we had a VLA or an incomplete element type size. 1767 uint64_t ArraySize = 1768 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize; 1769 1770 StringRef Name = (i == 0) ? Ty->getName() : ""; 1771 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name); 1772 ElementTypeIndex = TypeTable.writeLeafType(AR); 1773 } 1774 1775 return ElementTypeIndex; 1776 } 1777 1778 // This function lowers a Fortran character type (DIStringType). 1779 // Note that it handles only the character*n variant (using SizeInBits 1780 // field in DIString to describe the type size) at the moment. 1781 // Other variants (leveraging the StringLength and StringLengthExp 1782 // fields in DIStringType) remain TBD. 1783 TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) { 1784 TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter); 1785 uint64_t ArraySize = Ty->getSizeInBits() >> 3; 1786 StringRef Name = Ty->getName(); 1787 // IndexType is size_t, which depends on the bitness of the target. 1788 TypeIndex IndexType = getPointerSizeInBytes() == 8 1789 ? TypeIndex(SimpleTypeKind::UInt64Quad) 1790 : TypeIndex(SimpleTypeKind::UInt32Long); 1791 1792 // Create a type of character array of ArraySize. 1793 ArrayRecord AR(CharType, IndexType, ArraySize, Name); 1794 1795 return TypeTable.writeLeafType(AR); 1796 } 1797 1798 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 1799 TypeIndex Index; 1800 dwarf::TypeKind Kind; 1801 uint32_t ByteSize; 1802 1803 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 1804 ByteSize = Ty->getSizeInBits() / 8; 1805 1806 SimpleTypeKind STK = SimpleTypeKind::None; 1807 switch (Kind) { 1808 case dwarf::DW_ATE_address: 1809 // FIXME: Translate 1810 break; 1811 case dwarf::DW_ATE_boolean: 1812 switch (ByteSize) { 1813 case 1: STK = SimpleTypeKind::Boolean8; break; 1814 case 2: STK = SimpleTypeKind::Boolean16; break; 1815 case 4: STK = SimpleTypeKind::Boolean32; break; 1816 case 8: STK = SimpleTypeKind::Boolean64; break; 1817 case 16: STK = SimpleTypeKind::Boolean128; break; 1818 } 1819 break; 1820 case dwarf::DW_ATE_complex_float: 1821 // The CodeView size for a complex represents the size of 1822 // an individual component. 1823 switch (ByteSize) { 1824 case 4: STK = SimpleTypeKind::Complex16; break; 1825 case 8: STK = SimpleTypeKind::Complex32; break; 1826 case 16: STK = SimpleTypeKind::Complex64; break; 1827 case 20: STK = SimpleTypeKind::Complex80; break; 1828 case 32: STK = SimpleTypeKind::Complex128; break; 1829 } 1830 break; 1831 case dwarf::DW_ATE_float: 1832 switch (ByteSize) { 1833 case 2: STK = SimpleTypeKind::Float16; break; 1834 case 4: STK = SimpleTypeKind::Float32; break; 1835 case 6: STK = SimpleTypeKind::Float48; break; 1836 case 8: STK = SimpleTypeKind::Float64; break; 1837 case 10: STK = SimpleTypeKind::Float80; break; 1838 case 16: STK = SimpleTypeKind::Float128; break; 1839 } 1840 break; 1841 case dwarf::DW_ATE_signed: 1842 switch (ByteSize) { 1843 case 1: STK = SimpleTypeKind::SignedCharacter; break; 1844 case 2: STK = SimpleTypeKind::Int16Short; break; 1845 case 4: STK = SimpleTypeKind::Int32; break; 1846 case 8: STK = SimpleTypeKind::Int64Quad; break; 1847 case 16: STK = SimpleTypeKind::Int128Oct; break; 1848 } 1849 break; 1850 case dwarf::DW_ATE_unsigned: 1851 switch (ByteSize) { 1852 case 1: STK = SimpleTypeKind::UnsignedCharacter; break; 1853 case 2: STK = SimpleTypeKind::UInt16Short; break; 1854 case 4: STK = SimpleTypeKind::UInt32; break; 1855 case 8: STK = SimpleTypeKind::UInt64Quad; break; 1856 case 16: STK = SimpleTypeKind::UInt128Oct; break; 1857 } 1858 break; 1859 case dwarf::DW_ATE_UTF: 1860 switch (ByteSize) { 1861 case 1: STK = SimpleTypeKind::Character8; break; 1862 case 2: STK = SimpleTypeKind::Character16; break; 1863 case 4: STK = SimpleTypeKind::Character32; break; 1864 } 1865 break; 1866 case dwarf::DW_ATE_signed_char: 1867 if (ByteSize == 1) 1868 STK = SimpleTypeKind::SignedCharacter; 1869 break; 1870 case dwarf::DW_ATE_unsigned_char: 1871 if (ByteSize == 1) 1872 STK = SimpleTypeKind::UnsignedCharacter; 1873 break; 1874 default: 1875 break; 1876 } 1877 1878 // Apply some fixups based on the source-level type name. 1879 // Include some amount of canonicalization from an old naming scheme Clang 1880 // used to use for integer types (in an outdated effort to be compatible with 1881 // GCC's debug info/GDB's behavior, which has since been addressed). 1882 if (STK == SimpleTypeKind::Int32 && 1883 (Ty->getName() == "long int" || Ty->getName() == "long")) 1884 STK = SimpleTypeKind::Int32Long; 1885 if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" || 1886 Ty->getName() == "unsigned long")) 1887 STK = SimpleTypeKind::UInt32Long; 1888 if (STK == SimpleTypeKind::UInt16Short && 1889 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 1890 STK = SimpleTypeKind::WideCharacter; 1891 if ((STK == SimpleTypeKind::SignedCharacter || 1892 STK == SimpleTypeKind::UnsignedCharacter) && 1893 Ty->getName() == "char") 1894 STK = SimpleTypeKind::NarrowCharacter; 1895 1896 return TypeIndex(STK); 1897 } 1898 1899 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty, 1900 PointerOptions PO) { 1901 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 1902 1903 // Pointers to simple types without any options can use SimpleTypeMode, rather 1904 // than having a dedicated pointer type record. 1905 if (PointeeTI.isSimple() && PO == PointerOptions::None && 1906 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 1907 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 1908 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 1909 ? SimpleTypeMode::NearPointer64 1910 : SimpleTypeMode::NearPointer32; 1911 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 1912 } 1913 1914 PointerKind PK = 1915 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 1916 PointerMode PM = PointerMode::Pointer; 1917 switch (Ty->getTag()) { 1918 default: llvm_unreachable("not a pointer tag type"); 1919 case dwarf::DW_TAG_pointer_type: 1920 PM = PointerMode::Pointer; 1921 break; 1922 case dwarf::DW_TAG_reference_type: 1923 PM = PointerMode::LValueReference; 1924 break; 1925 case dwarf::DW_TAG_rvalue_reference_type: 1926 PM = PointerMode::RValueReference; 1927 break; 1928 } 1929 1930 if (Ty->isObjectPointer()) 1931 PO |= PointerOptions::Const; 1932 1933 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 1934 return TypeTable.writeLeafType(PR); 1935 } 1936 1937 static PointerToMemberRepresentation 1938 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 1939 // SizeInBytes being zero generally implies that the member pointer type was 1940 // incomplete, which can happen if it is part of a function prototype. In this 1941 // case, use the unknown model instead of the general model. 1942 if (IsPMF) { 1943 switch (Flags & DINode::FlagPtrToMemberRep) { 1944 case 0: 1945 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1946 : PointerToMemberRepresentation::GeneralFunction; 1947 case DINode::FlagSingleInheritance: 1948 return PointerToMemberRepresentation::SingleInheritanceFunction; 1949 case DINode::FlagMultipleInheritance: 1950 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1951 case DINode::FlagVirtualInheritance: 1952 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1953 } 1954 } else { 1955 switch (Flags & DINode::FlagPtrToMemberRep) { 1956 case 0: 1957 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1958 : PointerToMemberRepresentation::GeneralData; 1959 case DINode::FlagSingleInheritance: 1960 return PointerToMemberRepresentation::SingleInheritanceData; 1961 case DINode::FlagMultipleInheritance: 1962 return PointerToMemberRepresentation::MultipleInheritanceData; 1963 case DINode::FlagVirtualInheritance: 1964 return PointerToMemberRepresentation::VirtualInheritanceData; 1965 } 1966 } 1967 llvm_unreachable("invalid ptr to member representation"); 1968 } 1969 1970 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty, 1971 PointerOptions PO) { 1972 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1973 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1974 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1975 TypeIndex PointeeTI = 1976 getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr); 1977 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 1978 : PointerKind::Near32; 1979 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1980 : PointerMode::PointerToDataMember; 1981 1982 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1983 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1984 MemberPointerInfo MPI( 1985 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1986 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1987 return TypeTable.writeLeafType(PR); 1988 } 1989 1990 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1991 /// have a translation, use the NearC convention. 1992 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1993 switch (DwarfCC) { 1994 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1995 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1996 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1997 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1998 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1999 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 2000 } 2001 return CallingConvention::NearC; 2002 } 2003 2004 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 2005 ModifierOptions Mods = ModifierOptions::None; 2006 PointerOptions PO = PointerOptions::None; 2007 bool IsModifier = true; 2008 const DIType *BaseTy = Ty; 2009 while (IsModifier && BaseTy) { 2010 // FIXME: Need to add DWARF tags for __unaligned and _Atomic 2011 switch (BaseTy->getTag()) { 2012 case dwarf::DW_TAG_const_type: 2013 Mods |= ModifierOptions::Const; 2014 PO |= PointerOptions::Const; 2015 break; 2016 case dwarf::DW_TAG_volatile_type: 2017 Mods |= ModifierOptions::Volatile; 2018 PO |= PointerOptions::Volatile; 2019 break; 2020 case dwarf::DW_TAG_restrict_type: 2021 // Only pointer types be marked with __restrict. There is no known flag 2022 // for __restrict in LF_MODIFIER records. 2023 PO |= PointerOptions::Restrict; 2024 break; 2025 default: 2026 IsModifier = false; 2027 break; 2028 } 2029 if (IsModifier) 2030 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType(); 2031 } 2032 2033 // Check if the inner type will use an LF_POINTER record. If so, the 2034 // qualifiers will go in the LF_POINTER record. This comes up for types like 2035 // 'int *const' and 'int *__restrict', not the more common cases like 'const 2036 // char *'. 2037 if (BaseTy) { 2038 switch (BaseTy->getTag()) { 2039 case dwarf::DW_TAG_pointer_type: 2040 case dwarf::DW_TAG_reference_type: 2041 case dwarf::DW_TAG_rvalue_reference_type: 2042 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO); 2043 case dwarf::DW_TAG_ptr_to_member_type: 2044 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO); 2045 default: 2046 break; 2047 } 2048 } 2049 2050 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 2051 2052 // Return the base type index if there aren't any modifiers. For example, the 2053 // metadata could contain restrict wrappers around non-pointer types. 2054 if (Mods == ModifierOptions::None) 2055 return ModifiedTI; 2056 2057 ModifierRecord MR(ModifiedTI, Mods); 2058 return TypeTable.writeLeafType(MR); 2059 } 2060 2061 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 2062 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 2063 for (const DIType *ArgType : Ty->getTypeArray()) 2064 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType)); 2065 2066 // MSVC uses type none for variadic argument. 2067 if (ReturnAndArgTypeIndices.size() > 1 && 2068 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) { 2069 ReturnAndArgTypeIndices.back() = TypeIndex::None(); 2070 } 2071 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 2072 ArrayRef<TypeIndex> ArgTypeIndices = std::nullopt; 2073 if (!ReturnAndArgTypeIndices.empty()) { 2074 auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices); 2075 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 2076 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 2077 } 2078 2079 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 2080 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); 2081 2082 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 2083 2084 FunctionOptions FO = getFunctionOptions(Ty); 2085 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(), 2086 ArgListIndex); 2087 return TypeTable.writeLeafType(Procedure); 2088 } 2089 2090 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 2091 const DIType *ClassTy, 2092 int ThisAdjustment, 2093 bool IsStaticMethod, 2094 FunctionOptions FO) { 2095 // Lower the containing class type. 2096 TypeIndex ClassType = getTypeIndex(ClassTy); 2097 2098 DITypeRefArray ReturnAndArgs = Ty->getTypeArray(); 2099 2100 unsigned Index = 0; 2101 SmallVector<TypeIndex, 8> ArgTypeIndices; 2102 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 2103 if (ReturnAndArgs.size() > Index) { 2104 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]); 2105 } 2106 2107 // If the first argument is a pointer type and this isn't a static method, 2108 // treat it as the special 'this' parameter, which is encoded separately from 2109 // the arguments. 2110 TypeIndex ThisTypeIndex; 2111 if (!IsStaticMethod && ReturnAndArgs.size() > Index) { 2112 if (const DIDerivedType *PtrTy = 2113 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) { 2114 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) { 2115 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty); 2116 Index++; 2117 } 2118 } 2119 } 2120 2121 while (Index < ReturnAndArgs.size()) 2122 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++])); 2123 2124 // MSVC uses type none for variadic argument. 2125 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void()) 2126 ArgTypeIndices.back() = TypeIndex::None(); 2127 2128 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 2129 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); 2130 2131 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 2132 2133 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO, 2134 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment); 2135 return TypeTable.writeLeafType(MFR); 2136 } 2137 2138 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) { 2139 unsigned VSlotCount = 2140 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize()); 2141 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near); 2142 2143 VFTableShapeRecord VFTSR(Slots); 2144 return TypeTable.writeLeafType(VFTSR); 2145 } 2146 2147 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 2148 switch (Flags & DINode::FlagAccessibility) { 2149 case DINode::FlagPrivate: return MemberAccess::Private; 2150 case DINode::FlagPublic: return MemberAccess::Public; 2151 case DINode::FlagProtected: return MemberAccess::Protected; 2152 case 0: 2153 // If there was no explicit access control, provide the default for the tag. 2154 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 2155 : MemberAccess::Public; 2156 } 2157 llvm_unreachable("access flags are exclusive"); 2158 } 2159 2160 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 2161 if (SP->isArtificial()) 2162 return MethodOptions::CompilerGenerated; 2163 2164 // FIXME: Handle other MethodOptions. 2165 2166 return MethodOptions::None; 2167 } 2168 2169 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 2170 bool Introduced) { 2171 if (SP->getFlags() & DINode::FlagStaticMember) 2172 return MethodKind::Static; 2173 2174 switch (SP->getVirtuality()) { 2175 case dwarf::DW_VIRTUALITY_none: 2176 break; 2177 case dwarf::DW_VIRTUALITY_virtual: 2178 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 2179 case dwarf::DW_VIRTUALITY_pure_virtual: 2180 return Introduced ? MethodKind::PureIntroducingVirtual 2181 : MethodKind::PureVirtual; 2182 default: 2183 llvm_unreachable("unhandled virtuality case"); 2184 } 2185 2186 return MethodKind::Vanilla; 2187 } 2188 2189 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 2190 switch (Ty->getTag()) { 2191 case dwarf::DW_TAG_class_type: 2192 return TypeRecordKind::Class; 2193 case dwarf::DW_TAG_structure_type: 2194 return TypeRecordKind::Struct; 2195 default: 2196 llvm_unreachable("unexpected tag"); 2197 } 2198 } 2199 2200 /// Return ClassOptions that should be present on both the forward declaration 2201 /// and the defintion of a tag type. 2202 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) { 2203 ClassOptions CO = ClassOptions::None; 2204 2205 // MSVC always sets this flag, even for local types. Clang doesn't always 2206 // appear to give every type a linkage name, which may be problematic for us. 2207 // FIXME: Investigate the consequences of not following them here. 2208 if (!Ty->getIdentifier().empty()) 2209 CO |= ClassOptions::HasUniqueName; 2210 2211 // Put the Nested flag on a type if it appears immediately inside a tag type. 2212 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass 2213 // here. That flag is only set on definitions, and not forward declarations. 2214 const DIScope *ImmediateScope = Ty->getScope(); 2215 if (ImmediateScope && isa<DICompositeType>(ImmediateScope)) 2216 CO |= ClassOptions::Nested; 2217 2218 // Put the Scoped flag on function-local types. MSVC puts this flag for enum 2219 // type only when it has an immediate function scope. Clang never puts enums 2220 // inside DILexicalBlock scopes. Enum types, as generated by clang, are 2221 // always in function, class, or file scopes. 2222 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) { 2223 if (ImmediateScope && isa<DISubprogram>(ImmediateScope)) 2224 CO |= ClassOptions::Scoped; 2225 } else { 2226 for (const DIScope *Scope = ImmediateScope; Scope != nullptr; 2227 Scope = Scope->getScope()) { 2228 if (isa<DISubprogram>(Scope)) { 2229 CO |= ClassOptions::Scoped; 2230 break; 2231 } 2232 } 2233 } 2234 2235 return CO; 2236 } 2237 2238 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) { 2239 switch (Ty->getTag()) { 2240 case dwarf::DW_TAG_class_type: 2241 case dwarf::DW_TAG_structure_type: 2242 case dwarf::DW_TAG_union_type: 2243 case dwarf::DW_TAG_enumeration_type: 2244 break; 2245 default: 2246 return; 2247 } 2248 2249 if (const auto *File = Ty->getFile()) { 2250 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File)); 2251 TypeIndex SIDI = TypeTable.writeLeafType(SIDR); 2252 2253 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine()); 2254 TypeTable.writeLeafType(USLR); 2255 } 2256 } 2257 2258 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 2259 ClassOptions CO = getCommonClassOptions(Ty); 2260 TypeIndex FTI; 2261 unsigned EnumeratorCount = 0; 2262 2263 if (Ty->isForwardDecl()) { 2264 CO |= ClassOptions::ForwardReference; 2265 } else { 2266 ContinuationRecordBuilder ContinuationBuilder; 2267 ContinuationBuilder.begin(ContinuationRecordKind::FieldList); 2268 for (const DINode *Element : Ty->getElements()) { 2269 // We assume that the frontend provides all members in source declaration 2270 // order, which is what MSVC does. 2271 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 2272 // FIXME: Is it correct to always emit these as unsigned here? 2273 EnumeratorRecord ER(MemberAccess::Public, 2274 APSInt(Enumerator->getValue(), true), 2275 Enumerator->getName()); 2276 ContinuationBuilder.writeMemberType(ER); 2277 EnumeratorCount++; 2278 } 2279 } 2280 FTI = TypeTable.insertRecord(ContinuationBuilder); 2281 } 2282 2283 std::string FullName = getFullyQualifiedName(Ty); 2284 2285 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(), 2286 getTypeIndex(Ty->getBaseType())); 2287 TypeIndex EnumTI = TypeTable.writeLeafType(ER); 2288 2289 addUDTSrcLine(Ty, EnumTI); 2290 2291 return EnumTI; 2292 } 2293 2294 //===----------------------------------------------------------------------===// 2295 // ClassInfo 2296 //===----------------------------------------------------------------------===// 2297 2298 struct llvm::ClassInfo { 2299 struct MemberInfo { 2300 const DIDerivedType *MemberTypeNode; 2301 uint64_t BaseOffset; 2302 }; 2303 // [MemberInfo] 2304 using MemberList = std::vector<MemberInfo>; 2305 2306 using MethodsList = TinyPtrVector<const DISubprogram *>; 2307 // MethodName -> MethodsList 2308 using MethodsMap = MapVector<MDString *, MethodsList>; 2309 2310 /// Base classes. 2311 std::vector<const DIDerivedType *> Inheritance; 2312 2313 /// Direct members. 2314 MemberList Members; 2315 // Direct overloaded methods gathered by name. 2316 MethodsMap Methods; 2317 2318 TypeIndex VShapeTI; 2319 2320 std::vector<const DIType *> NestedTypes; 2321 }; 2322 2323 void CodeViewDebug::clear() { 2324 assert(CurFn == nullptr); 2325 FileIdMap.clear(); 2326 FnDebugInfo.clear(); 2327 FileToFilepathMap.clear(); 2328 LocalUDTs.clear(); 2329 GlobalUDTs.clear(); 2330 TypeIndices.clear(); 2331 CompleteTypeIndices.clear(); 2332 ScopeGlobals.clear(); 2333 CVGlobalVariableOffsets.clear(); 2334 } 2335 2336 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 2337 const DIDerivedType *DDTy) { 2338 if (!DDTy->getName().empty()) { 2339 Info.Members.push_back({DDTy, 0}); 2340 2341 // Collect static const data members with values. 2342 if ((DDTy->getFlags() & DINode::FlagStaticMember) == 2343 DINode::FlagStaticMember) { 2344 if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) || 2345 isa<ConstantFP>(DDTy->getConstant()))) 2346 StaticConstMembers.push_back(DDTy); 2347 } 2348 2349 return; 2350 } 2351 2352 // An unnamed member may represent a nested struct or union. Attempt to 2353 // interpret the unnamed member as a DICompositeType possibly wrapped in 2354 // qualifier types. Add all the indirect fields to the current record if that 2355 // succeeds, and drop the member if that fails. 2356 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 2357 uint64_t Offset = DDTy->getOffsetInBits(); 2358 const DIType *Ty = DDTy->getBaseType(); 2359 bool FullyResolved = false; 2360 while (!FullyResolved) { 2361 switch (Ty->getTag()) { 2362 case dwarf::DW_TAG_const_type: 2363 case dwarf::DW_TAG_volatile_type: 2364 // FIXME: we should apply the qualifier types to the indirect fields 2365 // rather than dropping them. 2366 Ty = cast<DIDerivedType>(Ty)->getBaseType(); 2367 break; 2368 default: 2369 FullyResolved = true; 2370 break; 2371 } 2372 } 2373 2374 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty); 2375 if (!DCTy) 2376 return; 2377 2378 ClassInfo NestedInfo = collectClassInfo(DCTy); 2379 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) 2380 Info.Members.push_back( 2381 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); 2382 } 2383 2384 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 2385 ClassInfo Info; 2386 // Add elements to structure type. 2387 DINodeArray Elements = Ty->getElements(); 2388 for (auto *Element : Elements) { 2389 // We assume that the frontend provides all members in source declaration 2390 // order, which is what MSVC does. 2391 if (!Element) 2392 continue; 2393 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 2394 Info.Methods[SP->getRawName()].push_back(SP); 2395 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 2396 if (DDTy->getTag() == dwarf::DW_TAG_member) { 2397 collectMemberInfo(Info, DDTy); 2398 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 2399 Info.Inheritance.push_back(DDTy); 2400 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type && 2401 DDTy->getName() == "__vtbl_ptr_type") { 2402 Info.VShapeTI = getTypeIndex(DDTy); 2403 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) { 2404 Info.NestedTypes.push_back(DDTy); 2405 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 2406 // Ignore friend members. It appears that MSVC emitted info about 2407 // friends in the past, but modern versions do not. 2408 } 2409 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) { 2410 Info.NestedTypes.push_back(Composite); 2411 } 2412 // Skip other unrecognized kinds of elements. 2413 } 2414 return Info; 2415 } 2416 2417 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) { 2418 // This routine is used by lowerTypeClass and lowerTypeUnion to determine 2419 // if a complete type should be emitted instead of a forward reference. 2420 return Ty->getName().empty() && Ty->getIdentifier().empty() && 2421 !Ty->isForwardDecl(); 2422 } 2423 2424 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 2425 // Emit the complete type for unnamed structs. C++ classes with methods 2426 // which have a circular reference back to the class type are expected to 2427 // be named by the front-end and should not be "unnamed". C unnamed 2428 // structs should not have circular references. 2429 if (shouldAlwaysEmitCompleteClassType(Ty)) { 2430 // If this unnamed complete type is already in the process of being defined 2431 // then the description of the type is malformed and cannot be emitted 2432 // into CodeView correctly so report a fatal error. 2433 auto I = CompleteTypeIndices.find(Ty); 2434 if (I != CompleteTypeIndices.end() && I->second == TypeIndex()) 2435 report_fatal_error("cannot debug circular reference to unnamed type"); 2436 return getCompleteTypeIndex(Ty); 2437 } 2438 2439 // First, construct the forward decl. Don't look into Ty to compute the 2440 // forward decl options, since it might not be available in all TUs. 2441 TypeRecordKind Kind = getRecordKind(Ty); 2442 ClassOptions CO = 2443 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 2444 std::string FullName = getFullyQualifiedName(Ty); 2445 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0, 2446 FullName, Ty->getIdentifier()); 2447 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR); 2448 if (!Ty->isForwardDecl()) 2449 DeferredCompleteTypes.push_back(Ty); 2450 return FwdDeclTI; 2451 } 2452 2453 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 2454 // Construct the field list and complete type record. 2455 TypeRecordKind Kind = getRecordKind(Ty); 2456 ClassOptions CO = getCommonClassOptions(Ty); 2457 TypeIndex FieldTI; 2458 TypeIndex VShapeTI; 2459 unsigned FieldCount; 2460 bool ContainsNestedClass; 2461 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) = 2462 lowerRecordFieldList(Ty); 2463 2464 if (ContainsNestedClass) 2465 CO |= ClassOptions::ContainsNestedClass; 2466 2467 // MSVC appears to set this flag by searching any destructor or method with 2468 // FunctionOptions::Constructor among the emitted members. Clang AST has all 2469 // the members, however special member functions are not yet emitted into 2470 // debug information. For now checking a class's non-triviality seems enough. 2471 // FIXME: not true for a nested unnamed struct. 2472 if (isNonTrivial(Ty)) 2473 CO |= ClassOptions::HasConstructorOrDestructor; 2474 2475 std::string FullName = getFullyQualifiedName(Ty); 2476 2477 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 2478 2479 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI, 2480 SizeInBytes, FullName, Ty->getIdentifier()); 2481 TypeIndex ClassTI = TypeTable.writeLeafType(CR); 2482 2483 addUDTSrcLine(Ty, ClassTI); 2484 2485 addToUDTs(Ty); 2486 2487 return ClassTI; 2488 } 2489 2490 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 2491 // Emit the complete type for unnamed unions. 2492 if (shouldAlwaysEmitCompleteClassType(Ty)) 2493 return getCompleteTypeIndex(Ty); 2494 2495 ClassOptions CO = 2496 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 2497 std::string FullName = getFullyQualifiedName(Ty); 2498 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier()); 2499 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR); 2500 if (!Ty->isForwardDecl()) 2501 DeferredCompleteTypes.push_back(Ty); 2502 return FwdDeclTI; 2503 } 2504 2505 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 2506 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty); 2507 TypeIndex FieldTI; 2508 unsigned FieldCount; 2509 bool ContainsNestedClass; 2510 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) = 2511 lowerRecordFieldList(Ty); 2512 2513 if (ContainsNestedClass) 2514 CO |= ClassOptions::ContainsNestedClass; 2515 2516 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 2517 std::string FullName = getFullyQualifiedName(Ty); 2518 2519 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName, 2520 Ty->getIdentifier()); 2521 TypeIndex UnionTI = TypeTable.writeLeafType(UR); 2522 2523 addUDTSrcLine(Ty, UnionTI); 2524 2525 addToUDTs(Ty); 2526 2527 return UnionTI; 2528 } 2529 2530 std::tuple<TypeIndex, TypeIndex, unsigned, bool> 2531 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 2532 // Manually count members. MSVC appears to count everything that generates a 2533 // field list record. Each individual overload in a method overload group 2534 // contributes to this count, even though the overload group is a single field 2535 // list record. 2536 unsigned MemberCount = 0; 2537 ClassInfo Info = collectClassInfo(Ty); 2538 ContinuationRecordBuilder ContinuationBuilder; 2539 ContinuationBuilder.begin(ContinuationRecordKind::FieldList); 2540 2541 // Create base classes. 2542 for (const DIDerivedType *I : Info.Inheritance) { 2543 if (I->getFlags() & DINode::FlagVirtual) { 2544 // Virtual base. 2545 unsigned VBPtrOffset = I->getVBPtrOffset(); 2546 // FIXME: Despite the accessor name, the offset is really in bytes. 2547 unsigned VBTableIndex = I->getOffsetInBits() / 4; 2548 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase 2549 ? TypeRecordKind::IndirectVirtualBaseClass 2550 : TypeRecordKind::VirtualBaseClass; 2551 VirtualBaseClassRecord VBCR( 2552 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()), 2553 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, 2554 VBTableIndex); 2555 2556 ContinuationBuilder.writeMemberType(VBCR); 2557 MemberCount++; 2558 } else { 2559 assert(I->getOffsetInBits() % 8 == 0 && 2560 "bases must be on byte boundaries"); 2561 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()), 2562 getTypeIndex(I->getBaseType()), 2563 I->getOffsetInBits() / 8); 2564 ContinuationBuilder.writeMemberType(BCR); 2565 MemberCount++; 2566 } 2567 } 2568 2569 // Create members. 2570 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 2571 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 2572 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 2573 StringRef MemberName = Member->getName(); 2574 MemberAccess Access = 2575 translateAccessFlags(Ty->getTag(), Member->getFlags()); 2576 2577 if (Member->isStaticMember()) { 2578 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName); 2579 ContinuationBuilder.writeMemberType(SDMR); 2580 MemberCount++; 2581 continue; 2582 } 2583 2584 // Virtual function pointer member. 2585 if ((Member->getFlags() & DINode::FlagArtificial) && 2586 Member->getName().startswith("_vptr$")) { 2587 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType())); 2588 ContinuationBuilder.writeMemberType(VFPR); 2589 MemberCount++; 2590 continue; 2591 } 2592 2593 // Data member. 2594 uint64_t MemberOffsetInBits = 2595 Member->getOffsetInBits() + MemberInfo.BaseOffset; 2596 if (Member->isBitField()) { 2597 uint64_t StartBitOffset = MemberOffsetInBits; 2598 if (const auto *CI = 2599 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { 2600 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset; 2601 } 2602 StartBitOffset -= MemberOffsetInBits; 2603 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(), 2604 StartBitOffset); 2605 MemberBaseType = TypeTable.writeLeafType(BFR); 2606 } 2607 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; 2608 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes, 2609 MemberName); 2610 ContinuationBuilder.writeMemberType(DMR); 2611 MemberCount++; 2612 } 2613 2614 // Create methods 2615 for (auto &MethodItr : Info.Methods) { 2616 StringRef Name = MethodItr.first->getString(); 2617 2618 std::vector<OneMethodRecord> Methods; 2619 for (const DISubprogram *SP : MethodItr.second) { 2620 TypeIndex MethodType = getMemberFunctionType(SP, Ty); 2621 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; 2622 2623 unsigned VFTableOffset = -1; 2624 if (Introduced) 2625 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 2626 2627 Methods.push_back(OneMethodRecord( 2628 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()), 2629 translateMethodKindFlags(SP, Introduced), 2630 translateMethodOptionFlags(SP), VFTableOffset, Name)); 2631 MemberCount++; 2632 } 2633 assert(!Methods.empty() && "Empty methods map entry"); 2634 if (Methods.size() == 1) 2635 ContinuationBuilder.writeMemberType(Methods[0]); 2636 else { 2637 // FIXME: Make this use its own ContinuationBuilder so that 2638 // MethodOverloadList can be split correctly. 2639 MethodOverloadListRecord MOLR(Methods); 2640 TypeIndex MethodList = TypeTable.writeLeafType(MOLR); 2641 2642 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name); 2643 ContinuationBuilder.writeMemberType(OMR); 2644 } 2645 } 2646 2647 // Create nested classes. 2648 for (const DIType *Nested : Info.NestedTypes) { 2649 NestedTypeRecord R(getTypeIndex(Nested), Nested->getName()); 2650 ContinuationBuilder.writeMemberType(R); 2651 MemberCount++; 2652 } 2653 2654 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder); 2655 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount, 2656 !Info.NestedTypes.empty()); 2657 } 2658 2659 TypeIndex CodeViewDebug::getVBPTypeIndex() { 2660 if (!VBPType.getIndex()) { 2661 // Make a 'const int *' type. 2662 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); 2663 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR); 2664 2665 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 2666 : PointerKind::Near32; 2667 PointerMode PM = PointerMode::Pointer; 2668 PointerOptions PO = PointerOptions::None; 2669 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); 2670 VBPType = TypeTable.writeLeafType(PR); 2671 } 2672 2673 return VBPType; 2674 } 2675 2676 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) { 2677 // The null DIType is the void type. Don't try to hash it. 2678 if (!Ty) 2679 return TypeIndex::Void(); 2680 2681 // Check if we've already translated this type. Don't try to do a 2682 // get-or-create style insertion that caches the hash lookup across the 2683 // lowerType call. It will update the TypeIndices map. 2684 auto I = TypeIndices.find({Ty, ClassTy}); 2685 if (I != TypeIndices.end()) 2686 return I->second; 2687 2688 TypeLoweringScope S(*this); 2689 TypeIndex TI = lowerType(Ty, ClassTy); 2690 return recordTypeIndexForDINode(Ty, TI, ClassTy); 2691 } 2692 2693 codeview::TypeIndex 2694 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy, 2695 const DISubroutineType *SubroutineTy) { 2696 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type && 2697 "this type must be a pointer type"); 2698 2699 PointerOptions Options = PointerOptions::None; 2700 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference) 2701 Options = PointerOptions::LValueRefThisPointer; 2702 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference) 2703 Options = PointerOptions::RValueRefThisPointer; 2704 2705 // Check if we've already translated this type. If there is no ref qualifier 2706 // on the function then we look up this pointer type with no associated class 2707 // so that the TypeIndex for the this pointer can be shared with the type 2708 // index for other pointers to this class type. If there is a ref qualifier 2709 // then we lookup the pointer using the subroutine as the parent type. 2710 auto I = TypeIndices.find({PtrTy, SubroutineTy}); 2711 if (I != TypeIndices.end()) 2712 return I->second; 2713 2714 TypeLoweringScope S(*this); 2715 TypeIndex TI = lowerTypePointer(PtrTy, Options); 2716 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy); 2717 } 2718 2719 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) { 2720 PointerRecord PR(getTypeIndex(Ty), 2721 getPointerSizeInBytes() == 8 ? PointerKind::Near64 2722 : PointerKind::Near32, 2723 PointerMode::LValueReference, PointerOptions::None, 2724 Ty->getSizeInBits() / 8); 2725 return TypeTable.writeLeafType(PR); 2726 } 2727 2728 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) { 2729 // The null DIType is the void type. Don't try to hash it. 2730 if (!Ty) 2731 return TypeIndex::Void(); 2732 2733 // Look through typedefs when getting the complete type index. Call 2734 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are 2735 // emitted only once. 2736 if (Ty->getTag() == dwarf::DW_TAG_typedef) 2737 (void)getTypeIndex(Ty); 2738 while (Ty->getTag() == dwarf::DW_TAG_typedef) 2739 Ty = cast<DIDerivedType>(Ty)->getBaseType(); 2740 2741 // If this is a non-record type, the complete type index is the same as the 2742 // normal type index. Just call getTypeIndex. 2743 switch (Ty->getTag()) { 2744 case dwarf::DW_TAG_class_type: 2745 case dwarf::DW_TAG_structure_type: 2746 case dwarf::DW_TAG_union_type: 2747 break; 2748 default: 2749 return getTypeIndex(Ty); 2750 } 2751 2752 const auto *CTy = cast<DICompositeType>(Ty); 2753 2754 TypeLoweringScope S(*this); 2755 2756 // Make sure the forward declaration is emitted first. It's unclear if this 2757 // is necessary, but MSVC does it, and we should follow suit until we can show 2758 // otherwise. 2759 // We only emit a forward declaration for named types. 2760 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) { 2761 TypeIndex FwdDeclTI = getTypeIndex(CTy); 2762 2763 // Just use the forward decl if we don't have complete type info. This 2764 // might happen if the frontend is using modules and expects the complete 2765 // definition to be emitted elsewhere. 2766 if (CTy->isForwardDecl()) 2767 return FwdDeclTI; 2768 } 2769 2770 // Check if we've already translated the complete record type. 2771 // Insert the type with a null TypeIndex to signify that the type is currently 2772 // being lowered. 2773 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 2774 if (!InsertResult.second) 2775 return InsertResult.first->second; 2776 2777 TypeIndex TI; 2778 switch (CTy->getTag()) { 2779 case dwarf::DW_TAG_class_type: 2780 case dwarf::DW_TAG_structure_type: 2781 TI = lowerCompleteTypeClass(CTy); 2782 break; 2783 case dwarf::DW_TAG_union_type: 2784 TI = lowerCompleteTypeUnion(CTy); 2785 break; 2786 default: 2787 llvm_unreachable("not a record"); 2788 } 2789 2790 // Update the type index associated with this CompositeType. This cannot 2791 // use the 'InsertResult' iterator above because it is potentially 2792 // invalidated by map insertions which can occur while lowering the class 2793 // type above. 2794 CompleteTypeIndices[CTy] = TI; 2795 return TI; 2796 } 2797 2798 /// Emit all the deferred complete record types. Try to do this in FIFO order, 2799 /// and do this until fixpoint, as each complete record type typically 2800 /// references 2801 /// many other record types. 2802 void CodeViewDebug::emitDeferredCompleteTypes() { 2803 SmallVector<const DICompositeType *, 4> TypesToEmit; 2804 while (!DeferredCompleteTypes.empty()) { 2805 std::swap(DeferredCompleteTypes, TypesToEmit); 2806 for (const DICompositeType *RecordTy : TypesToEmit) 2807 getCompleteTypeIndex(RecordTy); 2808 TypesToEmit.clear(); 2809 } 2810 } 2811 2812 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI, 2813 ArrayRef<LocalVariable> Locals) { 2814 // Get the sorted list of parameters and emit them first. 2815 SmallVector<const LocalVariable *, 6> Params; 2816 for (const LocalVariable &L : Locals) 2817 if (L.DIVar->isParameter()) 2818 Params.push_back(&L); 2819 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) { 2820 return L->DIVar->getArg() < R->DIVar->getArg(); 2821 }); 2822 for (const LocalVariable *L : Params) 2823 emitLocalVariable(FI, *L); 2824 2825 // Next emit all non-parameters in the order that we found them. 2826 for (const LocalVariable &L : Locals) { 2827 if (!L.DIVar->isParameter()) { 2828 if (L.ConstantValue) { 2829 // If ConstantValue is set we will emit it as a S_CONSTANT instead of a 2830 // S_LOCAL in order to be able to represent it at all. 2831 const DIType *Ty = L.DIVar->getType(); 2832 APSInt Val(*L.ConstantValue); 2833 emitConstantSymbolRecord(Ty, Val, std::string(L.DIVar->getName())); 2834 } else { 2835 emitLocalVariable(FI, L); 2836 } 2837 } 2838 } 2839 } 2840 2841 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI, 2842 const LocalVariable &Var) { 2843 // LocalSym record, see SymbolRecord.h for more info. 2844 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL); 2845 2846 LocalSymFlags Flags = LocalSymFlags::None; 2847 if (Var.DIVar->isParameter()) 2848 Flags |= LocalSymFlags::IsParameter; 2849 if (Var.DefRanges.empty()) 2850 Flags |= LocalSymFlags::IsOptimizedOut; 2851 2852 OS.AddComment("TypeIndex"); 2853 TypeIndex TI = Var.UseReferenceType 2854 ? getTypeIndexForReferenceTo(Var.DIVar->getType()) 2855 : getCompleteTypeIndex(Var.DIVar->getType()); 2856 OS.emitInt32(TI.getIndex()); 2857 OS.AddComment("Flags"); 2858 OS.emitInt16(static_cast<uint16_t>(Flags)); 2859 // Truncate the name so we won't overflow the record length field. 2860 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 2861 endSymbolRecord(LocalEnd); 2862 2863 // Calculate the on disk prefix of the appropriate def range record. The 2864 // records and on disk formats are described in SymbolRecords.h. BytePrefix 2865 // should be big enough to hold all forms without memory allocation. 2866 SmallString<20> BytePrefix; 2867 for (const auto &Pair : Var.DefRanges) { 2868 LocalVarDef DefRange = Pair.first; 2869 const auto &Ranges = Pair.second; 2870 BytePrefix.clear(); 2871 if (DefRange.InMemory) { 2872 int Offset = DefRange.DataOffset; 2873 unsigned Reg = DefRange.CVRegister; 2874 2875 // 32-bit x86 call sequences often use PUSH instructions, which disrupt 2876 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0, 2877 // instead. In frames without stack realignment, $T0 will be the CFA. 2878 if (RegisterId(Reg) == RegisterId::ESP) { 2879 Reg = unsigned(RegisterId::VFRAME); 2880 Offset += FI.OffsetAdjustment; 2881 } 2882 2883 // If we can use the chosen frame pointer for the frame and this isn't a 2884 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record. 2885 // Otherwise, use S_DEFRANGE_REGISTER_REL. 2886 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU); 2887 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None && 2888 (bool(Flags & LocalSymFlags::IsParameter) 2889 ? (EncFP == FI.EncodedParamFramePtrReg) 2890 : (EncFP == FI.EncodedLocalFramePtrReg))) { 2891 DefRangeFramePointerRelHeader DRHdr; 2892 DRHdr.Offset = Offset; 2893 OS.emitCVDefRangeDirective(Ranges, DRHdr); 2894 } else { 2895 uint16_t RegRelFlags = 0; 2896 if (DefRange.IsSubfield) { 2897 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag | 2898 (DefRange.StructOffset 2899 << DefRangeRegisterRelSym::OffsetInParentShift); 2900 } 2901 DefRangeRegisterRelHeader DRHdr; 2902 DRHdr.Register = Reg; 2903 DRHdr.Flags = RegRelFlags; 2904 DRHdr.BasePointerOffset = Offset; 2905 OS.emitCVDefRangeDirective(Ranges, DRHdr); 2906 } 2907 } else { 2908 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 2909 if (DefRange.IsSubfield) { 2910 DefRangeSubfieldRegisterHeader DRHdr; 2911 DRHdr.Register = DefRange.CVRegister; 2912 DRHdr.MayHaveNoName = 0; 2913 DRHdr.OffsetInParent = DefRange.StructOffset; 2914 OS.emitCVDefRangeDirective(Ranges, DRHdr); 2915 } else { 2916 DefRangeRegisterHeader DRHdr; 2917 DRHdr.Register = DefRange.CVRegister; 2918 DRHdr.MayHaveNoName = 0; 2919 OS.emitCVDefRangeDirective(Ranges, DRHdr); 2920 } 2921 } 2922 } 2923 } 2924 2925 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks, 2926 const FunctionInfo& FI) { 2927 for (LexicalBlock *Block : Blocks) 2928 emitLexicalBlock(*Block, FI); 2929 } 2930 2931 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a 2932 /// lexical block scope. 2933 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block, 2934 const FunctionInfo& FI) { 2935 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32); 2936 OS.AddComment("PtrParent"); 2937 OS.emitInt32(0); // PtrParent 2938 OS.AddComment("PtrEnd"); 2939 OS.emitInt32(0); // PtrEnd 2940 OS.AddComment("Code size"); 2941 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size 2942 OS.AddComment("Function section relative address"); 2943 OS.emitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset 2944 OS.AddComment("Function section index"); 2945 OS.emitCOFFSectionIndex(FI.Begin); // Func Symbol 2946 OS.AddComment("Lexical block name"); 2947 emitNullTerminatedSymbolName(OS, Block.Name); // Name 2948 endSymbolRecord(RecordEnd); 2949 2950 // Emit variables local to this lexical block. 2951 emitLocalVariableList(FI, Block.Locals); 2952 emitGlobalVariableList(Block.Globals); 2953 2954 // Emit lexical blocks contained within this block. 2955 emitLexicalBlockList(Block.Children, FI); 2956 2957 // Close the lexical block scope. 2958 emitEndSymbolRecord(SymbolKind::S_END); 2959 } 2960 2961 /// Convenience routine for collecting lexical block information for a list 2962 /// of lexical scopes. 2963 void CodeViewDebug::collectLexicalBlockInfo( 2964 SmallVectorImpl<LexicalScope *> &Scopes, 2965 SmallVectorImpl<LexicalBlock *> &Blocks, 2966 SmallVectorImpl<LocalVariable> &Locals, 2967 SmallVectorImpl<CVGlobalVariable> &Globals) { 2968 for (LexicalScope *Scope : Scopes) 2969 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals); 2970 } 2971 2972 /// Populate the lexical blocks and local variable lists of the parent with 2973 /// information about the specified lexical scope. 2974 void CodeViewDebug::collectLexicalBlockInfo( 2975 LexicalScope &Scope, 2976 SmallVectorImpl<LexicalBlock *> &ParentBlocks, 2977 SmallVectorImpl<LocalVariable> &ParentLocals, 2978 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) { 2979 if (Scope.isAbstractScope()) 2980 return; 2981 2982 // Gather information about the lexical scope including local variables, 2983 // global variables, and address ranges. 2984 bool IgnoreScope = false; 2985 auto LI = ScopeVariables.find(&Scope); 2986 SmallVectorImpl<LocalVariable> *Locals = 2987 LI != ScopeVariables.end() ? &LI->second : nullptr; 2988 auto GI = ScopeGlobals.find(Scope.getScopeNode()); 2989 SmallVectorImpl<CVGlobalVariable> *Globals = 2990 GI != ScopeGlobals.end() ? GI->second.get() : nullptr; 2991 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode()); 2992 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges(); 2993 2994 // Ignore lexical scopes which do not contain variables. 2995 if (!Locals && !Globals) 2996 IgnoreScope = true; 2997 2998 // Ignore lexical scopes which are not lexical blocks. 2999 if (!DILB) 3000 IgnoreScope = true; 3001 3002 // Ignore scopes which have too many address ranges to represent in the 3003 // current CodeView format or do not have a valid address range. 3004 // 3005 // For lexical scopes with multiple address ranges you may be tempted to 3006 // construct a single range covering every instruction where the block is 3007 // live and everything in between. Unfortunately, Visual Studio only 3008 // displays variables from the first matching lexical block scope. If the 3009 // first lexical block contains exception handling code or cold code which 3010 // is moved to the bottom of the routine creating a single range covering 3011 // nearly the entire routine, then it will hide all other lexical blocks 3012 // and the variables they contain. 3013 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) 3014 IgnoreScope = true; 3015 3016 if (IgnoreScope) { 3017 // This scope can be safely ignored and eliminating it will reduce the 3018 // size of the debug information. Be sure to collect any variable and scope 3019 // information from the this scope or any of its children and collapse them 3020 // into the parent scope. 3021 if (Locals) 3022 ParentLocals.append(Locals->begin(), Locals->end()); 3023 if (Globals) 3024 ParentGlobals.append(Globals->begin(), Globals->end()); 3025 collectLexicalBlockInfo(Scope.getChildren(), 3026 ParentBlocks, 3027 ParentLocals, 3028 ParentGlobals); 3029 return; 3030 } 3031 3032 // Create a new CodeView lexical block for this lexical scope. If we've 3033 // seen this DILexicalBlock before then the scope tree is malformed and 3034 // we can handle this gracefully by not processing it a second time. 3035 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()}); 3036 if (!BlockInsertion.second) 3037 return; 3038 3039 // Create a lexical block containing the variables and collect the 3040 // lexical block information for the children. 3041 const InsnRange &Range = Ranges.front(); 3042 assert(Range.first && Range.second); 3043 LexicalBlock &Block = BlockInsertion.first->second; 3044 Block.Begin = getLabelBeforeInsn(Range.first); 3045 Block.End = getLabelAfterInsn(Range.second); 3046 assert(Block.Begin && "missing label for scope begin"); 3047 assert(Block.End && "missing label for scope end"); 3048 Block.Name = DILB->getName(); 3049 if (Locals) 3050 Block.Locals = std::move(*Locals); 3051 if (Globals) 3052 Block.Globals = std::move(*Globals); 3053 ParentBlocks.push_back(&Block); 3054 collectLexicalBlockInfo(Scope.getChildren(), 3055 Block.Children, 3056 Block.Locals, 3057 Block.Globals); 3058 } 3059 3060 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) { 3061 const Function &GV = MF->getFunction(); 3062 assert(FnDebugInfo.count(&GV)); 3063 assert(CurFn == FnDebugInfo[&GV].get()); 3064 3065 collectVariableInfo(GV.getSubprogram()); 3066 3067 // Build the lexical block structure to emit for this routine. 3068 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope()) 3069 collectLexicalBlockInfo(*CFS, 3070 CurFn->ChildBlocks, 3071 CurFn->Locals, 3072 CurFn->Globals); 3073 3074 // Clear the scope and variable information from the map which will not be 3075 // valid after we have finished processing this routine. This also prepares 3076 // the map for the subsequent routine. 3077 ScopeVariables.clear(); 3078 3079 // Don't emit anything if we don't have any line tables. 3080 // Thunks are compiler-generated and probably won't have source correlation. 3081 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) { 3082 FnDebugInfo.erase(&GV); 3083 CurFn = nullptr; 3084 return; 3085 } 3086 3087 // Find heap alloc sites and add to list. 3088 for (const auto &MBB : *MF) { 3089 for (const auto &MI : MBB) { 3090 if (MDNode *MD = MI.getHeapAllocMarker()) { 3091 CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI), 3092 getLabelAfterInsn(&MI), 3093 dyn_cast<DIType>(MD))); 3094 } 3095 } 3096 } 3097 3098 bool isThumb = Triple(MMI->getModule()->getTargetTriple()).getArch() == 3099 llvm::Triple::ArchType::thumb; 3100 collectDebugInfoForJumpTables(MF, isThumb); 3101 3102 CurFn->Annotations = MF->getCodeViewAnnotations(); 3103 3104 CurFn->End = Asm->getFunctionEnd(); 3105 3106 CurFn = nullptr; 3107 } 3108 3109 // Usable locations are valid with non-zero line numbers. A line number of zero 3110 // corresponds to optimized code that doesn't have a distinct source location. 3111 // In this case, we try to use the previous or next source location depending on 3112 // the context. 3113 static bool isUsableDebugLoc(DebugLoc DL) { 3114 return DL && DL.getLine() != 0; 3115 } 3116 3117 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 3118 DebugHandlerBase::beginInstruction(MI); 3119 3120 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue. 3121 if (!Asm || !CurFn || MI->isDebugInstr() || 3122 MI->getFlag(MachineInstr::FrameSetup)) 3123 return; 3124 3125 // If the first instruction of a new MBB has no location, find the first 3126 // instruction with a location and use that. 3127 DebugLoc DL = MI->getDebugLoc(); 3128 if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) { 3129 for (const auto &NextMI : *MI->getParent()) { 3130 if (NextMI.isDebugInstr()) 3131 continue; 3132 DL = NextMI.getDebugLoc(); 3133 if (isUsableDebugLoc(DL)) 3134 break; 3135 } 3136 // FIXME: Handle the case where the BB has no valid locations. This would 3137 // probably require doing a real dataflow analysis. 3138 } 3139 PrevInstBB = MI->getParent(); 3140 3141 // If we still don't have a debug location, don't record a location. 3142 if (!isUsableDebugLoc(DL)) 3143 return; 3144 3145 maybeRecordLocation(DL, Asm->MF); 3146 } 3147 3148 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) { 3149 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 3150 *EndLabel = MMI->getContext().createTempSymbol(); 3151 OS.emitInt32(unsigned(Kind)); 3152 OS.AddComment("Subsection size"); 3153 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 3154 OS.emitLabel(BeginLabel); 3155 return EndLabel; 3156 } 3157 3158 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 3159 OS.emitLabel(EndLabel); 3160 // Every subsection must be aligned to a 4-byte boundary. 3161 OS.emitValueToAlignment(Align(4)); 3162 } 3163 3164 static StringRef getSymbolName(SymbolKind SymKind) { 3165 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames()) 3166 if (EE.Value == SymKind) 3167 return EE.Name; 3168 return ""; 3169 } 3170 3171 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) { 3172 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 3173 *EndLabel = MMI->getContext().createTempSymbol(); 3174 OS.AddComment("Record length"); 3175 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); 3176 OS.emitLabel(BeginLabel); 3177 if (OS.isVerboseAsm()) 3178 OS.AddComment("Record kind: " + getSymbolName(SymKind)); 3179 OS.emitInt16(unsigned(SymKind)); 3180 return EndLabel; 3181 } 3182 3183 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) { 3184 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid 3185 // an extra copy of every symbol record in LLD. This increases object file 3186 // size by less than 1% in the clang build, and is compatible with the Visual 3187 // C++ linker. 3188 OS.emitValueToAlignment(Align(4)); 3189 OS.emitLabel(SymEnd); 3190 } 3191 3192 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) { 3193 OS.AddComment("Record length"); 3194 OS.emitInt16(2); 3195 if (OS.isVerboseAsm()) 3196 OS.AddComment("Record kind: " + getSymbolName(EndKind)); 3197 OS.emitInt16(uint16_t(EndKind)); // Record Kind 3198 } 3199 3200 void CodeViewDebug::emitDebugInfoForUDTs( 3201 const std::vector<std::pair<std::string, const DIType *>> &UDTs) { 3202 #ifndef NDEBUG 3203 size_t OriginalSize = UDTs.size(); 3204 #endif 3205 for (const auto &UDT : UDTs) { 3206 const DIType *T = UDT.second; 3207 assert(shouldEmitUdt(T)); 3208 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT); 3209 OS.AddComment("Type"); 3210 OS.emitInt32(getCompleteTypeIndex(T).getIndex()); 3211 assert(OriginalSize == UDTs.size() && 3212 "getCompleteTypeIndex found new UDTs!"); 3213 emitNullTerminatedSymbolName(OS, UDT.first); 3214 endSymbolRecord(UDTRecordEnd); 3215 } 3216 } 3217 3218 void CodeViewDebug::collectGlobalVariableInfo() { 3219 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *> 3220 GlobalMap; 3221 for (const GlobalVariable &GV : MMI->getModule()->globals()) { 3222 SmallVector<DIGlobalVariableExpression *, 1> GVEs; 3223 GV.getDebugInfo(GVEs); 3224 for (const auto *GVE : GVEs) 3225 GlobalMap[GVE] = &GV; 3226 } 3227 3228 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 3229 for (const MDNode *Node : CUs->operands()) { 3230 const auto *CU = cast<DICompileUnit>(Node); 3231 for (const auto *GVE : CU->getGlobalVariables()) { 3232 const DIGlobalVariable *DIGV = GVE->getVariable(); 3233 const DIExpression *DIE = GVE->getExpression(); 3234 // Don't emit string literals in CodeView, as the only useful parts are 3235 // generally the filename and line number, which isn't possible to output 3236 // in CodeView. String literals should be the only unnamed GlobalVariable 3237 // with debug info. 3238 if (DIGV->getName().empty()) continue; 3239 3240 if ((DIE->getNumElements() == 2) && 3241 (DIE->getElement(0) == dwarf::DW_OP_plus_uconst)) 3242 // Record the constant offset for the variable. 3243 // 3244 // A Fortran common block uses this idiom to encode the offset 3245 // of a variable from the common block's starting address. 3246 CVGlobalVariableOffsets.insert( 3247 std::make_pair(DIGV, DIE->getElement(1))); 3248 3249 // Emit constant global variables in a global symbol section. 3250 if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) { 3251 CVGlobalVariable CVGV = {DIGV, DIE}; 3252 GlobalVariables.emplace_back(std::move(CVGV)); 3253 } 3254 3255 const auto *GV = GlobalMap.lookup(GVE); 3256 if (!GV || GV->isDeclarationForLinker()) 3257 continue; 3258 3259 DIScope *Scope = DIGV->getScope(); 3260 SmallVector<CVGlobalVariable, 1> *VariableList; 3261 if (Scope && isa<DILocalScope>(Scope)) { 3262 // Locate a global variable list for this scope, creating one if 3263 // necessary. 3264 auto Insertion = ScopeGlobals.insert( 3265 {Scope, std::unique_ptr<GlobalVariableList>()}); 3266 if (Insertion.second) 3267 Insertion.first->second = std::make_unique<GlobalVariableList>(); 3268 VariableList = Insertion.first->second.get(); 3269 } else if (GV->hasComdat()) 3270 // Emit this global variable into a COMDAT section. 3271 VariableList = &ComdatVariables; 3272 else 3273 // Emit this global variable in a single global symbol section. 3274 VariableList = &GlobalVariables; 3275 CVGlobalVariable CVGV = {DIGV, GV}; 3276 VariableList->emplace_back(std::move(CVGV)); 3277 } 3278 } 3279 } 3280 3281 void CodeViewDebug::collectDebugInfoForGlobals() { 3282 for (const CVGlobalVariable &CVGV : GlobalVariables) { 3283 const DIGlobalVariable *DIGV = CVGV.DIGV; 3284 const DIScope *Scope = DIGV->getScope(); 3285 getCompleteTypeIndex(DIGV->getType()); 3286 getFullyQualifiedName(Scope, DIGV->getName()); 3287 } 3288 3289 for (const CVGlobalVariable &CVGV : ComdatVariables) { 3290 const DIGlobalVariable *DIGV = CVGV.DIGV; 3291 const DIScope *Scope = DIGV->getScope(); 3292 getCompleteTypeIndex(DIGV->getType()); 3293 getFullyQualifiedName(Scope, DIGV->getName()); 3294 } 3295 } 3296 3297 void CodeViewDebug::emitDebugInfoForGlobals() { 3298 // First, emit all globals that are not in a comdat in a single symbol 3299 // substream. MSVC doesn't like it if the substream is empty, so only open 3300 // it if we have at least one global to emit. 3301 switchToDebugSectionForSymbol(nullptr); 3302 if (!GlobalVariables.empty() || !StaticConstMembers.empty()) { 3303 OS.AddComment("Symbol subsection for globals"); 3304 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); 3305 emitGlobalVariableList(GlobalVariables); 3306 emitStaticConstMemberList(); 3307 endCVSubsection(EndLabel); 3308 } 3309 3310 // Second, emit each global that is in a comdat into its own .debug$S 3311 // section along with its own symbol substream. 3312 for (const CVGlobalVariable &CVGV : ComdatVariables) { 3313 const GlobalVariable *GV = cast<const GlobalVariable *>(CVGV.GVInfo); 3314 MCSymbol *GVSym = Asm->getSymbol(GV); 3315 OS.AddComment("Symbol subsection for " + 3316 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName()))); 3317 switchToDebugSectionForSymbol(GVSym); 3318 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); 3319 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3320 emitDebugInfoForGlobal(CVGV); 3321 endCVSubsection(EndLabel); 3322 } 3323 } 3324 3325 void CodeViewDebug::emitDebugInfoForRetainedTypes() { 3326 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 3327 for (const MDNode *Node : CUs->operands()) { 3328 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { 3329 if (DIType *RT = dyn_cast<DIType>(Ty)) { 3330 getTypeIndex(RT); 3331 // FIXME: Add to global/local DTU list. 3332 } 3333 } 3334 } 3335 } 3336 3337 // Emit each global variable in the specified array. 3338 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) { 3339 for (const CVGlobalVariable &CVGV : Globals) { 3340 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3341 emitDebugInfoForGlobal(CVGV); 3342 } 3343 } 3344 3345 void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value, 3346 const std::string &QualifiedName) { 3347 MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT); 3348 OS.AddComment("Type"); 3349 OS.emitInt32(getTypeIndex(DTy).getIndex()); 3350 3351 OS.AddComment("Value"); 3352 3353 // Encoded integers shouldn't need more than 10 bytes. 3354 uint8_t Data[10]; 3355 BinaryStreamWriter Writer(Data, llvm::endianness::little); 3356 CodeViewRecordIO IO(Writer); 3357 cantFail(IO.mapEncodedInteger(Value)); 3358 StringRef SRef((char *)Data, Writer.getOffset()); 3359 OS.emitBinaryData(SRef); 3360 3361 OS.AddComment("Name"); 3362 emitNullTerminatedSymbolName(OS, QualifiedName); 3363 endSymbolRecord(SConstantEnd); 3364 } 3365 3366 void CodeViewDebug::emitStaticConstMemberList() { 3367 for (const DIDerivedType *DTy : StaticConstMembers) { 3368 const DIScope *Scope = DTy->getScope(); 3369 3370 APSInt Value; 3371 if (const ConstantInt *CI = 3372 dyn_cast_or_null<ConstantInt>(DTy->getConstant())) 3373 Value = APSInt(CI->getValue(), 3374 DebugHandlerBase::isUnsignedDIType(DTy->getBaseType())); 3375 else if (const ConstantFP *CFP = 3376 dyn_cast_or_null<ConstantFP>(DTy->getConstant())) 3377 Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true); 3378 else 3379 llvm_unreachable("cannot emit a constant without a value"); 3380 3381 emitConstantSymbolRecord(DTy->getBaseType(), Value, 3382 getFullyQualifiedName(Scope, DTy->getName())); 3383 } 3384 } 3385 3386 static bool isFloatDIType(const DIType *Ty) { 3387 if (isa<DICompositeType>(Ty)) 3388 return false; 3389 3390 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) { 3391 dwarf::Tag T = (dwarf::Tag)Ty->getTag(); 3392 if (T == dwarf::DW_TAG_pointer_type || 3393 T == dwarf::DW_TAG_ptr_to_member_type || 3394 T == dwarf::DW_TAG_reference_type || 3395 T == dwarf::DW_TAG_rvalue_reference_type) 3396 return false; 3397 assert(DTy->getBaseType() && "Expected valid base type"); 3398 return isFloatDIType(DTy->getBaseType()); 3399 } 3400 3401 auto *BTy = cast<DIBasicType>(Ty); 3402 return (BTy->getEncoding() == dwarf::DW_ATE_float); 3403 } 3404 3405 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) { 3406 const DIGlobalVariable *DIGV = CVGV.DIGV; 3407 3408 const DIScope *Scope = DIGV->getScope(); 3409 // For static data members, get the scope from the declaration. 3410 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>( 3411 DIGV->getRawStaticDataMemberDeclaration())) 3412 Scope = MemberDecl->getScope(); 3413 // For static local variables and Fortran, the scoping portion is elided 3414 // in its name so that we can reference the variable in the command line 3415 // of the VS debugger. 3416 std::string QualifiedName = 3417 (moduleIsInFortran() || (Scope && isa<DILocalScope>(Scope))) 3418 ? std::string(DIGV->getName()) 3419 : getFullyQualifiedName(Scope, DIGV->getName()); 3420 3421 if (const GlobalVariable *GV = 3422 dyn_cast_if_present<const GlobalVariable *>(CVGV.GVInfo)) { 3423 // DataSym record, see SymbolRecord.h for more info. Thread local data 3424 // happens to have the same format as global data. 3425 MCSymbol *GVSym = Asm->getSymbol(GV); 3426 SymbolKind DataSym = GV->isThreadLocal() 3427 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32 3428 : SymbolKind::S_GTHREAD32) 3429 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32 3430 : SymbolKind::S_GDATA32); 3431 MCSymbol *DataEnd = beginSymbolRecord(DataSym); 3432 OS.AddComment("Type"); 3433 OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex()); 3434 OS.AddComment("DataOffset"); 3435 3436 uint64_t Offset = 0; 3437 if (CVGlobalVariableOffsets.contains(DIGV)) 3438 // Use the offset seen while collecting info on globals. 3439 Offset = CVGlobalVariableOffsets[DIGV]; 3440 OS.emitCOFFSecRel32(GVSym, Offset); 3441 3442 OS.AddComment("Segment"); 3443 OS.emitCOFFSectionIndex(GVSym); 3444 OS.AddComment("Name"); 3445 const unsigned LengthOfDataRecord = 12; 3446 emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord); 3447 endSymbolRecord(DataEnd); 3448 } else { 3449 const DIExpression *DIE = cast<const DIExpression *>(CVGV.GVInfo); 3450 assert(DIE->isConstant() && 3451 "Global constant variables must contain a constant expression."); 3452 3453 // Use unsigned for floats. 3454 bool isUnsigned = isFloatDIType(DIGV->getType()) 3455 ? true 3456 : DebugHandlerBase::isUnsignedDIType(DIGV->getType()); 3457 APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned); 3458 emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName); 3459 } 3460 } 3461 3462 void forEachJumpTableBranch( 3463 const MachineFunction *MF, bool isThumb, 3464 const std::function<void(const MachineJumpTableInfo &, const MachineInstr &, 3465 int64_t)> &Callback) { 3466 auto JTI = MF->getJumpTableInfo(); 3467 if (JTI && !JTI->isEmpty()) { 3468 #ifndef NDEBUG 3469 auto UsedJTs = llvm::SmallBitVector(JTI->getJumpTables().size()); 3470 #endif 3471 for (const auto &MBB : *MF) { 3472 // Search for indirect branches... 3473 const auto LastMI = MBB.getFirstTerminator(); 3474 if (LastMI != MBB.end() && LastMI->isIndirectBranch()) { 3475 if (isThumb) { 3476 // ... that directly use jump table operands. 3477 // NOTE: ARM uses pattern matching to lower its BR_JT SDNode to 3478 // machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node 3479 // interferes with this process *but* the resulting pseudo-instruction 3480 // uses a Jump Table operand, so extract the jump table index directly 3481 // from that. 3482 for (const auto &MO : LastMI->operands()) { 3483 if (MO.isJTI()) { 3484 unsigned Index = MO.getIndex(); 3485 #ifndef NDEBUG 3486 UsedJTs.set(Index); 3487 #endif 3488 Callback(*JTI, *LastMI, Index); 3489 break; 3490 } 3491 } 3492 } else { 3493 // ... that have jump table debug info. 3494 // NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node 3495 // when lowering the BR_JT SDNode to an indirect branch. 3496 for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I) { 3497 if (I->isJumpTableDebugInfo()) { 3498 unsigned Index = I->getOperand(0).getImm(); 3499 #ifndef NDEBUG 3500 UsedJTs.set(Index); 3501 #endif 3502 Callback(*JTI, *LastMI, Index); 3503 break; 3504 } 3505 } 3506 } 3507 } 3508 } 3509 #ifndef NDEBUG 3510 assert(UsedJTs.all() && 3511 "Some of jump tables were not used in a debug info instruction"); 3512 #endif 3513 } 3514 } 3515 3516 void CodeViewDebug::discoverJumpTableBranches(const MachineFunction *MF, 3517 bool isThumb) { 3518 forEachJumpTableBranch( 3519 MF, isThumb, 3520 [this](const MachineJumpTableInfo &, const MachineInstr &BranchMI, 3521 int64_t) { requestLabelBeforeInsn(&BranchMI); }); 3522 } 3523 3524 void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction *MF, 3525 bool isThumb) { 3526 forEachJumpTableBranch( 3527 MF, isThumb, 3528 [this, MF](const MachineJumpTableInfo &JTI, const MachineInstr &BranchMI, 3529 int64_t JumpTableIndex) { 3530 // For label-difference jump tables, find the base expression. 3531 // Otherwise the jump table uses an absolute address (so no base 3532 // is required). 3533 const MCSymbol *Base; 3534 uint64_t BaseOffset = 0; 3535 const MCSymbol *Branch = getLabelBeforeInsn(&BranchMI); 3536 JumpTableEntrySize EntrySize; 3537 switch (JTI.getEntryKind()) { 3538 case MachineJumpTableInfo::EK_Custom32: 3539 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 3540 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 3541 llvm_unreachable( 3542 "EK_Custom32, EK_GPRel32BlockAddress, and " 3543 "EK_GPRel64BlockAddress should never be emitted for COFF"); 3544 case MachineJumpTableInfo::EK_BlockAddress: 3545 // Each entry is an absolute address. 3546 EntrySize = JumpTableEntrySize::Pointer; 3547 Base = nullptr; 3548 break; 3549 case MachineJumpTableInfo::EK_Inline: 3550 case MachineJumpTableInfo::EK_LabelDifference32: 3551 case MachineJumpTableInfo::EK_LabelDifference64: 3552 // Ask the AsmPrinter. 3553 std::tie(Base, BaseOffset, Branch, EntrySize) = 3554 Asm->getCodeViewJumpTableInfo(JumpTableIndex, &BranchMI, Branch); 3555 break; 3556 } 3557 3558 CurFn->JumpTables.push_back( 3559 {EntrySize, Base, BaseOffset, Branch, 3560 MF->getJTISymbol(JumpTableIndex, MMI->getContext()), 3561 JTI.getJumpTables()[JumpTableIndex].MBBs.size()}); 3562 }); 3563 } 3564 3565 void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo &FI) { 3566 for (auto JumpTable : FI.JumpTables) { 3567 MCSymbol *JumpTableEnd = beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE); 3568 if (JumpTable.Base) { 3569 OS.AddComment("Base offset"); 3570 OS.emitCOFFSecRel32(JumpTable.Base, JumpTable.BaseOffset); 3571 OS.AddComment("Base section index"); 3572 OS.emitCOFFSectionIndex(JumpTable.Base); 3573 } else { 3574 OS.AddComment("Base offset"); 3575 OS.emitInt32(0); 3576 OS.AddComment("Base section index"); 3577 OS.emitInt16(0); 3578 } 3579 OS.AddComment("Switch type"); 3580 OS.emitInt16(static_cast<uint16_t>(JumpTable.EntrySize)); 3581 OS.AddComment("Branch offset"); 3582 OS.emitCOFFSecRel32(JumpTable.Branch, /*Offset=*/0); 3583 OS.AddComment("Table offset"); 3584 OS.emitCOFFSecRel32(JumpTable.Table, /*Offset=*/0); 3585 OS.AddComment("Branch section index"); 3586 OS.emitCOFFSectionIndex(JumpTable.Branch); 3587 OS.AddComment("Table section index"); 3588 OS.emitCOFFSectionIndex(JumpTable.Table); 3589 OS.AddComment("Entries count"); 3590 OS.emitInt32(JumpTable.TableSize); 3591 endSymbolRecord(JumpTableEnd); 3592 } 3593 } 3594 3595 void CodeViewDebug::emitInlinees( 3596 const SmallSet<codeview::TypeIndex, 1> &Inlinees) { 3597 // Divide the list of inlinees into chunks such that each chunk fits within 3598 // one record. 3599 constexpr size_t ChunkSize = 3600 (MaxRecordLength - sizeof(SymbolKind) - sizeof(uint32_t)) / 3601 sizeof(uint32_t); 3602 3603 SmallVector<TypeIndex> SortedInlinees{Inlinees.begin(), Inlinees.end()}; 3604 llvm::sort(SortedInlinees); 3605 3606 size_t CurrentIndex = 0; 3607 while (CurrentIndex < SortedInlinees.size()) { 3608 auto Symbol = beginSymbolRecord(SymbolKind::S_INLINEES); 3609 auto CurrentChunkSize = 3610 std::min(ChunkSize, SortedInlinees.size() - CurrentIndex); 3611 OS.AddComment("Count"); 3612 OS.emitInt32(CurrentChunkSize); 3613 3614 const size_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize; 3615 for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) { 3616 OS.AddComment("Inlinee"); 3617 OS.emitInt32(SortedInlinees[CurrentIndex].getIndex()); 3618 } 3619 endSymbolRecord(Symbol); 3620 } 3621 } 3622