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