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