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 OS << " "; 853 llvm::sys::printArg(OS, Arg, /*Quote=*/true); 854 LastArg = Arg; 855 } 856 OS.flush(); 857 return FlatCmdLine; 858 } 859 860 void CodeViewDebug::emitBuildInfo() { 861 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of 862 // build info. The known prefix is: 863 // - Absolute path of current directory 864 // - Compiler path 865 // - Main source file path, relative to CWD or absolute 866 // - Type server PDB file 867 // - Canonical compiler command line 868 // If frontend and backend compilation are separated (think llc or LTO), it's 869 // not clear if the compiler path should refer to the executable for the 870 // frontend or the backend. Leave it blank for now. 871 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {}; 872 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 873 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs. 874 const auto *CU = cast<DICompileUnit>(Node); 875 const DIFile *MainSourceFile = CU->getFile(); 876 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] = 877 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory()); 878 BuildInfoArgs[BuildInfoRecord::SourceFile] = 879 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename()); 880 // FIXME: PDB is intentionally blank unless we implement /Zi type servers. 881 BuildInfoArgs[BuildInfoRecord::TypeServerPDB] = 882 getStringIdTypeIdx(TypeTable, ""); 883 if (Asm->TM.Options.MCOptions.Argv0 != nullptr) { 884 BuildInfoArgs[BuildInfoRecord::BuildTool] = 885 getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0); 886 BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx( 887 TypeTable, flattenCommandLine(Asm->TM.Options.MCOptions.CommandLineArgs, 888 MainSourceFile->getFilename())); 889 } 890 BuildInfoRecord BIR(BuildInfoArgs); 891 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR); 892 893 // Make a new .debug$S subsection for the S_BUILDINFO record, which points 894 // from the module symbols into the type stream. 895 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 896 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO); 897 OS.AddComment("LF_BUILDINFO index"); 898 OS.emitInt32(BuildInfoIndex.getIndex()); 899 endSymbolRecord(BIEnd); 900 endCVSubsection(BISubsecEnd); 901 } 902 903 void CodeViewDebug::emitInlineeLinesSubsection() { 904 if (InlinedSubprograms.empty()) 905 return; 906 907 OS.AddComment("Inlinee lines subsection"); 908 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines); 909 910 // We emit the checksum info for files. This is used by debuggers to 911 // determine if a pdb matches the source before loading it. Visual Studio, 912 // for instance, will display a warning that the breakpoints are not valid if 913 // the pdb does not match the source. 914 OS.AddComment("Inlinee lines signature"); 915 OS.emitInt32(unsigned(InlineeLinesSignature::Normal)); 916 917 for (const DISubprogram *SP : InlinedSubprograms) { 918 assert(TypeIndices.count({SP, nullptr})); 919 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 920 921 OS.AddBlankLine(); 922 unsigned FileId = maybeRecordFile(SP->getFile()); 923 OS.AddComment("Inlined function " + SP->getName() + " starts at " + 924 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 925 OS.AddBlankLine(); 926 OS.AddComment("Type index of inlined function"); 927 OS.emitInt32(InlineeIdx.getIndex()); 928 OS.AddComment("Offset into filechecksum table"); 929 OS.emitCVFileChecksumOffsetDirective(FileId); 930 OS.AddComment("Starting line number"); 931 OS.emitInt32(SP->getLine()); 932 } 933 934 endCVSubsection(InlineEnd); 935 } 936 937 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 938 const DILocation *InlinedAt, 939 const InlineSite &Site) { 940 assert(TypeIndices.count({Site.Inlinee, nullptr})); 941 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 942 943 // SymbolRecord 944 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE); 945 946 OS.AddComment("PtrParent"); 947 OS.emitInt32(0); 948 OS.AddComment("PtrEnd"); 949 OS.emitInt32(0); 950 OS.AddComment("Inlinee type index"); 951 OS.emitInt32(InlineeIdx.getIndex()); 952 953 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 954 unsigned StartLineNum = Site.Inlinee->getLine(); 955 956 OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 957 FI.Begin, FI.End); 958 959 endSymbolRecord(InlineEnd); 960 961 emitLocalVariableList(FI, Site.InlinedLocals); 962 963 // Recurse on child inlined call sites before closing the scope. 964 for (const DILocation *ChildSite : Site.ChildSites) { 965 auto I = FI.InlineSites.find(ChildSite); 966 assert(I != FI.InlineSites.end() && 967 "child site not in function inline site map"); 968 emitInlinedCallSite(FI, ChildSite, I->second); 969 } 970 971 // Close the scope. 972 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END); 973 } 974 975 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 976 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 977 // comdat key. A section may be comdat because of -ffunction-sections or 978 // because it is comdat in the IR. 979 MCSectionCOFF *GVSec = 980 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 981 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 982 983 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 984 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 985 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 986 987 OS.SwitchSection(DebugSec); 988 989 // Emit the magic version number if this is the first time we've switched to 990 // this section. 991 if (ComdatDebugSections.insert(DebugSec).second) 992 emitCodeViewMagicVersion(); 993 } 994 995 // Emit an S_THUNK32/S_END symbol pair for a thunk routine. 996 // The only supported thunk ordinal is currently the standard type. 997 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV, 998 FunctionInfo &FI, 999 const MCSymbol *Fn) { 1000 std::string FuncName = 1001 std::string(GlobalValue::dropLLVMManglingEscape(GV->getName())); 1002 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind. 1003 1004 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 1005 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 1006 1007 // Emit S_THUNK32 1008 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32); 1009 OS.AddComment("PtrParent"); 1010 OS.emitInt32(0); 1011 OS.AddComment("PtrEnd"); 1012 OS.emitInt32(0); 1013 OS.AddComment("PtrNext"); 1014 OS.emitInt32(0); 1015 OS.AddComment("Thunk section relative address"); 1016 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); 1017 OS.AddComment("Thunk section index"); 1018 OS.EmitCOFFSectionIndex(Fn); 1019 OS.AddComment("Code size"); 1020 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2); 1021 OS.AddComment("Ordinal"); 1022 OS.emitInt8(unsigned(ordinal)); 1023 OS.AddComment("Function name"); 1024 emitNullTerminatedSymbolName(OS, FuncName); 1025 // Additional fields specific to the thunk ordinal would go here. 1026 endSymbolRecord(ThunkRecordEnd); 1027 1028 // Local variables/inlined routines are purposely omitted here. The point of 1029 // marking this as a thunk is so Visual Studio will NOT stop in this routine. 1030 1031 // Emit S_PROC_ID_END 1032 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); 1033 1034 endCVSubsection(SymbolsEnd); 1035 } 1036 1037 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 1038 FunctionInfo &FI) { 1039 // For each function there is a separate subsection which holds the PC to 1040 // file:line table. 1041 const MCSymbol *Fn = Asm->getSymbol(GV); 1042 assert(Fn); 1043 1044 // Switch to the to a comdat section, if appropriate. 1045 switchToDebugSectionForSymbol(Fn); 1046 1047 std::string FuncName; 1048 auto *SP = GV->getSubprogram(); 1049 assert(SP); 1050 setCurrentSubprogram(SP); 1051 1052 if (SP->isThunk()) { 1053 emitDebugInfoForThunk(GV, FI, Fn); 1054 return; 1055 } 1056 1057 // If we have a display name, build the fully qualified name by walking the 1058 // chain of scopes. 1059 if (!SP->getName().empty()) 1060 FuncName = getFullyQualifiedName(SP->getScope(), SP->getName()); 1061 1062 // If our DISubprogram name is empty, use the mangled name. 1063 if (FuncName.empty()) 1064 FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName())); 1065 1066 // Emit FPO data, but only on 32-bit x86. No other platforms use it. 1067 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86) 1068 OS.EmitCVFPOData(Fn); 1069 1070 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 1071 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 1072 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); 1073 { 1074 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID 1075 : SymbolKind::S_GPROC32_ID; 1076 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind); 1077 1078 // These fields are filled in by tools like CVPACK which run after the fact. 1079 OS.AddComment("PtrParent"); 1080 OS.emitInt32(0); 1081 OS.AddComment("PtrEnd"); 1082 OS.emitInt32(0); 1083 OS.AddComment("PtrNext"); 1084 OS.emitInt32(0); 1085 // This is the important bit that tells the debugger where the function 1086 // code is located and what's its size: 1087 OS.AddComment("Code size"); 1088 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 1089 OS.AddComment("Offset after prologue"); 1090 OS.emitInt32(0); 1091 OS.AddComment("Offset before epilogue"); 1092 OS.emitInt32(0); 1093 OS.AddComment("Function type index"); 1094 OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex()); 1095 OS.AddComment("Function section relative address"); 1096 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); 1097 OS.AddComment("Function section index"); 1098 OS.EmitCOFFSectionIndex(Fn); 1099 OS.AddComment("Flags"); 1100 OS.emitInt8(0); 1101 // Emit the function display name as a null-terminated string. 1102 OS.AddComment("Function name"); 1103 // Truncate the name so we won't overflow the record length field. 1104 emitNullTerminatedSymbolName(OS, FuncName); 1105 endSymbolRecord(ProcRecordEnd); 1106 1107 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC); 1108 // Subtract out the CSR size since MSVC excludes that and we include it. 1109 OS.AddComment("FrameSize"); 1110 OS.emitInt32(FI.FrameSize - FI.CSRSize); 1111 OS.AddComment("Padding"); 1112 OS.emitInt32(0); 1113 OS.AddComment("Offset of padding"); 1114 OS.emitInt32(0); 1115 OS.AddComment("Bytes of callee saved registers"); 1116 OS.emitInt32(FI.CSRSize); 1117 OS.AddComment("Exception handler offset"); 1118 OS.emitInt32(0); 1119 OS.AddComment("Exception handler section"); 1120 OS.emitInt16(0); 1121 OS.AddComment("Flags (defines frame register)"); 1122 OS.emitInt32(uint32_t(FI.FrameProcOpts)); 1123 endSymbolRecord(FrameProcEnd); 1124 1125 emitLocalVariableList(FI, FI.Locals); 1126 emitGlobalVariableList(FI.Globals); 1127 emitLexicalBlockList(FI.ChildBlocks, FI); 1128 1129 // Emit inlined call site information. Only emit functions inlined directly 1130 // into the parent function. We'll emit the other sites recursively as part 1131 // of their parent inline site. 1132 for (const DILocation *InlinedAt : FI.ChildSites) { 1133 auto I = FI.InlineSites.find(InlinedAt); 1134 assert(I != FI.InlineSites.end() && 1135 "child site not in function inline site map"); 1136 emitInlinedCallSite(FI, InlinedAt, I->second); 1137 } 1138 1139 for (auto Annot : FI.Annotations) { 1140 MCSymbol *Label = Annot.first; 1141 MDTuple *Strs = cast<MDTuple>(Annot.second); 1142 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION); 1143 OS.EmitCOFFSecRel32(Label, /*Offset=*/0); 1144 // FIXME: Make sure we don't overflow the max record size. 1145 OS.EmitCOFFSectionIndex(Label); 1146 OS.emitInt16(Strs->getNumOperands()); 1147 for (Metadata *MD : Strs->operands()) { 1148 // MDStrings are null terminated, so we can do EmitBytes and get the 1149 // nice .asciz directive. 1150 StringRef Str = cast<MDString>(MD)->getString(); 1151 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString"); 1152 OS.emitBytes(StringRef(Str.data(), Str.size() + 1)); 1153 } 1154 endSymbolRecord(AnnotEnd); 1155 } 1156 1157 for (auto HeapAllocSite : FI.HeapAllocSites) { 1158 const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite); 1159 const MCSymbol *EndLabel = std::get<1>(HeapAllocSite); 1160 const DIType *DITy = std::get<2>(HeapAllocSite); 1161 MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE); 1162 OS.AddComment("Call site offset"); 1163 OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0); 1164 OS.AddComment("Call site section index"); 1165 OS.EmitCOFFSectionIndex(BeginLabel); 1166 OS.AddComment("Call instruction length"); 1167 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); 1168 OS.AddComment("Type index"); 1169 OS.emitInt32(getCompleteTypeIndex(DITy).getIndex()); 1170 endSymbolRecord(HeapAllocEnd); 1171 } 1172 1173 if (SP != nullptr) 1174 emitDebugInfoForUDTs(LocalUDTs); 1175 1176 // We're done with this function. 1177 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); 1178 } 1179 endCVSubsection(SymbolsEnd); 1180 1181 // We have an assembler directive that takes care of the whole line table. 1182 OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End); 1183 } 1184 1185 CodeViewDebug::LocalVarDefRange 1186 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 1187 LocalVarDefRange DR; 1188 DR.InMemory = -1; 1189 DR.DataOffset = Offset; 1190 assert(DR.DataOffset == Offset && "truncation"); 1191 DR.IsSubfield = 0; 1192 DR.StructOffset = 0; 1193 DR.CVRegister = CVRegister; 1194 return DR; 1195 } 1196 1197 void CodeViewDebug::collectVariableInfoFromMFTable( 1198 DenseSet<InlinedEntity> &Processed) { 1199 const MachineFunction &MF = *Asm->MF; 1200 const TargetSubtargetInfo &TSI = MF.getSubtarget(); 1201 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 1202 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 1203 1204 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) { 1205 if (!VI.Var) 1206 continue; 1207 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1208 "Expected inlined-at fields to agree"); 1209 1210 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt())); 1211 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1212 1213 // If variable scope is not found then skip this variable. 1214 if (!Scope) 1215 continue; 1216 1217 // If the variable has an attached offset expression, extract it. 1218 // FIXME: Try to handle DW_OP_deref as well. 1219 int64_t ExprOffset = 0; 1220 bool Deref = false; 1221 if (VI.Expr) { 1222 // If there is one DW_OP_deref element, use offset of 0 and keep going. 1223 if (VI.Expr->getNumElements() == 1 && 1224 VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref) 1225 Deref = true; 1226 else if (!VI.Expr->extractIfOffset(ExprOffset)) 1227 continue; 1228 } 1229 1230 // Get the frame register used and the offset. 1231 Register FrameReg; 1232 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 1233 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 1234 1235 // Calculate the label ranges. 1236 LocalVarDefRange DefRange = 1237 createDefRangeMem(CVReg, FrameOffset + ExprOffset); 1238 1239 for (const InsnRange &Range : Scope->getRanges()) { 1240 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 1241 const MCSymbol *End = getLabelAfterInsn(Range.second); 1242 End = End ? End : Asm->getFunctionEnd(); 1243 DefRange.Ranges.emplace_back(Begin, End); 1244 } 1245 1246 LocalVariable Var; 1247 Var.DIVar = VI.Var; 1248 Var.DefRanges.emplace_back(std::move(DefRange)); 1249 if (Deref) 1250 Var.UseReferenceType = true; 1251 1252 recordLocalVariable(std::move(Var), Scope); 1253 } 1254 } 1255 1256 static bool canUseReferenceType(const DbgVariableLocation &Loc) { 1257 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0; 1258 } 1259 1260 static bool needsReferenceType(const DbgVariableLocation &Loc) { 1261 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0; 1262 } 1263 1264 void CodeViewDebug::calculateRanges( 1265 LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) { 1266 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 1267 1268 // Calculate the definition ranges. 1269 for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) { 1270 const auto &Entry = *I; 1271 if (!Entry.isDbgValue()) 1272 continue; 1273 const MachineInstr *DVInst = Entry.getInstr(); 1274 assert(DVInst->isDebugValue() && "Invalid History entry"); 1275 // FIXME: Find a way to represent constant variables, since they are 1276 // relatively common. 1277 Optional<DbgVariableLocation> Location = 1278 DbgVariableLocation::extractFromMachineInstruction(*DVInst); 1279 if (!Location) 1280 continue; 1281 1282 // CodeView can only express variables in register and variables in memory 1283 // at a constant offset from a register. However, for variables passed 1284 // indirectly by pointer, it is common for that pointer to be spilled to a 1285 // stack location. For the special case of one offseted load followed by a 1286 // zero offset load (a pointer spilled to the stack), we change the type of 1287 // the local variable from a value type to a reference type. This tricks the 1288 // debugger into doing the load for us. 1289 if (Var.UseReferenceType) { 1290 // We're using a reference type. Drop the last zero offset load. 1291 if (canUseReferenceType(*Location)) 1292 Location->LoadChain.pop_back(); 1293 else 1294 continue; 1295 } else if (needsReferenceType(*Location)) { 1296 // This location can't be expressed without switching to a reference type. 1297 // Start over using that. 1298 Var.UseReferenceType = true; 1299 Var.DefRanges.clear(); 1300 calculateRanges(Var, Entries); 1301 return; 1302 } 1303 1304 // We can only handle a register or an offseted load of a register. 1305 if (Location->Register == 0 || Location->LoadChain.size() > 1) 1306 continue; 1307 { 1308 LocalVarDefRange DR; 1309 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register); 1310 DR.InMemory = !Location->LoadChain.empty(); 1311 DR.DataOffset = 1312 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0; 1313 if (Location->FragmentInfo) { 1314 DR.IsSubfield = true; 1315 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8; 1316 } else { 1317 DR.IsSubfield = false; 1318 DR.StructOffset = 0; 1319 } 1320 1321 if (Var.DefRanges.empty() || 1322 Var.DefRanges.back().isDifferentLocation(DR)) { 1323 Var.DefRanges.emplace_back(std::move(DR)); 1324 } 1325 } 1326 1327 // Compute the label range. 1328 const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr()); 1329 const MCSymbol *End; 1330 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) { 1331 auto &EndingEntry = Entries[Entry.getEndIndex()]; 1332 End = EndingEntry.isDbgValue() 1333 ? getLabelBeforeInsn(EndingEntry.getInstr()) 1334 : getLabelAfterInsn(EndingEntry.getInstr()); 1335 } else 1336 End = Asm->getFunctionEnd(); 1337 1338 // If the last range end is our begin, just extend the last range. 1339 // Otherwise make a new range. 1340 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R = 1341 Var.DefRanges.back().Ranges; 1342 if (!R.empty() && R.back().second == Begin) 1343 R.back().second = End; 1344 else 1345 R.emplace_back(Begin, End); 1346 1347 // FIXME: Do more range combining. 1348 } 1349 } 1350 1351 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 1352 DenseSet<InlinedEntity> Processed; 1353 // Grab the variable info that was squirreled away in the MMI side-table. 1354 collectVariableInfoFromMFTable(Processed); 1355 1356 for (const auto &I : DbgValues) { 1357 InlinedEntity IV = I.first; 1358 if (Processed.count(IV)) 1359 continue; 1360 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first); 1361 const DILocation *InlinedAt = IV.second; 1362 1363 // Instruction ranges, specifying where IV is accessible. 1364 const auto &Entries = I.second; 1365 1366 LexicalScope *Scope = nullptr; 1367 if (InlinedAt) 1368 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 1369 else 1370 Scope = LScopes.findLexicalScope(DIVar->getScope()); 1371 // If variable scope is not found then skip this variable. 1372 if (!Scope) 1373 continue; 1374 1375 LocalVariable Var; 1376 Var.DIVar = DIVar; 1377 1378 calculateRanges(Var, Entries); 1379 recordLocalVariable(std::move(Var), Scope); 1380 } 1381 } 1382 1383 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) { 1384 const TargetSubtargetInfo &TSI = MF->getSubtarget(); 1385 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 1386 const MachineFrameInfo &MFI = MF->getFrameInfo(); 1387 const Function &GV = MF->getFunction(); 1388 auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()}); 1389 assert(Insertion.second && "function already has info"); 1390 CurFn = Insertion.first->second.get(); 1391 CurFn->FuncId = NextFuncId++; 1392 CurFn->Begin = Asm->getFunctionBegin(); 1393 1394 // The S_FRAMEPROC record reports the stack size, and how many bytes of 1395 // callee-saved registers were used. For targets that don't use a PUSH 1396 // instruction (AArch64), this will be zero. 1397 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters(); 1398 CurFn->FrameSize = MFI.getStackSize(); 1399 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment(); 1400 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF); 1401 1402 // For this function S_FRAMEPROC record, figure out which codeview register 1403 // will be the frame pointer. 1404 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None. 1405 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None. 1406 if (CurFn->FrameSize > 0) { 1407 if (!TSI.getFrameLowering()->hasFP(*MF)) { 1408 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; 1409 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr; 1410 } else { 1411 // If there is an FP, parameters are always relative to it. 1412 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr; 1413 if (CurFn->HasStackRealignment) { 1414 // If the stack needs realignment, locals are relative to SP or VFRAME. 1415 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; 1416 } else { 1417 // Otherwise, locals are relative to EBP, and we probably have VLAs or 1418 // other stack adjustments. 1419 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr; 1420 } 1421 } 1422 } 1423 1424 // Compute other frame procedure options. 1425 FrameProcedureOptions FPO = FrameProcedureOptions::None; 1426 if (MFI.hasVarSizedObjects()) 1427 FPO |= FrameProcedureOptions::HasAlloca; 1428 if (MF->exposesReturnsTwice()) 1429 FPO |= FrameProcedureOptions::HasSetJmp; 1430 // FIXME: Set HasLongJmp if we ever track that info. 1431 if (MF->hasInlineAsm()) 1432 FPO |= FrameProcedureOptions::HasInlineAssembly; 1433 if (GV.hasPersonalityFn()) { 1434 if (isAsynchronousEHPersonality( 1435 classifyEHPersonality(GV.getPersonalityFn()))) 1436 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling; 1437 else 1438 FPO |= FrameProcedureOptions::HasExceptionHandling; 1439 } 1440 if (GV.hasFnAttribute(Attribute::InlineHint)) 1441 FPO |= FrameProcedureOptions::MarkedInline; 1442 if (GV.hasFnAttribute(Attribute::Naked)) 1443 FPO |= FrameProcedureOptions::Naked; 1444 if (MFI.hasStackProtectorIndex()) 1445 FPO |= FrameProcedureOptions::SecurityChecks; 1446 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U); 1447 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U); 1448 if (Asm->TM.getOptLevel() != CodeGenOpt::None && 1449 !GV.hasOptSize() && !GV.hasOptNone()) 1450 FPO |= FrameProcedureOptions::OptimizedForSpeed; 1451 // FIXME: Set GuardCfg when it is implemented. 1452 CurFn->FrameProcOpts = FPO; 1453 1454 OS.EmitCVFuncIdDirective(CurFn->FuncId); 1455 1456 // Find the end of the function prolog. First known non-DBG_VALUE and 1457 // non-frame setup location marks the beginning of the function body. 1458 // FIXME: is there a simpler a way to do this? Can we just search 1459 // for the first instruction of the function, not the last of the prolog? 1460 DebugLoc PrologEndLoc; 1461 bool EmptyPrologue = true; 1462 for (const auto &MBB : *MF) { 1463 for (const auto &MI : MBB) { 1464 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1465 MI.getDebugLoc()) { 1466 PrologEndLoc = MI.getDebugLoc(); 1467 break; 1468 } else if (!MI.isMetaInstruction()) { 1469 EmptyPrologue = false; 1470 } 1471 } 1472 } 1473 1474 // Record beginning of function if we have a non-empty prologue. 1475 if (PrologEndLoc && !EmptyPrologue) { 1476 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 1477 maybeRecordLocation(FnStartDL, MF); 1478 } 1479 1480 // Find heap alloc sites and emit labels around them. 1481 for (const auto &MBB : *MF) { 1482 for (const auto &MI : MBB) { 1483 if (MI.getHeapAllocMarker()) { 1484 requestLabelBeforeInsn(&MI); 1485 requestLabelAfterInsn(&MI); 1486 } 1487 } 1488 } 1489 } 1490 1491 static bool shouldEmitUdt(const DIType *T) { 1492 if (!T) 1493 return false; 1494 1495 // MSVC does not emit UDTs for typedefs that are scoped to classes. 1496 if (T->getTag() == dwarf::DW_TAG_typedef) { 1497 if (DIScope *Scope = T->getScope()) { 1498 switch (Scope->getTag()) { 1499 case dwarf::DW_TAG_structure_type: 1500 case dwarf::DW_TAG_class_type: 1501 case dwarf::DW_TAG_union_type: 1502 return false; 1503 } 1504 } 1505 } 1506 1507 while (true) { 1508 if (!T || T->isForwardDecl()) 1509 return false; 1510 1511 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T); 1512 if (!DT) 1513 return true; 1514 T = DT->getBaseType(); 1515 } 1516 return true; 1517 } 1518 1519 void CodeViewDebug::addToUDTs(const DIType *Ty) { 1520 // Don't record empty UDTs. 1521 if (Ty->getName().empty()) 1522 return; 1523 if (!shouldEmitUdt(Ty)) 1524 return; 1525 1526 SmallVector<StringRef, 5> ParentScopeNames; 1527 const DISubprogram *ClosestSubprogram = 1528 collectParentScopeNames(Ty->getScope(), ParentScopeNames); 1529 1530 std::string FullyQualifiedName = 1531 formatNestedName(ParentScopeNames, getPrettyScopeName(Ty)); 1532 1533 if (ClosestSubprogram == nullptr) { 1534 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); 1535 } else if (ClosestSubprogram == CurrentSubprogram) { 1536 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); 1537 } 1538 1539 // TODO: What if the ClosestSubprogram is neither null or the current 1540 // subprogram? Currently, the UDT just gets dropped on the floor. 1541 // 1542 // The current behavior is not desirable. To get maximal fidelity, we would 1543 // need to perform all type translation before beginning emission of .debug$S 1544 // and then make LocalUDTs a member of FunctionInfo 1545 } 1546 1547 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 1548 // Generic dispatch for lowering an unknown type. 1549 switch (Ty->getTag()) { 1550 case dwarf::DW_TAG_array_type: 1551 return lowerTypeArray(cast<DICompositeType>(Ty)); 1552 case dwarf::DW_TAG_typedef: 1553 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 1554 case dwarf::DW_TAG_base_type: 1555 return lowerTypeBasic(cast<DIBasicType>(Ty)); 1556 case dwarf::DW_TAG_pointer_type: 1557 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type") 1558 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty)); 1559 LLVM_FALLTHROUGH; 1560 case dwarf::DW_TAG_reference_type: 1561 case dwarf::DW_TAG_rvalue_reference_type: 1562 return lowerTypePointer(cast<DIDerivedType>(Ty)); 1563 case dwarf::DW_TAG_ptr_to_member_type: 1564 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 1565 case dwarf::DW_TAG_restrict_type: 1566 case dwarf::DW_TAG_const_type: 1567 case dwarf::DW_TAG_volatile_type: 1568 // TODO: add support for DW_TAG_atomic_type here 1569 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 1570 case dwarf::DW_TAG_subroutine_type: 1571 if (ClassTy) { 1572 // The member function type of a member function pointer has no 1573 // ThisAdjustment. 1574 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, 1575 /*ThisAdjustment=*/0, 1576 /*IsStaticMethod=*/false); 1577 } 1578 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 1579 case dwarf::DW_TAG_enumeration_type: 1580 return lowerTypeEnum(cast<DICompositeType>(Ty)); 1581 case dwarf::DW_TAG_class_type: 1582 case dwarf::DW_TAG_structure_type: 1583 return lowerTypeClass(cast<DICompositeType>(Ty)); 1584 case dwarf::DW_TAG_union_type: 1585 return lowerTypeUnion(cast<DICompositeType>(Ty)); 1586 case dwarf::DW_TAG_unspecified_type: 1587 if (Ty->getName() == "decltype(nullptr)") 1588 return TypeIndex::NullptrT(); 1589 return TypeIndex::None(); 1590 default: 1591 // Use the null type index. 1592 return TypeIndex(); 1593 } 1594 } 1595 1596 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 1597 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType()); 1598 StringRef TypeName = Ty->getName(); 1599 1600 addToUDTs(Ty); 1601 1602 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 1603 TypeName == "HRESULT") 1604 return TypeIndex(SimpleTypeKind::HResult); 1605 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 1606 TypeName == "wchar_t") 1607 return TypeIndex(SimpleTypeKind::WideCharacter); 1608 1609 return UnderlyingTypeIndex; 1610 } 1611 1612 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 1613 const DIType *ElementType = Ty->getBaseType(); 1614 TypeIndex ElementTypeIndex = getTypeIndex(ElementType); 1615 // IndexType is size_t, which depends on the bitness of the target. 1616 TypeIndex IndexType = getPointerSizeInBytes() == 8 1617 ? TypeIndex(SimpleTypeKind::UInt64Quad) 1618 : TypeIndex(SimpleTypeKind::UInt32Long); 1619 1620 uint64_t ElementSize = getBaseTypeSize(ElementType) / 8; 1621 1622 // Add subranges to array type. 1623 DINodeArray Elements = Ty->getElements(); 1624 for (int i = Elements.size() - 1; i >= 0; --i) { 1625 const DINode *Element = Elements[i]; 1626 assert(Element->getTag() == dwarf::DW_TAG_subrange_type); 1627 1628 const DISubrange *Subrange = cast<DISubrange>(Element); 1629 assert(!Subrange->getRawLowerBound() && 1630 "codeview doesn't support subranges with lower bounds"); 1631 int64_t Count = -1; 1632 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>()) 1633 Count = CI->getSExtValue(); 1634 1635 // Forward declarations of arrays without a size and VLAs use a count of -1. 1636 // Emit a count of zero in these cases to match what MSVC does for arrays 1637 // without a size. MSVC doesn't support VLAs, so it's not clear what we 1638 // should do for them even if we could distinguish them. 1639 if (Count == -1) 1640 Count = 0; 1641 1642 // Update the element size and element type index for subsequent subranges. 1643 ElementSize *= Count; 1644 1645 // If this is the outermost array, use the size from the array. It will be 1646 // more accurate if we had a VLA or an incomplete element type size. 1647 uint64_t ArraySize = 1648 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize; 1649 1650 StringRef Name = (i == 0) ? Ty->getName() : ""; 1651 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name); 1652 ElementTypeIndex = TypeTable.writeLeafType(AR); 1653 } 1654 1655 return ElementTypeIndex; 1656 } 1657 1658 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 1659 TypeIndex Index; 1660 dwarf::TypeKind Kind; 1661 uint32_t ByteSize; 1662 1663 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 1664 ByteSize = Ty->getSizeInBits() / 8; 1665 1666 SimpleTypeKind STK = SimpleTypeKind::None; 1667 switch (Kind) { 1668 case dwarf::DW_ATE_address: 1669 // FIXME: Translate 1670 break; 1671 case dwarf::DW_ATE_boolean: 1672 switch (ByteSize) { 1673 case 1: STK = SimpleTypeKind::Boolean8; break; 1674 case 2: STK = SimpleTypeKind::Boolean16; break; 1675 case 4: STK = SimpleTypeKind::Boolean32; break; 1676 case 8: STK = SimpleTypeKind::Boolean64; break; 1677 case 16: STK = SimpleTypeKind::Boolean128; break; 1678 } 1679 break; 1680 case dwarf::DW_ATE_complex_float: 1681 switch (ByteSize) { 1682 case 2: STK = SimpleTypeKind::Complex16; break; 1683 case 4: STK = SimpleTypeKind::Complex32; break; 1684 case 8: STK = SimpleTypeKind::Complex64; break; 1685 case 10: STK = SimpleTypeKind::Complex80; break; 1686 case 16: STK = SimpleTypeKind::Complex128; break; 1687 } 1688 break; 1689 case dwarf::DW_ATE_float: 1690 switch (ByteSize) { 1691 case 2: STK = SimpleTypeKind::Float16; break; 1692 case 4: STK = SimpleTypeKind::Float32; break; 1693 case 6: STK = SimpleTypeKind::Float48; break; 1694 case 8: STK = SimpleTypeKind::Float64; break; 1695 case 10: STK = SimpleTypeKind::Float80; break; 1696 case 16: STK = SimpleTypeKind::Float128; break; 1697 } 1698 break; 1699 case dwarf::DW_ATE_signed: 1700 switch (ByteSize) { 1701 case 1: STK = SimpleTypeKind::SignedCharacter; break; 1702 case 2: STK = SimpleTypeKind::Int16Short; break; 1703 case 4: STK = SimpleTypeKind::Int32; break; 1704 case 8: STK = SimpleTypeKind::Int64Quad; break; 1705 case 16: STK = SimpleTypeKind::Int128Oct; break; 1706 } 1707 break; 1708 case dwarf::DW_ATE_unsigned: 1709 switch (ByteSize) { 1710 case 1: STK = SimpleTypeKind::UnsignedCharacter; break; 1711 case 2: STK = SimpleTypeKind::UInt16Short; break; 1712 case 4: STK = SimpleTypeKind::UInt32; break; 1713 case 8: STK = SimpleTypeKind::UInt64Quad; break; 1714 case 16: STK = SimpleTypeKind::UInt128Oct; break; 1715 } 1716 break; 1717 case dwarf::DW_ATE_UTF: 1718 switch (ByteSize) { 1719 case 2: STK = SimpleTypeKind::Character16; break; 1720 case 4: STK = SimpleTypeKind::Character32; break; 1721 } 1722 break; 1723 case dwarf::DW_ATE_signed_char: 1724 if (ByteSize == 1) 1725 STK = SimpleTypeKind::SignedCharacter; 1726 break; 1727 case dwarf::DW_ATE_unsigned_char: 1728 if (ByteSize == 1) 1729 STK = SimpleTypeKind::UnsignedCharacter; 1730 break; 1731 default: 1732 break; 1733 } 1734 1735 // Apply some fixups based on the source-level type name. 1736 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 1737 STK = SimpleTypeKind::Int32Long; 1738 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 1739 STK = SimpleTypeKind::UInt32Long; 1740 if (STK == SimpleTypeKind::UInt16Short && 1741 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 1742 STK = SimpleTypeKind::WideCharacter; 1743 if ((STK == SimpleTypeKind::SignedCharacter || 1744 STK == SimpleTypeKind::UnsignedCharacter) && 1745 Ty->getName() == "char") 1746 STK = SimpleTypeKind::NarrowCharacter; 1747 1748 return TypeIndex(STK); 1749 } 1750 1751 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty, 1752 PointerOptions PO) { 1753 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 1754 1755 // Pointers to simple types without any options can use SimpleTypeMode, rather 1756 // than having a dedicated pointer type record. 1757 if (PointeeTI.isSimple() && PO == PointerOptions::None && 1758 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 1759 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 1760 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 1761 ? SimpleTypeMode::NearPointer64 1762 : SimpleTypeMode::NearPointer32; 1763 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 1764 } 1765 1766 PointerKind PK = 1767 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 1768 PointerMode PM = PointerMode::Pointer; 1769 switch (Ty->getTag()) { 1770 default: llvm_unreachable("not a pointer tag type"); 1771 case dwarf::DW_TAG_pointer_type: 1772 PM = PointerMode::Pointer; 1773 break; 1774 case dwarf::DW_TAG_reference_type: 1775 PM = PointerMode::LValueReference; 1776 break; 1777 case dwarf::DW_TAG_rvalue_reference_type: 1778 PM = PointerMode::RValueReference; 1779 break; 1780 } 1781 1782 if (Ty->isObjectPointer()) 1783 PO |= PointerOptions::Const; 1784 1785 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 1786 return TypeTable.writeLeafType(PR); 1787 } 1788 1789 static PointerToMemberRepresentation 1790 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 1791 // SizeInBytes being zero generally implies that the member pointer type was 1792 // incomplete, which can happen if it is part of a function prototype. In this 1793 // case, use the unknown model instead of the general model. 1794 if (IsPMF) { 1795 switch (Flags & DINode::FlagPtrToMemberRep) { 1796 case 0: 1797 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1798 : PointerToMemberRepresentation::GeneralFunction; 1799 case DINode::FlagSingleInheritance: 1800 return PointerToMemberRepresentation::SingleInheritanceFunction; 1801 case DINode::FlagMultipleInheritance: 1802 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1803 case DINode::FlagVirtualInheritance: 1804 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1805 } 1806 } else { 1807 switch (Flags & DINode::FlagPtrToMemberRep) { 1808 case 0: 1809 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1810 : PointerToMemberRepresentation::GeneralData; 1811 case DINode::FlagSingleInheritance: 1812 return PointerToMemberRepresentation::SingleInheritanceData; 1813 case DINode::FlagMultipleInheritance: 1814 return PointerToMemberRepresentation::MultipleInheritanceData; 1815 case DINode::FlagVirtualInheritance: 1816 return PointerToMemberRepresentation::VirtualInheritanceData; 1817 } 1818 } 1819 llvm_unreachable("invalid ptr to member representation"); 1820 } 1821 1822 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty, 1823 PointerOptions PO) { 1824 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1825 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1826 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1827 TypeIndex PointeeTI = 1828 getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr); 1829 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 1830 : PointerKind::Near32; 1831 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1832 : PointerMode::PointerToDataMember; 1833 1834 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1835 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1836 MemberPointerInfo MPI( 1837 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1838 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1839 return TypeTable.writeLeafType(PR); 1840 } 1841 1842 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1843 /// have a translation, use the NearC convention. 1844 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1845 switch (DwarfCC) { 1846 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1847 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1848 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1849 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1850 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1851 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 1852 } 1853 return CallingConvention::NearC; 1854 } 1855 1856 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 1857 ModifierOptions Mods = ModifierOptions::None; 1858 PointerOptions PO = PointerOptions::None; 1859 bool IsModifier = true; 1860 const DIType *BaseTy = Ty; 1861 while (IsModifier && BaseTy) { 1862 // FIXME: Need to add DWARF tags for __unaligned and _Atomic 1863 switch (BaseTy->getTag()) { 1864 case dwarf::DW_TAG_const_type: 1865 Mods |= ModifierOptions::Const; 1866 PO |= PointerOptions::Const; 1867 break; 1868 case dwarf::DW_TAG_volatile_type: 1869 Mods |= ModifierOptions::Volatile; 1870 PO |= PointerOptions::Volatile; 1871 break; 1872 case dwarf::DW_TAG_restrict_type: 1873 // Only pointer types be marked with __restrict. There is no known flag 1874 // for __restrict in LF_MODIFIER records. 1875 PO |= PointerOptions::Restrict; 1876 break; 1877 default: 1878 IsModifier = false; 1879 break; 1880 } 1881 if (IsModifier) 1882 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType(); 1883 } 1884 1885 // Check if the inner type will use an LF_POINTER record. If so, the 1886 // qualifiers will go in the LF_POINTER record. This comes up for types like 1887 // 'int *const' and 'int *__restrict', not the more common cases like 'const 1888 // char *'. 1889 if (BaseTy) { 1890 switch (BaseTy->getTag()) { 1891 case dwarf::DW_TAG_pointer_type: 1892 case dwarf::DW_TAG_reference_type: 1893 case dwarf::DW_TAG_rvalue_reference_type: 1894 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO); 1895 case dwarf::DW_TAG_ptr_to_member_type: 1896 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO); 1897 default: 1898 break; 1899 } 1900 } 1901 1902 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 1903 1904 // Return the base type index if there aren't any modifiers. For example, the 1905 // metadata could contain restrict wrappers around non-pointer types. 1906 if (Mods == ModifierOptions::None) 1907 return ModifiedTI; 1908 1909 ModifierRecord MR(ModifiedTI, Mods); 1910 return TypeTable.writeLeafType(MR); 1911 } 1912 1913 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 1914 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1915 for (const DIType *ArgType : Ty->getTypeArray()) 1916 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType)); 1917 1918 // MSVC uses type none for variadic argument. 1919 if (ReturnAndArgTypeIndices.size() > 1 && 1920 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) { 1921 ReturnAndArgTypeIndices.back() = TypeIndex::None(); 1922 } 1923 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1924 ArrayRef<TypeIndex> ArgTypeIndices = None; 1925 if (!ReturnAndArgTypeIndices.empty()) { 1926 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1927 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1928 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1929 } 1930 1931 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1932 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); 1933 1934 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1935 1936 FunctionOptions FO = getFunctionOptions(Ty); 1937 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(), 1938 ArgListIndex); 1939 return TypeTable.writeLeafType(Procedure); 1940 } 1941 1942 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 1943 const DIType *ClassTy, 1944 int ThisAdjustment, 1945 bool IsStaticMethod, 1946 FunctionOptions FO) { 1947 // Lower the containing class type. 1948 TypeIndex ClassType = getTypeIndex(ClassTy); 1949 1950 DITypeRefArray ReturnAndArgs = Ty->getTypeArray(); 1951 1952 unsigned Index = 0; 1953 SmallVector<TypeIndex, 8> ArgTypeIndices; 1954 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1955 if (ReturnAndArgs.size() > Index) { 1956 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]); 1957 } 1958 1959 // If the first argument is a pointer type and this isn't a static method, 1960 // treat it as the special 'this' parameter, which is encoded separately from 1961 // the arguments. 1962 TypeIndex ThisTypeIndex; 1963 if (!IsStaticMethod && ReturnAndArgs.size() > Index) { 1964 if (const DIDerivedType *PtrTy = 1965 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) { 1966 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) { 1967 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty); 1968 Index++; 1969 } 1970 } 1971 } 1972 1973 while (Index < ReturnAndArgs.size()) 1974 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++])); 1975 1976 // MSVC uses type none for variadic argument. 1977 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void()) 1978 ArgTypeIndices.back() = TypeIndex::None(); 1979 1980 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1981 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); 1982 1983 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1984 1985 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO, 1986 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment); 1987 return TypeTable.writeLeafType(MFR); 1988 } 1989 1990 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) { 1991 unsigned VSlotCount = 1992 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize()); 1993 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near); 1994 1995 VFTableShapeRecord VFTSR(Slots); 1996 return TypeTable.writeLeafType(VFTSR); 1997 } 1998 1999 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 2000 switch (Flags & DINode::FlagAccessibility) { 2001 case DINode::FlagPrivate: return MemberAccess::Private; 2002 case DINode::FlagPublic: return MemberAccess::Public; 2003 case DINode::FlagProtected: return MemberAccess::Protected; 2004 case 0: 2005 // If there was no explicit access control, provide the default for the tag. 2006 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 2007 : MemberAccess::Public; 2008 } 2009 llvm_unreachable("access flags are exclusive"); 2010 } 2011 2012 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 2013 if (SP->isArtificial()) 2014 return MethodOptions::CompilerGenerated; 2015 2016 // FIXME: Handle other MethodOptions. 2017 2018 return MethodOptions::None; 2019 } 2020 2021 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 2022 bool Introduced) { 2023 if (SP->getFlags() & DINode::FlagStaticMember) 2024 return MethodKind::Static; 2025 2026 switch (SP->getVirtuality()) { 2027 case dwarf::DW_VIRTUALITY_none: 2028 break; 2029 case dwarf::DW_VIRTUALITY_virtual: 2030 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 2031 case dwarf::DW_VIRTUALITY_pure_virtual: 2032 return Introduced ? MethodKind::PureIntroducingVirtual 2033 : MethodKind::PureVirtual; 2034 default: 2035 llvm_unreachable("unhandled virtuality case"); 2036 } 2037 2038 return MethodKind::Vanilla; 2039 } 2040 2041 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 2042 switch (Ty->getTag()) { 2043 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 2044 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 2045 } 2046 llvm_unreachable("unexpected tag"); 2047 } 2048 2049 /// Return ClassOptions that should be present on both the forward declaration 2050 /// and the defintion of a tag type. 2051 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) { 2052 ClassOptions CO = ClassOptions::None; 2053 2054 // MSVC always sets this flag, even for local types. Clang doesn't always 2055 // appear to give every type a linkage name, which may be problematic for us. 2056 // FIXME: Investigate the consequences of not following them here. 2057 if (!Ty->getIdentifier().empty()) 2058 CO |= ClassOptions::HasUniqueName; 2059 2060 // Put the Nested flag on a type if it appears immediately inside a tag type. 2061 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass 2062 // here. That flag is only set on definitions, and not forward declarations. 2063 const DIScope *ImmediateScope = Ty->getScope(); 2064 if (ImmediateScope && isa<DICompositeType>(ImmediateScope)) 2065 CO |= ClassOptions::Nested; 2066 2067 // Put the Scoped flag on function-local types. MSVC puts this flag for enum 2068 // type only when it has an immediate function scope. Clang never puts enums 2069 // inside DILexicalBlock scopes. Enum types, as generated by clang, are 2070 // always in function, class, or file scopes. 2071 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) { 2072 if (ImmediateScope && isa<DISubprogram>(ImmediateScope)) 2073 CO |= ClassOptions::Scoped; 2074 } else { 2075 for (const DIScope *Scope = ImmediateScope; Scope != nullptr; 2076 Scope = Scope->getScope()) { 2077 if (isa<DISubprogram>(Scope)) { 2078 CO |= ClassOptions::Scoped; 2079 break; 2080 } 2081 } 2082 } 2083 2084 return CO; 2085 } 2086 2087 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) { 2088 switch (Ty->getTag()) { 2089 case dwarf::DW_TAG_class_type: 2090 case dwarf::DW_TAG_structure_type: 2091 case dwarf::DW_TAG_union_type: 2092 case dwarf::DW_TAG_enumeration_type: 2093 break; 2094 default: 2095 return; 2096 } 2097 2098 if (const auto *File = Ty->getFile()) { 2099 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File)); 2100 TypeIndex SIDI = TypeTable.writeLeafType(SIDR); 2101 2102 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine()); 2103 TypeTable.writeLeafType(USLR); 2104 } 2105 } 2106 2107 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 2108 ClassOptions CO = getCommonClassOptions(Ty); 2109 TypeIndex FTI; 2110 unsigned EnumeratorCount = 0; 2111 2112 if (Ty->isForwardDecl()) { 2113 CO |= ClassOptions::ForwardReference; 2114 } else { 2115 ContinuationRecordBuilder ContinuationBuilder; 2116 ContinuationBuilder.begin(ContinuationRecordKind::FieldList); 2117 for (const DINode *Element : Ty->getElements()) { 2118 // We assume that the frontend provides all members in source declaration 2119 // order, which is what MSVC does. 2120 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 2121 EnumeratorRecord ER(MemberAccess::Public, 2122 APSInt(Enumerator->getValue(), true), 2123 Enumerator->getName()); 2124 ContinuationBuilder.writeMemberType(ER); 2125 EnumeratorCount++; 2126 } 2127 } 2128 FTI = TypeTable.insertRecord(ContinuationBuilder); 2129 } 2130 2131 std::string FullName = getFullyQualifiedName(Ty); 2132 2133 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(), 2134 getTypeIndex(Ty->getBaseType())); 2135 TypeIndex EnumTI = TypeTable.writeLeafType(ER); 2136 2137 addUDTSrcLine(Ty, EnumTI); 2138 2139 return EnumTI; 2140 } 2141 2142 //===----------------------------------------------------------------------===// 2143 // ClassInfo 2144 //===----------------------------------------------------------------------===// 2145 2146 struct llvm::ClassInfo { 2147 struct MemberInfo { 2148 const DIDerivedType *MemberTypeNode; 2149 uint64_t BaseOffset; 2150 }; 2151 // [MemberInfo] 2152 using MemberList = std::vector<MemberInfo>; 2153 2154 using MethodsList = TinyPtrVector<const DISubprogram *>; 2155 // MethodName -> MethodsList 2156 using MethodsMap = MapVector<MDString *, MethodsList>; 2157 2158 /// Base classes. 2159 std::vector<const DIDerivedType *> Inheritance; 2160 2161 /// Direct members. 2162 MemberList Members; 2163 // Direct overloaded methods gathered by name. 2164 MethodsMap Methods; 2165 2166 TypeIndex VShapeTI; 2167 2168 std::vector<const DIType *> NestedTypes; 2169 }; 2170 2171 void CodeViewDebug::clear() { 2172 assert(CurFn == nullptr); 2173 FileIdMap.clear(); 2174 FnDebugInfo.clear(); 2175 FileToFilepathMap.clear(); 2176 LocalUDTs.clear(); 2177 GlobalUDTs.clear(); 2178 TypeIndices.clear(); 2179 CompleteTypeIndices.clear(); 2180 ScopeGlobals.clear(); 2181 } 2182 2183 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 2184 const DIDerivedType *DDTy) { 2185 if (!DDTy->getName().empty()) { 2186 Info.Members.push_back({DDTy, 0}); 2187 return; 2188 } 2189 2190 // An unnamed member may represent a nested struct or union. Attempt to 2191 // interpret the unnamed member as a DICompositeType possibly wrapped in 2192 // qualifier types. Add all the indirect fields to the current record if that 2193 // succeeds, and drop the member if that fails. 2194 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 2195 uint64_t Offset = DDTy->getOffsetInBits(); 2196 const DIType *Ty = DDTy->getBaseType(); 2197 bool FullyResolved = false; 2198 while (!FullyResolved) { 2199 switch (Ty->getTag()) { 2200 case dwarf::DW_TAG_const_type: 2201 case dwarf::DW_TAG_volatile_type: 2202 // FIXME: we should apply the qualifier types to the indirect fields 2203 // rather than dropping them. 2204 Ty = cast<DIDerivedType>(Ty)->getBaseType(); 2205 break; 2206 default: 2207 FullyResolved = true; 2208 break; 2209 } 2210 } 2211 2212 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty); 2213 if (!DCTy) 2214 return; 2215 2216 ClassInfo NestedInfo = collectClassInfo(DCTy); 2217 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) 2218 Info.Members.push_back( 2219 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); 2220 } 2221 2222 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 2223 ClassInfo Info; 2224 // Add elements to structure type. 2225 DINodeArray Elements = Ty->getElements(); 2226 for (auto *Element : Elements) { 2227 // We assume that the frontend provides all members in source declaration 2228 // order, which is what MSVC does. 2229 if (!Element) 2230 continue; 2231 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 2232 Info.Methods[SP->getRawName()].push_back(SP); 2233 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 2234 if (DDTy->getTag() == dwarf::DW_TAG_member) { 2235 collectMemberInfo(Info, DDTy); 2236 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 2237 Info.Inheritance.push_back(DDTy); 2238 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type && 2239 DDTy->getName() == "__vtbl_ptr_type") { 2240 Info.VShapeTI = getTypeIndex(DDTy); 2241 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) { 2242 Info.NestedTypes.push_back(DDTy); 2243 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 2244 // Ignore friend members. It appears that MSVC emitted info about 2245 // friends in the past, but modern versions do not. 2246 } 2247 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) { 2248 Info.NestedTypes.push_back(Composite); 2249 } 2250 // Skip other unrecognized kinds of elements. 2251 } 2252 return Info; 2253 } 2254 2255 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) { 2256 // This routine is used by lowerTypeClass and lowerTypeUnion to determine 2257 // if a complete type should be emitted instead of a forward reference. 2258 return Ty->getName().empty() && Ty->getIdentifier().empty() && 2259 !Ty->isForwardDecl(); 2260 } 2261 2262 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 2263 // Emit the complete type for unnamed structs. C++ classes with methods 2264 // which have a circular reference back to the class type are expected to 2265 // be named by the front-end and should not be "unnamed". C unnamed 2266 // structs should not have circular references. 2267 if (shouldAlwaysEmitCompleteClassType(Ty)) { 2268 // If this unnamed complete type is already in the process of being defined 2269 // then the description of the type is malformed and cannot be emitted 2270 // into CodeView correctly so report a fatal error. 2271 auto I = CompleteTypeIndices.find(Ty); 2272 if (I != CompleteTypeIndices.end() && I->second == TypeIndex()) 2273 report_fatal_error("cannot debug circular reference to unnamed type"); 2274 return getCompleteTypeIndex(Ty); 2275 } 2276 2277 // First, construct the forward decl. Don't look into Ty to compute the 2278 // forward decl options, since it might not be available in all TUs. 2279 TypeRecordKind Kind = getRecordKind(Ty); 2280 ClassOptions CO = 2281 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 2282 std::string FullName = getFullyQualifiedName(Ty); 2283 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0, 2284 FullName, Ty->getIdentifier()); 2285 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR); 2286 if (!Ty->isForwardDecl()) 2287 DeferredCompleteTypes.push_back(Ty); 2288 return FwdDeclTI; 2289 } 2290 2291 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 2292 // Construct the field list and complete type record. 2293 TypeRecordKind Kind = getRecordKind(Ty); 2294 ClassOptions CO = getCommonClassOptions(Ty); 2295 TypeIndex FieldTI; 2296 TypeIndex VShapeTI; 2297 unsigned FieldCount; 2298 bool ContainsNestedClass; 2299 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) = 2300 lowerRecordFieldList(Ty); 2301 2302 if (ContainsNestedClass) 2303 CO |= ClassOptions::ContainsNestedClass; 2304 2305 // MSVC appears to set this flag by searching any destructor or method with 2306 // FunctionOptions::Constructor among the emitted members. Clang AST has all 2307 // the members, however special member functions are not yet emitted into 2308 // debug information. For now checking a class's non-triviality seems enough. 2309 // FIXME: not true for a nested unnamed struct. 2310 if (isNonTrivial(Ty)) 2311 CO |= ClassOptions::HasConstructorOrDestructor; 2312 2313 std::string FullName = getFullyQualifiedName(Ty); 2314 2315 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 2316 2317 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI, 2318 SizeInBytes, FullName, Ty->getIdentifier()); 2319 TypeIndex ClassTI = TypeTable.writeLeafType(CR); 2320 2321 addUDTSrcLine(Ty, ClassTI); 2322 2323 addToUDTs(Ty); 2324 2325 return ClassTI; 2326 } 2327 2328 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 2329 // Emit the complete type for unnamed unions. 2330 if (shouldAlwaysEmitCompleteClassType(Ty)) 2331 return getCompleteTypeIndex(Ty); 2332 2333 ClassOptions CO = 2334 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 2335 std::string FullName = getFullyQualifiedName(Ty); 2336 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier()); 2337 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR); 2338 if (!Ty->isForwardDecl()) 2339 DeferredCompleteTypes.push_back(Ty); 2340 return FwdDeclTI; 2341 } 2342 2343 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 2344 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty); 2345 TypeIndex FieldTI; 2346 unsigned FieldCount; 2347 bool ContainsNestedClass; 2348 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) = 2349 lowerRecordFieldList(Ty); 2350 2351 if (ContainsNestedClass) 2352 CO |= ClassOptions::ContainsNestedClass; 2353 2354 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 2355 std::string FullName = getFullyQualifiedName(Ty); 2356 2357 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName, 2358 Ty->getIdentifier()); 2359 TypeIndex UnionTI = TypeTable.writeLeafType(UR); 2360 2361 addUDTSrcLine(Ty, UnionTI); 2362 2363 addToUDTs(Ty); 2364 2365 return UnionTI; 2366 } 2367 2368 std::tuple<TypeIndex, TypeIndex, unsigned, bool> 2369 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 2370 // Manually count members. MSVC appears to count everything that generates a 2371 // field list record. Each individual overload in a method overload group 2372 // contributes to this count, even though the overload group is a single field 2373 // list record. 2374 unsigned MemberCount = 0; 2375 ClassInfo Info = collectClassInfo(Ty); 2376 ContinuationRecordBuilder ContinuationBuilder; 2377 ContinuationBuilder.begin(ContinuationRecordKind::FieldList); 2378 2379 // Create base classes. 2380 for (const DIDerivedType *I : Info.Inheritance) { 2381 if (I->getFlags() & DINode::FlagVirtual) { 2382 // Virtual base. 2383 unsigned VBPtrOffset = I->getVBPtrOffset(); 2384 // FIXME: Despite the accessor name, the offset is really in bytes. 2385 unsigned VBTableIndex = I->getOffsetInBits() / 4; 2386 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase 2387 ? TypeRecordKind::IndirectVirtualBaseClass 2388 : TypeRecordKind::VirtualBaseClass; 2389 VirtualBaseClassRecord VBCR( 2390 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()), 2391 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, 2392 VBTableIndex); 2393 2394 ContinuationBuilder.writeMemberType(VBCR); 2395 MemberCount++; 2396 } else { 2397 assert(I->getOffsetInBits() % 8 == 0 && 2398 "bases must be on byte boundaries"); 2399 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()), 2400 getTypeIndex(I->getBaseType()), 2401 I->getOffsetInBits() / 8); 2402 ContinuationBuilder.writeMemberType(BCR); 2403 MemberCount++; 2404 } 2405 } 2406 2407 // Create members. 2408 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 2409 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 2410 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 2411 StringRef MemberName = Member->getName(); 2412 MemberAccess Access = 2413 translateAccessFlags(Ty->getTag(), Member->getFlags()); 2414 2415 if (Member->isStaticMember()) { 2416 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName); 2417 ContinuationBuilder.writeMemberType(SDMR); 2418 MemberCount++; 2419 continue; 2420 } 2421 2422 // Virtual function pointer member. 2423 if ((Member->getFlags() & DINode::FlagArtificial) && 2424 Member->getName().startswith("_vptr$")) { 2425 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType())); 2426 ContinuationBuilder.writeMemberType(VFPR); 2427 MemberCount++; 2428 continue; 2429 } 2430 2431 // Data member. 2432 uint64_t MemberOffsetInBits = 2433 Member->getOffsetInBits() + MemberInfo.BaseOffset; 2434 if (Member->isBitField()) { 2435 uint64_t StartBitOffset = MemberOffsetInBits; 2436 if (const auto *CI = 2437 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { 2438 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset; 2439 } 2440 StartBitOffset -= MemberOffsetInBits; 2441 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(), 2442 StartBitOffset); 2443 MemberBaseType = TypeTable.writeLeafType(BFR); 2444 } 2445 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; 2446 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes, 2447 MemberName); 2448 ContinuationBuilder.writeMemberType(DMR); 2449 MemberCount++; 2450 } 2451 2452 // Create methods 2453 for (auto &MethodItr : Info.Methods) { 2454 StringRef Name = MethodItr.first->getString(); 2455 2456 std::vector<OneMethodRecord> Methods; 2457 for (const DISubprogram *SP : MethodItr.second) { 2458 TypeIndex MethodType = getMemberFunctionType(SP, Ty); 2459 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; 2460 2461 unsigned VFTableOffset = -1; 2462 if (Introduced) 2463 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 2464 2465 Methods.push_back(OneMethodRecord( 2466 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()), 2467 translateMethodKindFlags(SP, Introduced), 2468 translateMethodOptionFlags(SP), VFTableOffset, Name)); 2469 MemberCount++; 2470 } 2471 assert(!Methods.empty() && "Empty methods map entry"); 2472 if (Methods.size() == 1) 2473 ContinuationBuilder.writeMemberType(Methods[0]); 2474 else { 2475 // FIXME: Make this use its own ContinuationBuilder so that 2476 // MethodOverloadList can be split correctly. 2477 MethodOverloadListRecord MOLR(Methods); 2478 TypeIndex MethodList = TypeTable.writeLeafType(MOLR); 2479 2480 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name); 2481 ContinuationBuilder.writeMemberType(OMR); 2482 } 2483 } 2484 2485 // Create nested classes. 2486 for (const DIType *Nested : Info.NestedTypes) { 2487 NestedTypeRecord R(getTypeIndex(Nested), Nested->getName()); 2488 ContinuationBuilder.writeMemberType(R); 2489 MemberCount++; 2490 } 2491 2492 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder); 2493 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount, 2494 !Info.NestedTypes.empty()); 2495 } 2496 2497 TypeIndex CodeViewDebug::getVBPTypeIndex() { 2498 if (!VBPType.getIndex()) { 2499 // Make a 'const int *' type. 2500 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); 2501 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR); 2502 2503 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 2504 : PointerKind::Near32; 2505 PointerMode PM = PointerMode::Pointer; 2506 PointerOptions PO = PointerOptions::None; 2507 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); 2508 VBPType = TypeTable.writeLeafType(PR); 2509 } 2510 2511 return VBPType; 2512 } 2513 2514 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) { 2515 // The null DIType is the void type. Don't try to hash it. 2516 if (!Ty) 2517 return TypeIndex::Void(); 2518 2519 // Check if we've already translated this type. Don't try to do a 2520 // get-or-create style insertion that caches the hash lookup across the 2521 // lowerType call. It will update the TypeIndices map. 2522 auto I = TypeIndices.find({Ty, ClassTy}); 2523 if (I != TypeIndices.end()) 2524 return I->second; 2525 2526 TypeLoweringScope S(*this); 2527 TypeIndex TI = lowerType(Ty, ClassTy); 2528 return recordTypeIndexForDINode(Ty, TI, ClassTy); 2529 } 2530 2531 codeview::TypeIndex 2532 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy, 2533 const DISubroutineType *SubroutineTy) { 2534 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type && 2535 "this type must be a pointer type"); 2536 2537 PointerOptions Options = PointerOptions::None; 2538 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference) 2539 Options = PointerOptions::LValueRefThisPointer; 2540 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference) 2541 Options = PointerOptions::RValueRefThisPointer; 2542 2543 // Check if we've already translated this type. If there is no ref qualifier 2544 // on the function then we look up this pointer type with no associated class 2545 // so that the TypeIndex for the this pointer can be shared with the type 2546 // index for other pointers to this class type. If there is a ref qualifier 2547 // then we lookup the pointer using the subroutine as the parent type. 2548 auto I = TypeIndices.find({PtrTy, SubroutineTy}); 2549 if (I != TypeIndices.end()) 2550 return I->second; 2551 2552 TypeLoweringScope S(*this); 2553 TypeIndex TI = lowerTypePointer(PtrTy, Options); 2554 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy); 2555 } 2556 2557 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) { 2558 PointerRecord PR(getTypeIndex(Ty), 2559 getPointerSizeInBytes() == 8 ? PointerKind::Near64 2560 : PointerKind::Near32, 2561 PointerMode::LValueReference, PointerOptions::None, 2562 Ty->getSizeInBits() / 8); 2563 return TypeTable.writeLeafType(PR); 2564 } 2565 2566 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) { 2567 // The null DIType is the void type. Don't try to hash it. 2568 if (!Ty) 2569 return TypeIndex::Void(); 2570 2571 // Look through typedefs when getting the complete type index. Call 2572 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are 2573 // emitted only once. 2574 if (Ty->getTag() == dwarf::DW_TAG_typedef) 2575 (void)getTypeIndex(Ty); 2576 while (Ty->getTag() == dwarf::DW_TAG_typedef) 2577 Ty = cast<DIDerivedType>(Ty)->getBaseType(); 2578 2579 // If this is a non-record type, the complete type index is the same as the 2580 // normal type index. Just call getTypeIndex. 2581 switch (Ty->getTag()) { 2582 case dwarf::DW_TAG_class_type: 2583 case dwarf::DW_TAG_structure_type: 2584 case dwarf::DW_TAG_union_type: 2585 break; 2586 default: 2587 return getTypeIndex(Ty); 2588 } 2589 2590 const auto *CTy = cast<DICompositeType>(Ty); 2591 2592 TypeLoweringScope S(*this); 2593 2594 // Make sure the forward declaration is emitted first. It's unclear if this 2595 // is necessary, but MSVC does it, and we should follow suit until we can show 2596 // otherwise. 2597 // We only emit a forward declaration for named types. 2598 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) { 2599 TypeIndex FwdDeclTI = getTypeIndex(CTy); 2600 2601 // Just use the forward decl if we don't have complete type info. This 2602 // might happen if the frontend is using modules and expects the complete 2603 // definition to be emitted elsewhere. 2604 if (CTy->isForwardDecl()) 2605 return FwdDeclTI; 2606 } 2607 2608 // Check if we've already translated the complete record type. 2609 // Insert the type with a null TypeIndex to signify that the type is currently 2610 // being lowered. 2611 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 2612 if (!InsertResult.second) 2613 return InsertResult.first->second; 2614 2615 TypeIndex TI; 2616 switch (CTy->getTag()) { 2617 case dwarf::DW_TAG_class_type: 2618 case dwarf::DW_TAG_structure_type: 2619 TI = lowerCompleteTypeClass(CTy); 2620 break; 2621 case dwarf::DW_TAG_union_type: 2622 TI = lowerCompleteTypeUnion(CTy); 2623 break; 2624 default: 2625 llvm_unreachable("not a record"); 2626 } 2627 2628 // Update the type index associated with this CompositeType. This cannot 2629 // use the 'InsertResult' iterator above because it is potentially 2630 // invalidated by map insertions which can occur while lowering the class 2631 // type above. 2632 CompleteTypeIndices[CTy] = TI; 2633 return TI; 2634 } 2635 2636 /// Emit all the deferred complete record types. Try to do this in FIFO order, 2637 /// and do this until fixpoint, as each complete record type typically 2638 /// references 2639 /// many other record types. 2640 void CodeViewDebug::emitDeferredCompleteTypes() { 2641 SmallVector<const DICompositeType *, 4> TypesToEmit; 2642 while (!DeferredCompleteTypes.empty()) { 2643 std::swap(DeferredCompleteTypes, TypesToEmit); 2644 for (const DICompositeType *RecordTy : TypesToEmit) 2645 getCompleteTypeIndex(RecordTy); 2646 TypesToEmit.clear(); 2647 } 2648 } 2649 2650 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI, 2651 ArrayRef<LocalVariable> Locals) { 2652 // Get the sorted list of parameters and emit them first. 2653 SmallVector<const LocalVariable *, 6> Params; 2654 for (const LocalVariable &L : Locals) 2655 if (L.DIVar->isParameter()) 2656 Params.push_back(&L); 2657 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) { 2658 return L->DIVar->getArg() < R->DIVar->getArg(); 2659 }); 2660 for (const LocalVariable *L : Params) 2661 emitLocalVariable(FI, *L); 2662 2663 // Next emit all non-parameters in the order that we found them. 2664 for (const LocalVariable &L : Locals) 2665 if (!L.DIVar->isParameter()) 2666 emitLocalVariable(FI, L); 2667 } 2668 2669 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI, 2670 const LocalVariable &Var) { 2671 // LocalSym record, see SymbolRecord.h for more info. 2672 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL); 2673 2674 LocalSymFlags Flags = LocalSymFlags::None; 2675 if (Var.DIVar->isParameter()) 2676 Flags |= LocalSymFlags::IsParameter; 2677 if (Var.DefRanges.empty()) 2678 Flags |= LocalSymFlags::IsOptimizedOut; 2679 2680 OS.AddComment("TypeIndex"); 2681 TypeIndex TI = Var.UseReferenceType 2682 ? getTypeIndexForReferenceTo(Var.DIVar->getType()) 2683 : getCompleteTypeIndex(Var.DIVar->getType()); 2684 OS.emitInt32(TI.getIndex()); 2685 OS.AddComment("Flags"); 2686 OS.emitInt16(static_cast<uint16_t>(Flags)); 2687 // Truncate the name so we won't overflow the record length field. 2688 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 2689 endSymbolRecord(LocalEnd); 2690 2691 // Calculate the on disk prefix of the appropriate def range record. The 2692 // records and on disk formats are described in SymbolRecords.h. BytePrefix 2693 // should be big enough to hold all forms without memory allocation. 2694 SmallString<20> BytePrefix; 2695 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 2696 BytePrefix.clear(); 2697 if (DefRange.InMemory) { 2698 int Offset = DefRange.DataOffset; 2699 unsigned Reg = DefRange.CVRegister; 2700 2701 // 32-bit x86 call sequences often use PUSH instructions, which disrupt 2702 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0, 2703 // instead. In frames without stack realignment, $T0 will be the CFA. 2704 if (RegisterId(Reg) == RegisterId::ESP) { 2705 Reg = unsigned(RegisterId::VFRAME); 2706 Offset += FI.OffsetAdjustment; 2707 } 2708 2709 // If we can use the chosen frame pointer for the frame and this isn't a 2710 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record. 2711 // Otherwise, use S_DEFRANGE_REGISTER_REL. 2712 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU); 2713 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None && 2714 (bool(Flags & LocalSymFlags::IsParameter) 2715 ? (EncFP == FI.EncodedParamFramePtrReg) 2716 : (EncFP == FI.EncodedLocalFramePtrReg))) { 2717 DefRangeFramePointerRelHeader DRHdr; 2718 DRHdr.Offset = Offset; 2719 OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); 2720 } else { 2721 uint16_t RegRelFlags = 0; 2722 if (DefRange.IsSubfield) { 2723 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag | 2724 (DefRange.StructOffset 2725 << DefRangeRegisterRelSym::OffsetInParentShift); 2726 } 2727 DefRangeRegisterRelHeader DRHdr; 2728 DRHdr.Register = Reg; 2729 DRHdr.Flags = RegRelFlags; 2730 DRHdr.BasePointerOffset = Offset; 2731 OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); 2732 } 2733 } else { 2734 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 2735 if (DefRange.IsSubfield) { 2736 DefRangeSubfieldRegisterHeader DRHdr; 2737 DRHdr.Register = DefRange.CVRegister; 2738 DRHdr.MayHaveNoName = 0; 2739 DRHdr.OffsetInParent = DefRange.StructOffset; 2740 OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); 2741 } else { 2742 DefRangeRegisterHeader DRHdr; 2743 DRHdr.Register = DefRange.CVRegister; 2744 DRHdr.MayHaveNoName = 0; 2745 OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); 2746 } 2747 } 2748 } 2749 } 2750 2751 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks, 2752 const FunctionInfo& FI) { 2753 for (LexicalBlock *Block : Blocks) 2754 emitLexicalBlock(*Block, FI); 2755 } 2756 2757 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a 2758 /// lexical block scope. 2759 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block, 2760 const FunctionInfo& FI) { 2761 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32); 2762 OS.AddComment("PtrParent"); 2763 OS.emitInt32(0); // PtrParent 2764 OS.AddComment("PtrEnd"); 2765 OS.emitInt32(0); // PtrEnd 2766 OS.AddComment("Code size"); 2767 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size 2768 OS.AddComment("Function section relative address"); 2769 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset 2770 OS.AddComment("Function section index"); 2771 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol 2772 OS.AddComment("Lexical block name"); 2773 emitNullTerminatedSymbolName(OS, Block.Name); // Name 2774 endSymbolRecord(RecordEnd); 2775 2776 // Emit variables local to this lexical block. 2777 emitLocalVariableList(FI, Block.Locals); 2778 emitGlobalVariableList(Block.Globals); 2779 2780 // Emit lexical blocks contained within this block. 2781 emitLexicalBlockList(Block.Children, FI); 2782 2783 // Close the lexical block scope. 2784 emitEndSymbolRecord(SymbolKind::S_END); 2785 } 2786 2787 /// Convenience routine for collecting lexical block information for a list 2788 /// of lexical scopes. 2789 void CodeViewDebug::collectLexicalBlockInfo( 2790 SmallVectorImpl<LexicalScope *> &Scopes, 2791 SmallVectorImpl<LexicalBlock *> &Blocks, 2792 SmallVectorImpl<LocalVariable> &Locals, 2793 SmallVectorImpl<CVGlobalVariable> &Globals) { 2794 for (LexicalScope *Scope : Scopes) 2795 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals); 2796 } 2797 2798 /// Populate the lexical blocks and local variable lists of the parent with 2799 /// information about the specified lexical scope. 2800 void CodeViewDebug::collectLexicalBlockInfo( 2801 LexicalScope &Scope, 2802 SmallVectorImpl<LexicalBlock *> &ParentBlocks, 2803 SmallVectorImpl<LocalVariable> &ParentLocals, 2804 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) { 2805 if (Scope.isAbstractScope()) 2806 return; 2807 2808 // Gather information about the lexical scope including local variables, 2809 // global variables, and address ranges. 2810 bool IgnoreScope = false; 2811 auto LI = ScopeVariables.find(&Scope); 2812 SmallVectorImpl<LocalVariable> *Locals = 2813 LI != ScopeVariables.end() ? &LI->second : nullptr; 2814 auto GI = ScopeGlobals.find(Scope.getScopeNode()); 2815 SmallVectorImpl<CVGlobalVariable> *Globals = 2816 GI != ScopeGlobals.end() ? GI->second.get() : nullptr; 2817 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode()); 2818 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges(); 2819 2820 // Ignore lexical scopes which do not contain variables. 2821 if (!Locals && !Globals) 2822 IgnoreScope = true; 2823 2824 // Ignore lexical scopes which are not lexical blocks. 2825 if (!DILB) 2826 IgnoreScope = true; 2827 2828 // Ignore scopes which have too many address ranges to represent in the 2829 // current CodeView format or do not have a valid address range. 2830 // 2831 // For lexical scopes with multiple address ranges you may be tempted to 2832 // construct a single range covering every instruction where the block is 2833 // live and everything in between. Unfortunately, Visual Studio only 2834 // displays variables from the first matching lexical block scope. If the 2835 // first lexical block contains exception handling code or cold code which 2836 // is moved to the bottom of the routine creating a single range covering 2837 // nearly the entire routine, then it will hide all other lexical blocks 2838 // and the variables they contain. 2839 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) 2840 IgnoreScope = true; 2841 2842 if (IgnoreScope) { 2843 // This scope can be safely ignored and eliminating it will reduce the 2844 // size of the debug information. Be sure to collect any variable and scope 2845 // information from the this scope or any of its children and collapse them 2846 // into the parent scope. 2847 if (Locals) 2848 ParentLocals.append(Locals->begin(), Locals->end()); 2849 if (Globals) 2850 ParentGlobals.append(Globals->begin(), Globals->end()); 2851 collectLexicalBlockInfo(Scope.getChildren(), 2852 ParentBlocks, 2853 ParentLocals, 2854 ParentGlobals); 2855 return; 2856 } 2857 2858 // Create a new CodeView lexical block for this lexical scope. If we've 2859 // seen this DILexicalBlock before then the scope tree is malformed and 2860 // we can handle this gracefully by not processing it a second time. 2861 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()}); 2862 if (!BlockInsertion.second) 2863 return; 2864 2865 // Create a lexical block containing the variables and collect the the 2866 // lexical block information for the children. 2867 const InsnRange &Range = Ranges.front(); 2868 assert(Range.first && Range.second); 2869 LexicalBlock &Block = BlockInsertion.first->second; 2870 Block.Begin = getLabelBeforeInsn(Range.first); 2871 Block.End = getLabelAfterInsn(Range.second); 2872 assert(Block.Begin && "missing label for scope begin"); 2873 assert(Block.End && "missing label for scope end"); 2874 Block.Name = DILB->getName(); 2875 if (Locals) 2876 Block.Locals = std::move(*Locals); 2877 if (Globals) 2878 Block.Globals = std::move(*Globals); 2879 ParentBlocks.push_back(&Block); 2880 collectLexicalBlockInfo(Scope.getChildren(), 2881 Block.Children, 2882 Block.Locals, 2883 Block.Globals); 2884 } 2885 2886 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) { 2887 const Function &GV = MF->getFunction(); 2888 assert(FnDebugInfo.count(&GV)); 2889 assert(CurFn == FnDebugInfo[&GV].get()); 2890 2891 collectVariableInfo(GV.getSubprogram()); 2892 2893 // Build the lexical block structure to emit for this routine. 2894 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope()) 2895 collectLexicalBlockInfo(*CFS, 2896 CurFn->ChildBlocks, 2897 CurFn->Locals, 2898 CurFn->Globals); 2899 2900 // Clear the scope and variable information from the map which will not be 2901 // valid after we have finished processing this routine. This also prepares 2902 // the map for the subsequent routine. 2903 ScopeVariables.clear(); 2904 2905 // Don't emit anything if we don't have any line tables. 2906 // Thunks are compiler-generated and probably won't have source correlation. 2907 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) { 2908 FnDebugInfo.erase(&GV); 2909 CurFn = nullptr; 2910 return; 2911 } 2912 2913 // Find heap alloc sites and add to list. 2914 for (const auto &MBB : *MF) { 2915 for (const auto &MI : MBB) { 2916 if (MDNode *MD = MI.getHeapAllocMarker()) { 2917 CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI), 2918 getLabelAfterInsn(&MI), 2919 dyn_cast<DIType>(MD))); 2920 } 2921 } 2922 } 2923 2924 CurFn->Annotations = MF->getCodeViewAnnotations(); 2925 2926 CurFn->End = Asm->getFunctionEnd(); 2927 2928 CurFn = nullptr; 2929 } 2930 2931 // Usable locations are valid with non-zero line numbers. A line number of zero 2932 // corresponds to optimized code that doesn't have a distinct source location. 2933 // In this case, we try to use the previous or next source location depending on 2934 // the context. 2935 static bool isUsableDebugLoc(DebugLoc DL) { 2936 return DL && DL.getLine() != 0; 2937 } 2938 2939 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 2940 DebugHandlerBase::beginInstruction(MI); 2941 2942 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue. 2943 if (!Asm || !CurFn || MI->isDebugInstr() || 2944 MI->getFlag(MachineInstr::FrameSetup)) 2945 return; 2946 2947 // If the first instruction of a new MBB has no location, find the first 2948 // instruction with a location and use that. 2949 DebugLoc DL = MI->getDebugLoc(); 2950 if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) { 2951 for (const auto &NextMI : *MI->getParent()) { 2952 if (NextMI.isDebugInstr()) 2953 continue; 2954 DL = NextMI.getDebugLoc(); 2955 if (isUsableDebugLoc(DL)) 2956 break; 2957 } 2958 // FIXME: Handle the case where the BB has no valid locations. This would 2959 // probably require doing a real dataflow analysis. 2960 } 2961 PrevInstBB = MI->getParent(); 2962 2963 // If we still don't have a debug location, don't record a location. 2964 if (!isUsableDebugLoc(DL)) 2965 return; 2966 2967 maybeRecordLocation(DL, Asm->MF); 2968 } 2969 2970 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) { 2971 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 2972 *EndLabel = MMI->getContext().createTempSymbol(); 2973 OS.emitInt32(unsigned(Kind)); 2974 OS.AddComment("Subsection size"); 2975 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 2976 OS.emitLabel(BeginLabel); 2977 return EndLabel; 2978 } 2979 2980 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 2981 OS.emitLabel(EndLabel); 2982 // Every subsection must be aligned to a 4-byte boundary. 2983 OS.emitValueToAlignment(4); 2984 } 2985 2986 static StringRef getSymbolName(SymbolKind SymKind) { 2987 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames()) 2988 if (EE.Value == SymKind) 2989 return EE.Name; 2990 return ""; 2991 } 2992 2993 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) { 2994 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 2995 *EndLabel = MMI->getContext().createTempSymbol(); 2996 OS.AddComment("Record length"); 2997 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); 2998 OS.emitLabel(BeginLabel); 2999 if (OS.isVerboseAsm()) 3000 OS.AddComment("Record kind: " + getSymbolName(SymKind)); 3001 OS.emitInt16(unsigned(SymKind)); 3002 return EndLabel; 3003 } 3004 3005 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) { 3006 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid 3007 // an extra copy of every symbol record in LLD. This increases object file 3008 // size by less than 1% in the clang build, and is compatible with the Visual 3009 // C++ linker. 3010 OS.emitValueToAlignment(4); 3011 OS.emitLabel(SymEnd); 3012 } 3013 3014 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) { 3015 OS.AddComment("Record length"); 3016 OS.emitInt16(2); 3017 if (OS.isVerboseAsm()) 3018 OS.AddComment("Record kind: " + getSymbolName(EndKind)); 3019 OS.emitInt16(uint16_t(EndKind)); // Record Kind 3020 } 3021 3022 void CodeViewDebug::emitDebugInfoForUDTs( 3023 const std::vector<std::pair<std::string, const DIType *>> &UDTs) { 3024 #ifndef NDEBUG 3025 size_t OriginalSize = UDTs.size(); 3026 #endif 3027 for (const auto &UDT : UDTs) { 3028 const DIType *T = UDT.second; 3029 assert(shouldEmitUdt(T)); 3030 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT); 3031 OS.AddComment("Type"); 3032 OS.emitInt32(getCompleteTypeIndex(T).getIndex()); 3033 assert(OriginalSize == UDTs.size() && 3034 "getCompleteTypeIndex found new UDTs!"); 3035 emitNullTerminatedSymbolName(OS, UDT.first); 3036 endSymbolRecord(UDTRecordEnd); 3037 } 3038 } 3039 3040 void CodeViewDebug::collectGlobalVariableInfo() { 3041 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *> 3042 GlobalMap; 3043 for (const GlobalVariable &GV : MMI->getModule()->globals()) { 3044 SmallVector<DIGlobalVariableExpression *, 1> GVEs; 3045 GV.getDebugInfo(GVEs); 3046 for (const auto *GVE : GVEs) 3047 GlobalMap[GVE] = &GV; 3048 } 3049 3050 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 3051 for (const MDNode *Node : CUs->operands()) { 3052 const auto *CU = cast<DICompileUnit>(Node); 3053 for (const auto *GVE : CU->getGlobalVariables()) { 3054 const DIGlobalVariable *DIGV = GVE->getVariable(); 3055 const DIExpression *DIE = GVE->getExpression(); 3056 3057 // Emit constant global variables in a global symbol section. 3058 if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) { 3059 CVGlobalVariable CVGV = {DIGV, DIE}; 3060 GlobalVariables.emplace_back(std::move(CVGV)); 3061 } 3062 3063 const auto *GV = GlobalMap.lookup(GVE); 3064 if (!GV || GV->isDeclarationForLinker()) 3065 continue; 3066 3067 DIScope *Scope = DIGV->getScope(); 3068 SmallVector<CVGlobalVariable, 1> *VariableList; 3069 if (Scope && isa<DILocalScope>(Scope)) { 3070 // Locate a global variable list for this scope, creating one if 3071 // necessary. 3072 auto Insertion = ScopeGlobals.insert( 3073 {Scope, std::unique_ptr<GlobalVariableList>()}); 3074 if (Insertion.second) 3075 Insertion.first->second = std::make_unique<GlobalVariableList>(); 3076 VariableList = Insertion.first->second.get(); 3077 } else if (GV->hasComdat()) 3078 // Emit this global variable into a COMDAT section. 3079 VariableList = &ComdatVariables; 3080 else 3081 // Emit this global variable in a single global symbol section. 3082 VariableList = &GlobalVariables; 3083 CVGlobalVariable CVGV = {DIGV, GV}; 3084 VariableList->emplace_back(std::move(CVGV)); 3085 } 3086 } 3087 } 3088 3089 void CodeViewDebug::emitDebugInfoForGlobals() { 3090 // First, emit all globals that are not in a comdat in a single symbol 3091 // substream. MSVC doesn't like it if the substream is empty, so only open 3092 // it if we have at least one global to emit. 3093 switchToDebugSectionForSymbol(nullptr); 3094 if (!GlobalVariables.empty()) { 3095 OS.AddComment("Symbol subsection for globals"); 3096 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); 3097 emitGlobalVariableList(GlobalVariables); 3098 endCVSubsection(EndLabel); 3099 } 3100 3101 // Second, emit each global that is in a comdat into its own .debug$S 3102 // section along with its own symbol substream. 3103 for (const CVGlobalVariable &CVGV : ComdatVariables) { 3104 const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>(); 3105 MCSymbol *GVSym = Asm->getSymbol(GV); 3106 OS.AddComment("Symbol subsection for " + 3107 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName()))); 3108 switchToDebugSectionForSymbol(GVSym); 3109 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); 3110 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3111 emitDebugInfoForGlobal(CVGV); 3112 endCVSubsection(EndLabel); 3113 } 3114 } 3115 3116 void CodeViewDebug::emitDebugInfoForRetainedTypes() { 3117 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 3118 for (const MDNode *Node : CUs->operands()) { 3119 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { 3120 if (DIType *RT = dyn_cast<DIType>(Ty)) { 3121 getTypeIndex(RT); 3122 // FIXME: Add to global/local DTU list. 3123 } 3124 } 3125 } 3126 } 3127 3128 // Emit each global variable in the specified array. 3129 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) { 3130 for (const CVGlobalVariable &CVGV : Globals) { 3131 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 3132 emitDebugInfoForGlobal(CVGV); 3133 } 3134 } 3135 3136 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) { 3137 const DIGlobalVariable *DIGV = CVGV.DIGV; 3138 3139 const DIScope *Scope = DIGV->getScope(); 3140 // For static data members, get the scope from the declaration. 3141 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>( 3142 DIGV->getRawStaticDataMemberDeclaration())) 3143 Scope = MemberDecl->getScope(); 3144 std::string QualifiedName = getFullyQualifiedName(Scope, DIGV->getName()); 3145 3146 if (const GlobalVariable *GV = 3147 CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) { 3148 // DataSym record, see SymbolRecord.h for more info. Thread local data 3149 // happens to have the same format as global data. 3150 MCSymbol *GVSym = Asm->getSymbol(GV); 3151 SymbolKind DataSym = GV->isThreadLocal() 3152 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32 3153 : SymbolKind::S_GTHREAD32) 3154 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32 3155 : SymbolKind::S_GDATA32); 3156 MCSymbol *DataEnd = beginSymbolRecord(DataSym); 3157 OS.AddComment("Type"); 3158 OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex()); 3159 OS.AddComment("DataOffset"); 3160 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0); 3161 OS.AddComment("Segment"); 3162 OS.EmitCOFFSectionIndex(GVSym); 3163 OS.AddComment("Name"); 3164 const unsigned LengthOfDataRecord = 12; 3165 emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord); 3166 endSymbolRecord(DataEnd); 3167 } else { 3168 const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>(); 3169 assert(DIE->isConstant() && 3170 "Global constant variables must contain a constant expression."); 3171 uint64_t Val = DIE->getElement(1); 3172 3173 MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT); 3174 OS.AddComment("Type"); 3175 OS.emitInt32(getTypeIndex(DIGV->getType()).getIndex()); 3176 OS.AddComment("Value"); 3177 3178 // Encoded integers shouldn't need more than 10 bytes. 3179 uint8_t data[10]; 3180 BinaryStreamWriter Writer(data, llvm::support::endianness::little); 3181 CodeViewRecordIO IO(Writer); 3182 cantFail(IO.mapEncodedInteger(Val)); 3183 StringRef SRef((char *)data, Writer.getOffset()); 3184 OS.emitBinaryData(SRef); 3185 3186 OS.AddComment("Name"); 3187 emitNullTerminatedSymbolName(OS, QualifiedName); 3188 endSymbolRecord(SConstantEnd); 3189 } 3190 } 3191