1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===// 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 #include "llvm/MC/MCDwarf.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/DenseMap.h" 12 #include "llvm/ADT/Hashing.h" 13 #include "llvm/ADT/STLExtras.h" 14 #include "llvm/ADT/SmallString.h" 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/StringRef.h" 17 #include "llvm/ADT/Twine.h" 18 #include "llvm/BinaryFormat/Dwarf.h" 19 #include "llvm/Config/config.h" 20 #include "llvm/MC/MCAsmInfo.h" 21 #include "llvm/MC/MCContext.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCObjectFileInfo.h" 24 #include "llvm/MC/MCObjectStreamer.h" 25 #include "llvm/MC/MCRegisterInfo.h" 26 #include "llvm/MC/MCSection.h" 27 #include "llvm/MC/MCStreamer.h" 28 #include "llvm/MC/MCSymbol.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/Endian.h" 31 #include "llvm/Support/EndianStream.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/LEB128.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/Path.h" 36 #include "llvm/Support/SourceMgr.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <cassert> 39 #include <cstdint> 40 #include <optional> 41 #include <string> 42 #include <utility> 43 #include <vector> 44 45 using namespace llvm; 46 47 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) { 48 MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start"); 49 MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end"); 50 auto DwarfFormat = S.getContext().getDwarfFormat(); 51 if (DwarfFormat == dwarf::DWARF64) { 52 S.AddComment("DWARF64 mark"); 53 S.emitInt32(dwarf::DW_LENGTH_DWARF64); 54 } 55 S.AddComment("Length"); 56 S.emitAbsoluteSymbolDiff(End, Start, 57 dwarf::getDwarfOffsetByteSize(DwarfFormat)); 58 S.emitLabel(Start); 59 S.AddComment("Version"); 60 S.emitInt16(S.getContext().getDwarfVersion()); 61 S.AddComment("Address size"); 62 S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize()); 63 S.AddComment("Segment selector size"); 64 S.emitInt8(0); 65 return End; 66 } 67 68 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) { 69 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment(); 70 if (MinInsnLength == 1) 71 return AddrDelta; 72 if (AddrDelta % MinInsnLength != 0) { 73 // TODO: report this error, but really only once. 74 ; 75 } 76 return AddrDelta / MinInsnLength; 77 } 78 79 MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) { 80 UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections(); 81 if (UseRelocs) 82 LineStrLabel = 83 Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol(); 84 } 85 86 // 87 // This is called when an instruction is assembled into the specified section 88 // and if there is information from the last .loc directive that has yet to have 89 // a line entry made for it is made. 90 // 91 void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) { 92 if (!MCOS->getContext().getDwarfLocSeen()) 93 return; 94 95 // Create a symbol at in the current section for use in the line entry. 96 MCSymbol *LineSym = MCOS->getContext().createTempSymbol(); 97 // Set the value of the symbol to use for the MCDwarfLineEntry. 98 MCOS->emitLabel(LineSym); 99 100 // Get the current .loc info saved in the context. 101 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); 102 103 // Create a (local) line entry with the symbol and the current .loc info. 104 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc); 105 106 // clear DwarfLocSeen saying the current .loc info is now used. 107 MCOS->getContext().clearDwarfLocSeen(); 108 109 // Add the line entry to this section's entries. 110 MCOS->getContext() 111 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID()) 112 .getMCLineSections() 113 .addLineEntry(LineEntry, Section); 114 } 115 116 // 117 // This helper routine returns an expression of End - Start - IntVal . 118 // 119 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx, 120 const MCSymbol &Start, 121 const MCSymbol &End, 122 int IntVal) { 123 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 124 const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx); 125 const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx); 126 const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx); 127 const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx); 128 const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx); 129 return Res3; 130 } 131 132 // 133 // This helper routine returns an expression of Start + IntVal . 134 // 135 static inline const MCExpr * 136 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) { 137 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 138 const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx); 139 const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx); 140 const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx); 141 return Res; 142 } 143 144 void MCLineSection::addEndEntry(MCSymbol *EndLabel) { 145 auto *Sec = &EndLabel->getSection(); 146 // The line table may be empty, which we should skip adding an end entry. 147 // There are two cases: 148 // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in 149 // place instead of adding a line entry if the target has 150 // usesDwarfFileAndLocDirectives. 151 // (2) MCObjectStreamer - if a function has incomplete debug info where 152 // instructions don't have DILocations, the line entries are missing. 153 auto I = MCLineDivisions.find(Sec); 154 if (I != MCLineDivisions.end()) { 155 auto &Entries = I->second; 156 auto EndEntry = Entries.back(); 157 EndEntry.setEndLabel(EndLabel); 158 Entries.push_back(EndEntry); 159 } 160 } 161 162 // 163 // This emits the Dwarf line table for the specified section from the entries 164 // in the LineSection. 165 // 166 void MCDwarfLineTable::emitOne( 167 MCStreamer *MCOS, MCSection *Section, 168 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) { 169 170 unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator; 171 MCSymbol *LastLabel; 172 auto init = [&]() { 173 FileNum = 1; 174 LastLine = 1; 175 Column = 0; 176 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 177 Isa = 0; 178 Discriminator = 0; 179 LastLabel = nullptr; 180 }; 181 init(); 182 183 // Loop through each MCDwarfLineEntry and encode the dwarf line number table. 184 bool EndEntryEmitted = false; 185 for (const MCDwarfLineEntry &LineEntry : LineEntries) { 186 MCSymbol *Label = LineEntry.getLabel(); 187 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo(); 188 if (LineEntry.IsEndEntry) { 189 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label, 190 asmInfo->getCodePointerSize()); 191 init(); 192 EndEntryEmitted = true; 193 continue; 194 } 195 196 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine; 197 198 if (FileNum != LineEntry.getFileNum()) { 199 FileNum = LineEntry.getFileNum(); 200 MCOS->emitInt8(dwarf::DW_LNS_set_file); 201 MCOS->emitULEB128IntValue(FileNum); 202 } 203 if (Column != LineEntry.getColumn()) { 204 Column = LineEntry.getColumn(); 205 MCOS->emitInt8(dwarf::DW_LNS_set_column); 206 MCOS->emitULEB128IntValue(Column); 207 } 208 if (Discriminator != LineEntry.getDiscriminator() && 209 MCOS->getContext().getDwarfVersion() >= 4) { 210 Discriminator = LineEntry.getDiscriminator(); 211 unsigned Size = getULEB128Size(Discriminator); 212 MCOS->emitInt8(dwarf::DW_LNS_extended_op); 213 MCOS->emitULEB128IntValue(Size + 1); 214 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator); 215 MCOS->emitULEB128IntValue(Discriminator); 216 } 217 if (Isa != LineEntry.getIsa()) { 218 Isa = LineEntry.getIsa(); 219 MCOS->emitInt8(dwarf::DW_LNS_set_isa); 220 MCOS->emitULEB128IntValue(Isa); 221 } 222 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 223 Flags = LineEntry.getFlags(); 224 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt); 225 } 226 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK) 227 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block); 228 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END) 229 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end); 230 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 231 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin); 232 233 // At this point we want to emit/create the sequence to encode the delta in 234 // line numbers and the increment of the address from the previous Label 235 // and the current Label. 236 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 237 asmInfo->getCodePointerSize()); 238 239 Discriminator = 0; 240 LastLine = LineEntry.getLine(); 241 LastLabel = Label; 242 } 243 244 // Generate DWARF line end entry. 245 // We do not need this for DwarfDebug that explicitly terminates the line 246 // table using ranges whenever CU or section changes. However, the MC path 247 // does not track ranges nor terminate the line table. In that case, 248 // conservatively use the section end symbol to end the line table. 249 if (!EndEntryEmitted) 250 MCOS->emitDwarfLineEndEntry(Section, LastLabel); 251 } 252 253 // 254 // This emits the Dwarf file and the line tables. 255 // 256 void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) { 257 MCContext &context = MCOS->getContext(); 258 259 auto &LineTables = context.getMCDwarfLineTables(); 260 261 // Bail out early so we don't switch to the debug_line section needlessly and 262 // in doing so create an unnecessary (if empty) section. 263 if (LineTables.empty()) 264 return; 265 266 // In a v5 non-split line table, put the strings in a separate section. 267 std::optional<MCDwarfLineStr> LineStr; 268 if (context.getDwarfVersion() >= 5) 269 LineStr.emplace(context); 270 271 // Switch to the section where the table will be emitted into. 272 MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection()); 273 274 // Handle the rest of the Compile Units. 275 for (const auto &CUIDTablePair : LineTables) { 276 CUIDTablePair.second.emitCU(MCOS, Params, LineStr); 277 } 278 279 if (LineStr) 280 LineStr->emitSection(MCOS); 281 } 282 283 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params, 284 MCSection *Section) const { 285 if (!HasSplitLineTable) 286 return; 287 std::optional<MCDwarfLineStr> NoLineStr(std::nullopt); 288 MCOS.switchSection(Section); 289 MCOS.emitLabel(Header.Emit(&MCOS, Params, std::nullopt, NoLineStr).second); 290 } 291 292 std::pair<MCSymbol *, MCSymbol *> 293 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 294 std::optional<MCDwarfLineStr> &LineStr) const { 295 static const char StandardOpcodeLengths[] = { 296 0, // length of DW_LNS_copy 297 1, // length of DW_LNS_advance_pc 298 1, // length of DW_LNS_advance_line 299 1, // length of DW_LNS_set_file 300 1, // length of DW_LNS_set_column 301 0, // length of DW_LNS_negate_stmt 302 0, // length of DW_LNS_set_basic_block 303 0, // length of DW_LNS_const_add_pc 304 1, // length of DW_LNS_fixed_advance_pc 305 0, // length of DW_LNS_set_prologue_end 306 0, // length of DW_LNS_set_epilogue_begin 307 1 // DW_LNS_set_isa 308 }; 309 assert(std::size(StandardOpcodeLengths) >= 310 (Params.DWARF2LineOpcodeBase - 1U)); 311 return Emit(MCOS, Params, 312 ArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1), 313 LineStr); 314 } 315 316 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) { 317 MCContext &Context = OS.getContext(); 318 assert(!isa<MCSymbolRefExpr>(Expr)); 319 if (Context.getAsmInfo()->hasAggressiveSymbolFolding()) 320 return Expr; 321 322 MCSymbol *ABS = Context.createTempSymbol(); 323 OS.emitAssignment(ABS, Expr); 324 return MCSymbolRefExpr::create(ABS, Context); 325 } 326 327 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) { 328 const MCExpr *ABS = forceExpAbs(OS, Value); 329 OS.emitValue(ABS, Size); 330 } 331 332 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) { 333 // Switch to the .debug_line_str section. 334 MCOS->switchSection( 335 MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection()); 336 SmallString<0> Data = getFinalizedData(); 337 MCOS->emitBinaryData(Data.str()); 338 } 339 340 SmallString<0> MCDwarfLineStr::getFinalizedData() { 341 // Emit the strings without perturbing the offsets we used. 342 if (!LineStrings.isFinalized()) 343 LineStrings.finalizeInOrder(); 344 SmallString<0> Data; 345 Data.resize(LineStrings.getSize()); 346 LineStrings.write((uint8_t *)Data.data()); 347 return Data; 348 } 349 350 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) { 351 int RefSize = 352 dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat()); 353 size_t Offset = LineStrings.add(Path); 354 if (UseRelocs) { 355 MCContext &Ctx = MCOS->getContext(); 356 MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize); 357 } else 358 MCOS->emitIntValue(Offset, RefSize); 359 } 360 361 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const { 362 // First the directory table. 363 for (auto &Dir : MCDwarfDirs) { 364 MCOS->emitBytes(Dir); // The DirectoryName, and... 365 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 366 } 367 MCOS->emitInt8(0); // Terminate the directory list. 368 369 // Second the file table. 370 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { 371 assert(!MCDwarfFiles[i].Name.empty()); 372 MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and... 373 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 374 MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number. 375 MCOS->emitInt8(0); // Last modification timestamp (always 0). 376 MCOS->emitInt8(0); // File size (always 0). 377 } 378 MCOS->emitInt8(0); // Terminate the file list. 379 } 380 381 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile, 382 bool EmitMD5, bool HasSource, 383 std::optional<MCDwarfLineStr> &LineStr) { 384 assert(!DwarfFile.Name.empty()); 385 if (LineStr) 386 LineStr->emitRef(MCOS, DwarfFile.Name); 387 else { 388 MCOS->emitBytes(DwarfFile.Name); // FileName and... 389 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 390 } 391 MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number. 392 if (EmitMD5) { 393 const MD5::MD5Result &Cksum = *DwarfFile.Checksum; 394 MCOS->emitBinaryData( 395 StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size())); 396 } 397 if (HasSource) { 398 if (LineStr) 399 LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef())); 400 else { 401 MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); // Source and... 402 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 403 } 404 } 405 } 406 407 void MCDwarfLineTableHeader::emitV5FileDirTables( 408 MCStreamer *MCOS, std::optional<MCDwarfLineStr> &LineStr) const { 409 // The directory format, which is just a list of the directory paths. In a 410 // non-split object, these are references to .debug_line_str; in a split 411 // object, they are inline strings. 412 MCOS->emitInt8(1); 413 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path); 414 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 415 : dwarf::DW_FORM_string); 416 MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1); 417 // Try not to emit an empty compilation directory. 418 SmallString<256> Dir; 419 StringRef CompDir = MCOS->getContext().getCompilationDir(); 420 if (!CompilationDir.empty()) { 421 Dir = CompilationDir; 422 MCOS->getContext().remapDebugPath(Dir); 423 CompDir = Dir.str(); 424 if (LineStr) 425 CompDir = LineStr->getSaver().save(CompDir); 426 } 427 if (LineStr) { 428 // Record path strings, emit references here. 429 LineStr->emitRef(MCOS, CompDir); 430 for (const auto &Dir : MCDwarfDirs) 431 LineStr->emitRef(MCOS, Dir); 432 } else { 433 // The list of directory paths. Compilation directory comes first. 434 MCOS->emitBytes(CompDir); 435 MCOS->emitBytes(StringRef("\0", 1)); 436 for (const auto &Dir : MCDwarfDirs) { 437 MCOS->emitBytes(Dir); // The DirectoryName, and... 438 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 439 } 440 } 441 442 // The file format, which is the inline null-terminated filename and a 443 // directory index. We don't track file size/timestamp so don't emit them 444 // in the v5 table. Emit MD5 checksums and source if we have them. 445 uint64_t Entries = 2; 446 if (HasAllMD5) 447 Entries += 1; 448 if (HasSource) 449 Entries += 1; 450 MCOS->emitInt8(Entries); 451 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path); 452 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 453 : dwarf::DW_FORM_string); 454 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index); 455 MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata); 456 if (HasAllMD5) { 457 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5); 458 MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16); 459 } 460 if (HasSource) { 461 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source); 462 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 463 : dwarf::DW_FORM_string); 464 } 465 // Then the counted list of files. The root file is file #0, then emit the 466 // files as provide by .file directives. 467 // MCDwarfFiles has an unused element [0] so use size() not size()+1. 468 // But sometimes MCDwarfFiles is empty, in which case we still emit one file. 469 MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size()); 470 // To accommodate assembler source written for DWARF v4 but trying to emit 471 // v5: If we didn't see a root file explicitly, replicate file #1. 472 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) && 473 "No root file and no .file directives"); 474 emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile, 475 HasAllMD5, HasSource, LineStr); 476 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i) 477 emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr); 478 } 479 480 std::pair<MCSymbol *, MCSymbol *> 481 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 482 ArrayRef<char> StandardOpcodeLengths, 483 std::optional<MCDwarfLineStr> &LineStr) const { 484 MCContext &context = MCOS->getContext(); 485 486 // Create a symbol at the beginning of the line table. 487 MCSymbol *LineStartSym = Label; 488 if (!LineStartSym) 489 LineStartSym = context.createTempSymbol(); 490 491 // Set the value of the symbol, as we are at the start of the line table. 492 MCOS->emitDwarfLineStartLabel(LineStartSym); 493 494 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 495 496 MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length"); 497 498 // Next 2 bytes is the Version. 499 unsigned LineTableVersion = context.getDwarfVersion(); 500 MCOS->emitInt16(LineTableVersion); 501 502 // In v5, we get address info next. 503 if (LineTableVersion >= 5) { 504 MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize()); 505 MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges. 506 } 507 508 // Create symbols for the start/end of the prologue. 509 MCSymbol *ProStartSym = context.createTempSymbol("prologue_start"); 510 MCSymbol *ProEndSym = context.createTempSymbol("prologue_end"); 511 512 // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is 513 // actually the length from after the length word, to the end of the prologue. 514 MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize); 515 516 MCOS->emitLabel(ProStartSym); 517 518 // Parameters of the state machine, are next. 519 MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment()); 520 // maximum_operations_per_instruction 521 // For non-VLIW architectures this field is always 1. 522 // FIXME: VLIW architectures need to update this field accordingly. 523 if (LineTableVersion >= 4) 524 MCOS->emitInt8(1); 525 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT); 526 MCOS->emitInt8(Params.DWARF2LineBase); 527 MCOS->emitInt8(Params.DWARF2LineRange); 528 MCOS->emitInt8(StandardOpcodeLengths.size() + 1); 529 530 // Standard opcode lengths 531 for (char Length : StandardOpcodeLengths) 532 MCOS->emitInt8(Length); 533 534 // Put out the directory and file tables. The formats vary depending on 535 // the version. 536 if (LineTableVersion >= 5) 537 emitV5FileDirTables(MCOS, LineStr); 538 else 539 emitV2FileDirTables(MCOS); 540 541 // This is the end of the prologue, so set the value of the symbol at the 542 // end of the prologue (that was used in a previous expression). 543 MCOS->emitLabel(ProEndSym); 544 545 return std::make_pair(LineStartSym, LineEndSym); 546 } 547 548 void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params, 549 std::optional<MCDwarfLineStr> &LineStr) const { 550 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second; 551 552 // Put out the line tables. 553 for (const auto &LineSec : MCLineSections.getMCLineEntries()) 554 emitOne(MCOS, LineSec.first, LineSec.second); 555 556 // This is the end of the section, so set the value of the symbol at the end 557 // of this section (that was used in a previous expression). 558 MCOS->emitLabel(LineEndSym); 559 } 560 561 Expected<unsigned> 562 MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName, 563 std::optional<MD5::MD5Result> Checksum, 564 std::optional<StringRef> Source, 565 uint16_t DwarfVersion, unsigned FileNumber) { 566 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, 567 FileNumber); 568 } 569 570 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory, 571 StringRef &FileName, 572 std::optional<MD5::MD5Result> Checksum) { 573 if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName) 574 return false; 575 return RootFile.Checksum == Checksum; 576 } 577 578 Expected<unsigned> 579 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName, 580 std::optional<MD5::MD5Result> Checksum, 581 std::optional<StringRef> Source, 582 uint16_t DwarfVersion, unsigned FileNumber) { 583 if (Directory == CompilationDir) 584 Directory = ""; 585 if (FileName.empty()) { 586 FileName = "<stdin>"; 587 Directory = ""; 588 } 589 assert(!FileName.empty()); 590 // Keep track of whether any or all files have an MD5 checksum. 591 // If any files have embedded source, they all must. 592 if (MCDwarfFiles.empty()) { 593 trackMD5Usage(Checksum.has_value()); 594 HasSource = (Source != std::nullopt); 595 } 596 if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum)) 597 return 0; 598 if (FileNumber == 0) { 599 // File numbers start with 1 and/or after any file numbers 600 // allocated by inline-assembler .file directives. 601 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size(); 602 SmallString<256> Buffer; 603 auto IterBool = SourceIdMap.insert( 604 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer), 605 FileNumber)); 606 if (!IterBool.second) 607 return IterBool.first->second; 608 } 609 // Make space for this FileNumber in the MCDwarfFiles vector if needed. 610 if (FileNumber >= MCDwarfFiles.size()) 611 MCDwarfFiles.resize(FileNumber + 1); 612 613 // Get the new MCDwarfFile slot for this FileNumber. 614 MCDwarfFile &File = MCDwarfFiles[FileNumber]; 615 616 // It is an error to see the same number more than once. 617 if (!File.Name.empty()) 618 return make_error<StringError>("file number already allocated", 619 inconvertibleErrorCode()); 620 621 // If any files have embedded source, they all must. 622 if (HasSource != (Source != std::nullopt)) 623 return make_error<StringError>("inconsistent use of embedded source", 624 inconvertibleErrorCode()); 625 626 if (Directory.empty()) { 627 // Separate the directory part from the basename of the FileName. 628 StringRef tFileName = sys::path::filename(FileName); 629 if (!tFileName.empty()) { 630 Directory = sys::path::parent_path(FileName); 631 if (!Directory.empty()) 632 FileName = tFileName; 633 } 634 } 635 636 // Find or make an entry in the MCDwarfDirs vector for this Directory. 637 // Capture directory name. 638 unsigned DirIndex; 639 if (Directory.empty()) { 640 // For FileNames with no directories a DirIndex of 0 is used. 641 DirIndex = 0; 642 } else { 643 DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin(); 644 if (DirIndex >= MCDwarfDirs.size()) 645 MCDwarfDirs.push_back(std::string(Directory)); 646 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with 647 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the 648 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames 649 // are stored at MCDwarfFiles[FileNumber].Name . 650 DirIndex++; 651 } 652 653 File.Name = std::string(FileName); 654 File.DirIndex = DirIndex; 655 File.Checksum = Checksum; 656 trackMD5Usage(Checksum.has_value()); 657 File.Source = Source; 658 if (Source) 659 HasSource = true; 660 661 // return the allocated FileNumber. 662 return FileNumber; 663 } 664 665 /// Utility function to emit the encoding to a streamer. 666 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 667 int64_t LineDelta, uint64_t AddrDelta) { 668 MCContext &Context = MCOS->getContext(); 669 SmallString<256> Tmp; 670 raw_svector_ostream OS(Tmp); 671 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS); 672 MCOS->emitBytes(OS.str()); 673 } 674 675 /// Given a special op, return the address skip amount (in units of 676 /// DWARF2_LINE_MIN_INSN_LENGTH). 677 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) { 678 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange; 679 } 680 681 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. 682 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params, 683 int64_t LineDelta, uint64_t AddrDelta, 684 raw_ostream &OS) { 685 uint64_t Temp, Opcode; 686 bool NeedCopy = false; 687 688 // The maximum address skip amount that can be encoded with a special op. 689 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255); 690 691 // Scale the address delta by the minimum instruction length. 692 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 693 694 // A LineDelta of INT64_MAX is a signal that this is actually a 695 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 696 // end_sequence to emit the matrix entry. 697 if (LineDelta == INT64_MAX) { 698 if (AddrDelta == MaxSpecialAddrDelta) 699 OS << char(dwarf::DW_LNS_const_add_pc); 700 else if (AddrDelta) { 701 OS << char(dwarf::DW_LNS_advance_pc); 702 encodeULEB128(AddrDelta, OS); 703 } 704 OS << char(dwarf::DW_LNS_extended_op); 705 OS << char(1); 706 OS << char(dwarf::DW_LNE_end_sequence); 707 return; 708 } 709 710 // Bias the line delta by the base. 711 Temp = LineDelta - Params.DWARF2LineBase; 712 713 // If the line increment is out of range of a special opcode, we must encode 714 // it with DW_LNS_advance_line. 715 if (Temp >= Params.DWARF2LineRange || 716 Temp + Params.DWARF2LineOpcodeBase > 255) { 717 OS << char(dwarf::DW_LNS_advance_line); 718 encodeSLEB128(LineDelta, OS); 719 720 LineDelta = 0; 721 Temp = 0 - Params.DWARF2LineBase; 722 NeedCopy = true; 723 } 724 725 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. 726 if (LineDelta == 0 && AddrDelta == 0) { 727 OS << char(dwarf::DW_LNS_copy); 728 return; 729 } 730 731 // Bias the opcode by the special opcode base. 732 Temp += Params.DWARF2LineOpcodeBase; 733 734 // Avoid overflow when addr_delta is large. 735 if (AddrDelta < 256 + MaxSpecialAddrDelta) { 736 // Try using a special opcode. 737 Opcode = Temp + AddrDelta * Params.DWARF2LineRange; 738 if (Opcode <= 255) { 739 OS << char(Opcode); 740 return; 741 } 742 743 // Try using DW_LNS_const_add_pc followed by special op. 744 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange; 745 if (Opcode <= 255) { 746 OS << char(dwarf::DW_LNS_const_add_pc); 747 OS << char(Opcode); 748 return; 749 } 750 } 751 752 // Otherwise use DW_LNS_advance_pc. 753 OS << char(dwarf::DW_LNS_advance_pc); 754 encodeULEB128(AddrDelta, OS); 755 756 if (NeedCopy) 757 OS << char(dwarf::DW_LNS_copy); 758 else { 759 assert(Temp <= 255 && "Buggy special opcode encoding."); 760 OS << char(Temp); 761 } 762 } 763 764 // Utility function to write a tuple for .debug_abbrev. 765 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { 766 MCOS->emitULEB128IntValue(Name); 767 MCOS->emitULEB128IntValue(Form); 768 } 769 770 // When generating dwarf for assembly source files this emits 771 // the data for .debug_abbrev section which contains three DIEs. 772 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { 773 MCContext &context = MCOS->getContext(); 774 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 775 776 // DW_TAG_compile_unit DIE abbrev (1). 777 MCOS->emitULEB128IntValue(1); 778 MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit); 779 MCOS->emitInt8(dwarf::DW_CHILDREN_yes); 780 dwarf::Form SecOffsetForm = 781 context.getDwarfVersion() >= 4 782 ? dwarf::DW_FORM_sec_offset 783 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8 784 : dwarf::DW_FORM_data4); 785 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm); 786 if (context.getGenDwarfSectionSyms().size() > 1 && 787 context.getDwarfVersion() >= 3) { 788 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm); 789 } else { 790 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 791 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); 792 } 793 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 794 if (!context.getCompilationDir().empty()) 795 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); 796 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 797 if (!DwarfDebugFlags.empty()) 798 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); 799 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); 800 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); 801 EmitAbbrev(MCOS, 0, 0); 802 803 // DW_TAG_label DIE abbrev (2). 804 MCOS->emitULEB128IntValue(2); 805 MCOS->emitULEB128IntValue(dwarf::DW_TAG_label); 806 MCOS->emitInt8(dwarf::DW_CHILDREN_no); 807 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 808 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); 809 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); 810 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 811 EmitAbbrev(MCOS, 0, 0); 812 813 // Terminate the abbreviations for this compilation unit. 814 MCOS->emitInt8(0); 815 } 816 817 // When generating dwarf for assembly source files this emits the data for 818 // .debug_aranges section. This section contains a header and a table of pairs 819 // of PointerSize'ed values for the address and size of section(s) with line 820 // table entries. 821 static void EmitGenDwarfAranges(MCStreamer *MCOS, 822 const MCSymbol *InfoSectionSymbol) { 823 MCContext &context = MCOS->getContext(); 824 825 auto &Sections = context.getGenDwarfSectionSyms(); 826 827 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 828 829 unsigned UnitLengthBytes = 830 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 831 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 832 833 // This will be the length of the .debug_aranges section, first account for 834 // the size of each item in the header (see below where we emit these items). 835 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1; 836 837 // Figure the padding after the header before the table of address and size 838 // pairs who's values are PointerSize'ed. 839 const MCAsmInfo *asmInfo = context.getAsmInfo(); 840 int AddrSize = asmInfo->getCodePointerSize(); 841 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); 842 if (Pad == 2 * AddrSize) 843 Pad = 0; 844 Length += Pad; 845 846 // Add the size of the pair of PointerSize'ed values for the address and size 847 // of each section we have in the table. 848 Length += 2 * AddrSize * Sections.size(); 849 // And the pair of terminating zeros. 850 Length += 2 * AddrSize; 851 852 // Emit the header for this section. 853 if (context.getDwarfFormat() == dwarf::DWARF64) 854 // The DWARF64 mark. 855 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 856 // The 4 (8 for DWARF64) byte length not including the length of the unit 857 // length field itself. 858 MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize); 859 // The 2 byte version, which is 2. 860 MCOS->emitInt16(2); 861 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info 862 // from the start of the .debug_info. 863 if (InfoSectionSymbol) 864 MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize, 865 asmInfo->needsDwarfSectionOffsetDirective()); 866 else 867 MCOS->emitIntValue(0, OffsetSize); 868 // The 1 byte size of an address. 869 MCOS->emitInt8(AddrSize); 870 // The 1 byte size of a segment descriptor, we use a value of zero. 871 MCOS->emitInt8(0); 872 // Align the header with the padding if needed, before we put out the table. 873 for(int i = 0; i < Pad; i++) 874 MCOS->emitInt8(0); 875 876 // Now emit the table of pairs of PointerSize'ed values for the section 877 // addresses and sizes. 878 for (MCSection *Sec : Sections) { 879 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 880 MCSymbol *EndSymbol = Sec->getEndSymbol(context); 881 assert(StartSymbol && "StartSymbol must not be NULL"); 882 assert(EndSymbol && "EndSymbol must not be NULL"); 883 884 const MCExpr *Addr = MCSymbolRefExpr::create( 885 StartSymbol, MCSymbolRefExpr::VK_None, context); 886 const MCExpr *Size = 887 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 888 MCOS->emitValue(Addr, AddrSize); 889 emitAbsValue(*MCOS, Size, AddrSize); 890 } 891 892 // And finally the pair of terminating zeros. 893 MCOS->emitIntValue(0, AddrSize); 894 MCOS->emitIntValue(0, AddrSize); 895 } 896 897 // When generating dwarf for assembly source files this emits the data for 898 // .debug_info section which contains three parts. The header, the compile_unit 899 // DIE and a list of label DIEs. 900 static void EmitGenDwarfInfo(MCStreamer *MCOS, 901 const MCSymbol *AbbrevSectionSymbol, 902 const MCSymbol *LineSectionSymbol, 903 const MCSymbol *RangesSymbol) { 904 MCContext &context = MCOS->getContext(); 905 906 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 907 908 // Create a symbol at the start and end of this section used in here for the 909 // expression to calculate the length in the header. 910 MCSymbol *InfoStart = context.createTempSymbol(); 911 MCOS->emitLabel(InfoStart); 912 MCSymbol *InfoEnd = context.createTempSymbol(); 913 914 // First part: the header. 915 916 unsigned UnitLengthBytes = 917 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 918 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 919 920 if (context.getDwarfFormat() == dwarf::DWARF64) 921 // Emit DWARF64 mark. 922 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 923 924 // The 4 (8 for DWARF64) byte total length of the information for this 925 // compilation unit, not including the unit length field itself. 926 const MCExpr *Length = 927 makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes); 928 emitAbsValue(*MCOS, Length, OffsetSize); 929 930 // The 2 byte DWARF version. 931 MCOS->emitInt16(context.getDwarfVersion()); 932 933 // The DWARF v5 header has unit type, address size, abbrev offset. 934 // Earlier versions have abbrev offset, address size. 935 const MCAsmInfo &AsmInfo = *context.getAsmInfo(); 936 int AddrSize = AsmInfo.getCodePointerSize(); 937 if (context.getDwarfVersion() >= 5) { 938 MCOS->emitInt8(dwarf::DW_UT_compile); 939 MCOS->emitInt8(AddrSize); 940 } 941 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of 942 // the .debug_abbrev. 943 if (AbbrevSectionSymbol) 944 MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize, 945 AsmInfo.needsDwarfSectionOffsetDirective()); 946 else 947 // Since the abbrevs are at the start of the section, the offset is zero. 948 MCOS->emitIntValue(0, OffsetSize); 949 if (context.getDwarfVersion() <= 4) 950 MCOS->emitInt8(AddrSize); 951 952 // Second part: the compile_unit DIE. 953 954 // The DW_TAG_compile_unit DIE abbrev (1). 955 MCOS->emitULEB128IntValue(1); 956 957 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the 958 // .debug_line section. 959 if (LineSectionSymbol) 960 MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize, 961 AsmInfo.needsDwarfSectionOffsetDirective()); 962 else 963 // The line table is at the start of the section, so the offset is zero. 964 MCOS->emitIntValue(0, OffsetSize); 965 966 if (RangesSymbol) { 967 // There are multiple sections containing code, so we must use 968 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the 969 // start of the .debug_ranges/.debug_rnglists. 970 MCOS->emitSymbolValue(RangesSymbol, OffsetSize); 971 } else { 972 // If we only have one non-empty code section, we can use the simpler 973 // AT_low_pc and AT_high_pc attributes. 974 975 // Find the first (and only) non-empty text section 976 auto &Sections = context.getGenDwarfSectionSyms(); 977 const auto TextSection = Sections.begin(); 978 assert(TextSection != Sections.end() && "No text section found"); 979 980 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol(); 981 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context); 982 assert(StartSymbol && "StartSymbol must not be NULL"); 983 assert(EndSymbol && "EndSymbol must not be NULL"); 984 985 // AT_low_pc, the first address of the default .text section. 986 const MCExpr *Start = MCSymbolRefExpr::create( 987 StartSymbol, MCSymbolRefExpr::VK_None, context); 988 MCOS->emitValue(Start, AddrSize); 989 990 // AT_high_pc, the last address of the default .text section. 991 const MCExpr *End = MCSymbolRefExpr::create( 992 EndSymbol, MCSymbolRefExpr::VK_None, context); 993 MCOS->emitValue(End, AddrSize); 994 } 995 996 // AT_name, the name of the source file. Reconstruct from the first directory 997 // and file table entries. 998 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs(); 999 if (MCDwarfDirs.size() > 0) { 1000 MCOS->emitBytes(MCDwarfDirs[0]); 1001 MCOS->emitBytes(sys::path::get_separator()); 1002 } 1003 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles(); 1004 // MCDwarfFiles might be empty if we have an empty source file. 1005 // If it's not empty, [0] is unused and [1] is the first actual file. 1006 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2); 1007 const MCDwarfFile &RootFile = 1008 MCDwarfFiles.empty() 1009 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile() 1010 : MCDwarfFiles[1]; 1011 MCOS->emitBytes(RootFile.Name); 1012 MCOS->emitInt8(0); // NULL byte to terminate the string. 1013 1014 // AT_comp_dir, the working directory the assembly was done in. 1015 if (!context.getCompilationDir().empty()) { 1016 MCOS->emitBytes(context.getCompilationDir()); 1017 MCOS->emitInt8(0); // NULL byte to terminate the string. 1018 } 1019 1020 // AT_APPLE_flags, the command line arguments of the assembler tool. 1021 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 1022 if (!DwarfDebugFlags.empty()){ 1023 MCOS->emitBytes(DwarfDebugFlags); 1024 MCOS->emitInt8(0); // NULL byte to terminate the string. 1025 } 1026 1027 // AT_producer, the version of the assembler tool. 1028 StringRef DwarfDebugProducer = context.getDwarfDebugProducer(); 1029 if (!DwarfDebugProducer.empty()) 1030 MCOS->emitBytes(DwarfDebugProducer); 1031 else 1032 MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")")); 1033 MCOS->emitInt8(0); // NULL byte to terminate the string. 1034 1035 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 1036 // draft has no standard code for assembler. 1037 MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler); 1038 1039 // Third part: the list of label DIEs. 1040 1041 // Loop on saved info for dwarf labels and create the DIEs for them. 1042 const std::vector<MCGenDwarfLabelEntry> &Entries = 1043 MCOS->getContext().getMCGenDwarfLabelEntries(); 1044 for (const auto &Entry : Entries) { 1045 // The DW_TAG_label DIE abbrev (2). 1046 MCOS->emitULEB128IntValue(2); 1047 1048 // AT_name, of the label without any leading underbar. 1049 MCOS->emitBytes(Entry.getName()); 1050 MCOS->emitInt8(0); // NULL byte to terminate the string. 1051 1052 // AT_decl_file, index into the file table. 1053 MCOS->emitInt32(Entry.getFileNumber()); 1054 1055 // AT_decl_line, source line number. 1056 MCOS->emitInt32(Entry.getLineNumber()); 1057 1058 // AT_low_pc, start address of the label. 1059 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(), 1060 MCSymbolRefExpr::VK_None, context); 1061 MCOS->emitValue(AT_low_pc, AddrSize); 1062 } 1063 1064 // Add the NULL DIE terminating the Compile Unit DIE's. 1065 MCOS->emitInt8(0); 1066 1067 // Now set the value of the symbol at the end of the info section. 1068 MCOS->emitLabel(InfoEnd); 1069 } 1070 1071 // When generating dwarf for assembly source files this emits the data for 1072 // .debug_ranges section. We only emit one range list, which spans all of the 1073 // executable sections of this file. 1074 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) { 1075 MCContext &context = MCOS->getContext(); 1076 auto &Sections = context.getGenDwarfSectionSyms(); 1077 1078 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 1079 int AddrSize = AsmInfo->getCodePointerSize(); 1080 MCSymbol *RangesSymbol; 1081 1082 if (MCOS->getContext().getDwarfVersion() >= 5) { 1083 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection()); 1084 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS); 1085 MCOS->AddComment("Offset entry count"); 1086 MCOS->emitInt32(0); 1087 RangesSymbol = context.createTempSymbol("debug_rnglist0_start"); 1088 MCOS->emitLabel(RangesSymbol); 1089 for (MCSection *Sec : Sections) { 1090 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 1091 const MCSymbol *EndSymbol = Sec->getEndSymbol(context); 1092 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 1093 StartSymbol, MCSymbolRefExpr::VK_None, context); 1094 const MCExpr *SectionSize = 1095 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 1096 MCOS->emitInt8(dwarf::DW_RLE_start_length); 1097 MCOS->emitValue(SectionStartAddr, AddrSize); 1098 MCOS->emitULEB128Value(SectionSize); 1099 } 1100 MCOS->emitInt8(dwarf::DW_RLE_end_of_list); 1101 MCOS->emitLabel(EndSymbol); 1102 } else { 1103 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection()); 1104 RangesSymbol = context.createTempSymbol("debug_ranges_start"); 1105 MCOS->emitLabel(RangesSymbol); 1106 for (MCSection *Sec : Sections) { 1107 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 1108 const MCSymbol *EndSymbol = Sec->getEndSymbol(context); 1109 1110 // Emit a base address selection entry for the section start. 1111 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 1112 StartSymbol, MCSymbolRefExpr::VK_None, context); 1113 MCOS->emitFill(AddrSize, 0xFF); 1114 MCOS->emitValue(SectionStartAddr, AddrSize); 1115 1116 // Emit a range list entry spanning this section. 1117 const MCExpr *SectionSize = 1118 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 1119 MCOS->emitIntValue(0, AddrSize); 1120 emitAbsValue(*MCOS, SectionSize, AddrSize); 1121 } 1122 1123 // Emit end of list entry 1124 MCOS->emitIntValue(0, AddrSize); 1125 MCOS->emitIntValue(0, AddrSize); 1126 } 1127 1128 return RangesSymbol; 1129 } 1130 1131 // 1132 // When generating dwarf for assembly source files this emits the Dwarf 1133 // sections. 1134 // 1135 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) { 1136 MCContext &context = MCOS->getContext(); 1137 1138 // Create the dwarf sections in this order (.debug_line already created). 1139 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 1140 bool CreateDwarfSectionSymbols = 1141 AsmInfo->doesDwarfUseRelocationsAcrossSections(); 1142 MCSymbol *LineSectionSymbol = nullptr; 1143 if (CreateDwarfSectionSymbols) 1144 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0); 1145 MCSymbol *AbbrevSectionSymbol = nullptr; 1146 MCSymbol *InfoSectionSymbol = nullptr; 1147 MCSymbol *RangesSymbol = nullptr; 1148 1149 // Create end symbols for each section, and remove empty sections 1150 MCOS->getContext().finalizeDwarfSections(*MCOS); 1151 1152 // If there are no sections to generate debug info for, we don't need 1153 // to do anything 1154 if (MCOS->getContext().getGenDwarfSectionSyms().empty()) 1155 return; 1156 1157 // We only use the .debug_ranges section if we have multiple code sections, 1158 // and we are emitting a DWARF version which supports it. 1159 const bool UseRangesSection = 1160 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 && 1161 MCOS->getContext().getDwarfVersion() >= 3; 1162 CreateDwarfSectionSymbols |= UseRangesSection; 1163 1164 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 1165 if (CreateDwarfSectionSymbols) { 1166 InfoSectionSymbol = context.createTempSymbol(); 1167 MCOS->emitLabel(InfoSectionSymbol); 1168 } 1169 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 1170 if (CreateDwarfSectionSymbols) { 1171 AbbrevSectionSymbol = context.createTempSymbol(); 1172 MCOS->emitLabel(AbbrevSectionSymbol); 1173 } 1174 1175 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 1176 1177 // Output the data for .debug_aranges section. 1178 EmitGenDwarfAranges(MCOS, InfoSectionSymbol); 1179 1180 if (UseRangesSection) { 1181 RangesSymbol = emitGenDwarfRanges(MCOS); 1182 assert(RangesSymbol); 1183 } 1184 1185 // Output the data for .debug_abbrev section. 1186 EmitGenDwarfAbbrev(MCOS); 1187 1188 // Output the data for .debug_info section. 1189 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol); 1190 } 1191 1192 // 1193 // When generating dwarf for assembly source files this is called when symbol 1194 // for a label is created. If this symbol is not a temporary and is in the 1195 // section that dwarf is being generated for, save the needed info to create 1196 // a dwarf label. 1197 // 1198 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, 1199 SourceMgr &SrcMgr, SMLoc &Loc) { 1200 // We won't create dwarf labels for temporary symbols. 1201 if (Symbol->isTemporary()) 1202 return; 1203 MCContext &context = MCOS->getContext(); 1204 // We won't create dwarf labels for symbols in sections that we are not 1205 // generating debug info for. 1206 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly())) 1207 return; 1208 1209 // The dwarf label's name does not have the symbol name's leading 1210 // underbar if any. 1211 StringRef Name = Symbol->getName(); 1212 if (Name.startswith("_")) 1213 Name = Name.substr(1, Name.size()-1); 1214 1215 // Get the dwarf file number to be used for the dwarf label. 1216 unsigned FileNumber = context.getGenDwarfFileNumber(); 1217 1218 // Finding the line number is the expensive part which is why we just don't 1219 // pass it in as for some symbols we won't create a dwarf label. 1220 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); 1221 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); 1222 1223 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc 1224 // values so that they don't have things like an ARM thumb bit from the 1225 // original symbol. So when used they won't get a low bit set after 1226 // relocation. 1227 MCSymbol *Label = context.createTempSymbol(); 1228 MCOS->emitLabel(Label); 1229 1230 // Create and entry for the info and add it to the other entries. 1231 MCOS->getContext().addMCGenDwarfLabelEntry( 1232 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label)); 1233 } 1234 1235 static int getDataAlignmentFactor(MCStreamer &streamer) { 1236 MCContext &context = streamer.getContext(); 1237 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1238 int size = asmInfo->getCalleeSaveStackSlotSize(); 1239 if (asmInfo->isStackGrowthDirectionUp()) 1240 return size; 1241 else 1242 return -size; 1243 } 1244 1245 static unsigned getSizeForEncoding(MCStreamer &streamer, 1246 unsigned symbolEncoding) { 1247 MCContext &context = streamer.getContext(); 1248 unsigned format = symbolEncoding & 0x0f; 1249 switch (format) { 1250 default: llvm_unreachable("Unknown Encoding"); 1251 case dwarf::DW_EH_PE_absptr: 1252 case dwarf::DW_EH_PE_signed: 1253 return context.getAsmInfo()->getCodePointerSize(); 1254 case dwarf::DW_EH_PE_udata2: 1255 case dwarf::DW_EH_PE_sdata2: 1256 return 2; 1257 case dwarf::DW_EH_PE_udata4: 1258 case dwarf::DW_EH_PE_sdata4: 1259 return 4; 1260 case dwarf::DW_EH_PE_udata8: 1261 case dwarf::DW_EH_PE_sdata8: 1262 return 8; 1263 } 1264 } 1265 1266 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol, 1267 unsigned symbolEncoding, bool isEH) { 1268 MCContext &context = streamer.getContext(); 1269 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1270 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol, 1271 symbolEncoding, 1272 streamer); 1273 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1274 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH) 1275 emitAbsValue(streamer, v, size); 1276 else 1277 streamer.emitValue(v, size); 1278 } 1279 1280 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, 1281 unsigned symbolEncoding) { 1282 MCContext &context = streamer.getContext(); 1283 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1284 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol, 1285 symbolEncoding, 1286 streamer); 1287 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1288 streamer.emitValue(v, size); 1289 } 1290 1291 namespace { 1292 1293 class FrameEmitterImpl { 1294 int CFAOffset = 0; 1295 int InitialCFAOffset = 0; 1296 bool IsEH; 1297 MCObjectStreamer &Streamer; 1298 1299 public: 1300 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer) 1301 : IsEH(IsEH), Streamer(Streamer) {} 1302 1303 /// Emit the unwind information in a compact way. 1304 void EmitCompactUnwind(const MCDwarfFrameInfo &frame); 1305 1306 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F); 1307 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame, 1308 bool LastInSection, const MCSymbol &SectionStart); 1309 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1310 MCSymbol *BaseLabel); 1311 void emitCFIInstruction(const MCCFIInstruction &Instr); 1312 }; 1313 1314 } // end anonymous namespace 1315 1316 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) { 1317 Streamer.emitInt8(Encoding); 1318 } 1319 1320 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) { 1321 int dataAlignmentFactor = getDataAlignmentFactor(Streamer); 1322 auto *MRI = Streamer.getContext().getRegisterInfo(); 1323 1324 switch (Instr.getOperation()) { 1325 case MCCFIInstruction::OpRegister: { 1326 unsigned Reg1 = Instr.getRegister(); 1327 unsigned Reg2 = Instr.getRegister2(); 1328 if (!IsEH) { 1329 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1); 1330 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2); 1331 } 1332 Streamer.emitInt8(dwarf::DW_CFA_register); 1333 Streamer.emitULEB128IntValue(Reg1); 1334 Streamer.emitULEB128IntValue(Reg2); 1335 return; 1336 } 1337 case MCCFIInstruction::OpWindowSave: 1338 Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save); 1339 return; 1340 1341 case MCCFIInstruction::OpNegateRAState: 1342 Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state); 1343 return; 1344 1345 case MCCFIInstruction::OpUndefined: { 1346 unsigned Reg = Instr.getRegister(); 1347 Streamer.emitInt8(dwarf::DW_CFA_undefined); 1348 Streamer.emitULEB128IntValue(Reg); 1349 return; 1350 } 1351 case MCCFIInstruction::OpAdjustCfaOffset: 1352 case MCCFIInstruction::OpDefCfaOffset: { 1353 const bool IsRelative = 1354 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset; 1355 1356 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset); 1357 1358 if (IsRelative) 1359 CFAOffset += Instr.getOffset(); 1360 else 1361 CFAOffset = Instr.getOffset(); 1362 1363 Streamer.emitULEB128IntValue(CFAOffset); 1364 1365 return; 1366 } 1367 case MCCFIInstruction::OpDefCfa: { 1368 unsigned Reg = Instr.getRegister(); 1369 if (!IsEH) 1370 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1371 Streamer.emitInt8(dwarf::DW_CFA_def_cfa); 1372 Streamer.emitULEB128IntValue(Reg); 1373 CFAOffset = Instr.getOffset(); 1374 Streamer.emitULEB128IntValue(CFAOffset); 1375 1376 return; 1377 } 1378 case MCCFIInstruction::OpDefCfaRegister: { 1379 unsigned Reg = Instr.getRegister(); 1380 if (!IsEH) 1381 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1382 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register); 1383 Streamer.emitULEB128IntValue(Reg); 1384 1385 return; 1386 } 1387 // TODO: Implement `_sf` variants if/when they need to be emitted. 1388 case MCCFIInstruction::OpLLVMDefAspaceCfa: { 1389 unsigned Reg = Instr.getRegister(); 1390 if (!IsEH) 1391 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1392 Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1); 1393 Streamer.emitULEB128IntValue(Reg); 1394 CFAOffset = Instr.getOffset(); 1395 Streamer.emitULEB128IntValue(CFAOffset); 1396 Streamer.emitULEB128IntValue(Instr.getAddressSpace()); 1397 1398 return; 1399 } 1400 case MCCFIInstruction::OpOffset: 1401 case MCCFIInstruction::OpRelOffset: { 1402 const bool IsRelative = 1403 Instr.getOperation() == MCCFIInstruction::OpRelOffset; 1404 1405 unsigned Reg = Instr.getRegister(); 1406 if (!IsEH) 1407 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1408 1409 int Offset = Instr.getOffset(); 1410 if (IsRelative) 1411 Offset -= CFAOffset; 1412 Offset = Offset / dataAlignmentFactor; 1413 1414 if (Offset < 0) { 1415 Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf); 1416 Streamer.emitULEB128IntValue(Reg); 1417 Streamer.emitSLEB128IntValue(Offset); 1418 } else if (Reg < 64) { 1419 Streamer.emitInt8(dwarf::DW_CFA_offset + Reg); 1420 Streamer.emitULEB128IntValue(Offset); 1421 } else { 1422 Streamer.emitInt8(dwarf::DW_CFA_offset_extended); 1423 Streamer.emitULEB128IntValue(Reg); 1424 Streamer.emitULEB128IntValue(Offset); 1425 } 1426 return; 1427 } 1428 case MCCFIInstruction::OpRememberState: 1429 Streamer.emitInt8(dwarf::DW_CFA_remember_state); 1430 return; 1431 case MCCFIInstruction::OpRestoreState: 1432 Streamer.emitInt8(dwarf::DW_CFA_restore_state); 1433 return; 1434 case MCCFIInstruction::OpSameValue: { 1435 unsigned Reg = Instr.getRegister(); 1436 Streamer.emitInt8(dwarf::DW_CFA_same_value); 1437 Streamer.emitULEB128IntValue(Reg); 1438 return; 1439 } 1440 case MCCFIInstruction::OpRestore: { 1441 unsigned Reg = Instr.getRegister(); 1442 if (!IsEH) 1443 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1444 if (Reg < 64) { 1445 Streamer.emitInt8(dwarf::DW_CFA_restore | Reg); 1446 } else { 1447 Streamer.emitInt8(dwarf::DW_CFA_restore_extended); 1448 Streamer.emitULEB128IntValue(Reg); 1449 } 1450 return; 1451 } 1452 case MCCFIInstruction::OpGnuArgsSize: 1453 Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size); 1454 Streamer.emitULEB128IntValue(Instr.getOffset()); 1455 return; 1456 1457 case MCCFIInstruction::OpEscape: 1458 Streamer.emitBytes(Instr.getValues()); 1459 return; 1460 } 1461 llvm_unreachable("Unhandled case in switch"); 1462 } 1463 1464 /// Emit frame instructions to describe the layout of the frame. 1465 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1466 MCSymbol *BaseLabel) { 1467 for (const MCCFIInstruction &Instr : Instrs) { 1468 MCSymbol *Label = Instr.getLabel(); 1469 // Throw out move if the label is invalid. 1470 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. 1471 1472 // Advance row if new location. 1473 if (BaseLabel && Label) { 1474 MCSymbol *ThisSym = Label; 1475 if (ThisSym != BaseLabel) { 1476 Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); 1477 BaseLabel = ThisSym; 1478 } 1479 } 1480 1481 emitCFIInstruction(Instr); 1482 } 1483 } 1484 1485 /// Emit the unwind information in a compact way. 1486 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) { 1487 MCContext &Context = Streamer.getContext(); 1488 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1489 1490 // range-start range-length compact-unwind-enc personality-func lsda 1491 // _foo LfooEnd-_foo 0x00000023 0 0 1492 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 1493 // 1494 // .section __LD,__compact_unwind,regular,debug 1495 // 1496 // # compact unwind for _foo 1497 // .quad _foo 1498 // .set L1,LfooEnd-_foo 1499 // .long L1 1500 // .long 0x01010001 1501 // .quad 0 1502 // .quad 0 1503 // 1504 // # compact unwind for _bar 1505 // .quad _bar 1506 // .set L2,LbarEnd-_bar 1507 // .long L2 1508 // .long 0x01020011 1509 // .quad __gxx_personality 1510 // .quad except_tab1 1511 1512 uint32_t Encoding = Frame.CompactUnwindEncoding; 1513 if (!Encoding) return; 1514 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly()); 1515 1516 // The encoding needs to know we have an LSDA. 1517 if (!DwarfEHFrameOnly && Frame.Lsda) 1518 Encoding |= 0x40000000; 1519 1520 // Range Start 1521 unsigned FDEEncoding = MOFI->getFDEEncoding(); 1522 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); 1523 Streamer.emitSymbolValue(Frame.Begin, Size); 1524 1525 // Range Length 1526 const MCExpr *Range = 1527 makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0); 1528 emitAbsValue(Streamer, Range, 4); 1529 1530 // Compact Encoding 1531 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); 1532 Streamer.emitIntValue(Encoding, Size); 1533 1534 // Personality Function 1535 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); 1536 if (!DwarfEHFrameOnly && Frame.Personality) 1537 Streamer.emitSymbolValue(Frame.Personality, Size); 1538 else 1539 Streamer.emitIntValue(0, Size); // No personality fn 1540 1541 // LSDA 1542 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); 1543 if (!DwarfEHFrameOnly && Frame.Lsda) 1544 Streamer.emitSymbolValue(Frame.Lsda, Size); 1545 else 1546 Streamer.emitIntValue(0, Size); // No LSDA 1547 } 1548 1549 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) { 1550 if (IsEH) 1551 return 1; 1552 switch (DwarfVersion) { 1553 case 2: 1554 return 1; 1555 case 3: 1556 return 3; 1557 case 4: 1558 case 5: 1559 return 4; 1560 } 1561 llvm_unreachable("Unknown version"); 1562 } 1563 1564 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) { 1565 MCContext &context = Streamer.getContext(); 1566 const MCRegisterInfo *MRI = context.getRegisterInfo(); 1567 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1568 1569 MCSymbol *sectionStart = context.createTempSymbol(); 1570 Streamer.emitLabel(sectionStart); 1571 1572 MCSymbol *sectionEnd = context.createTempSymbol(); 1573 1574 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat(); 1575 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format); 1576 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format); 1577 bool IsDwarf64 = Format == dwarf::DWARF64; 1578 1579 if (IsDwarf64) 1580 // DWARF64 mark 1581 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64); 1582 1583 // Length 1584 const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart, 1585 *sectionEnd, UnitLengthBytes); 1586 emitAbsValue(Streamer, Length, OffsetSize); 1587 1588 // CIE ID 1589 uint64_t CIE_ID = 1590 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID); 1591 Streamer.emitIntValue(CIE_ID, OffsetSize); 1592 1593 // Version 1594 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion()); 1595 Streamer.emitInt8(CIEVersion); 1596 1597 if (IsEH) { 1598 SmallString<8> Augmentation; 1599 Augmentation += "z"; 1600 if (Frame.Personality) 1601 Augmentation += "P"; 1602 if (Frame.Lsda) 1603 Augmentation += "L"; 1604 Augmentation += "R"; 1605 if (Frame.IsSignalFrame) 1606 Augmentation += "S"; 1607 if (Frame.IsBKeyFrame) 1608 Augmentation += "B"; 1609 if (Frame.IsMTETaggedFrame) 1610 Augmentation += "G"; 1611 Streamer.emitBytes(Augmentation); 1612 } 1613 Streamer.emitInt8(0); 1614 1615 if (CIEVersion >= 4) { 1616 // Address Size 1617 Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize()); 1618 1619 // Segment Descriptor Size 1620 Streamer.emitInt8(0); 1621 } 1622 1623 // Code Alignment Factor 1624 Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment()); 1625 1626 // Data Alignment Factor 1627 Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer)); 1628 1629 // Return Address Register 1630 unsigned RAReg = Frame.RAReg; 1631 if (RAReg == static_cast<unsigned>(INT_MAX)) 1632 RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH); 1633 1634 if (CIEVersion == 1) { 1635 assert(RAReg <= 255 && 1636 "DWARF 2 encodes return_address_register in one byte"); 1637 Streamer.emitInt8(RAReg); 1638 } else { 1639 Streamer.emitULEB128IntValue(RAReg); 1640 } 1641 1642 // Augmentation Data Length (optional) 1643 unsigned augmentationLength = 0; 1644 if (IsEH) { 1645 if (Frame.Personality) { 1646 // Personality Encoding 1647 augmentationLength += 1; 1648 // Personality 1649 augmentationLength += 1650 getSizeForEncoding(Streamer, Frame.PersonalityEncoding); 1651 } 1652 if (Frame.Lsda) 1653 augmentationLength += 1; 1654 // Encoding of the FDE pointers 1655 augmentationLength += 1; 1656 1657 Streamer.emitULEB128IntValue(augmentationLength); 1658 1659 // Augmentation Data (optional) 1660 if (Frame.Personality) { 1661 // Personality Encoding 1662 emitEncodingByte(Streamer, Frame.PersonalityEncoding); 1663 // Personality 1664 EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding); 1665 } 1666 1667 if (Frame.Lsda) 1668 emitEncodingByte(Streamer, Frame.LsdaEncoding); 1669 1670 // Encoding of the FDE pointers 1671 emitEncodingByte(Streamer, MOFI->getFDEEncoding()); 1672 } 1673 1674 // Initial Instructions 1675 1676 const MCAsmInfo *MAI = context.getAsmInfo(); 1677 if (!Frame.IsSimple) { 1678 const std::vector<MCCFIInstruction> &Instructions = 1679 MAI->getInitialFrameState(); 1680 emitCFIInstructions(Instructions, nullptr); 1681 } 1682 1683 InitialCFAOffset = CFAOffset; 1684 1685 // Padding 1686 Streamer.emitValueToAlignment(Align(IsEH ? 4 : MAI->getCodePointerSize())); 1687 1688 Streamer.emitLabel(sectionEnd); 1689 return *sectionStart; 1690 } 1691 1692 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart, 1693 const MCDwarfFrameInfo &frame, 1694 bool LastInSection, 1695 const MCSymbol &SectionStart) { 1696 MCContext &context = Streamer.getContext(); 1697 MCSymbol *fdeStart = context.createTempSymbol(); 1698 MCSymbol *fdeEnd = context.createTempSymbol(); 1699 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1700 1701 CFAOffset = InitialCFAOffset; 1702 1703 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat(); 1704 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format); 1705 1706 if (Format == dwarf::DWARF64) 1707 // DWARF64 mark 1708 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64); 1709 1710 // Length 1711 const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0); 1712 emitAbsValue(Streamer, Length, OffsetSize); 1713 1714 Streamer.emitLabel(fdeStart); 1715 1716 // CIE Pointer 1717 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1718 if (IsEH) { 1719 const MCExpr *offset = 1720 makeEndMinusStartExpr(context, cieStart, *fdeStart, 0); 1721 emitAbsValue(Streamer, offset, OffsetSize); 1722 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) { 1723 const MCExpr *offset = 1724 makeEndMinusStartExpr(context, SectionStart, cieStart, 0); 1725 emitAbsValue(Streamer, offset, OffsetSize); 1726 } else { 1727 Streamer.emitSymbolValue(&cieStart, OffsetSize, 1728 asmInfo->needsDwarfSectionOffsetDirective()); 1729 } 1730 1731 // PC Begin 1732 unsigned PCEncoding = 1733 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr; 1734 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding); 1735 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH); 1736 1737 // PC Range 1738 const MCExpr *Range = 1739 makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0); 1740 emitAbsValue(Streamer, Range, PCSize); 1741 1742 if (IsEH) { 1743 // Augmentation Data Length 1744 unsigned augmentationLength = 0; 1745 1746 if (frame.Lsda) 1747 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding); 1748 1749 Streamer.emitULEB128IntValue(augmentationLength); 1750 1751 // Augmentation Data 1752 if (frame.Lsda) 1753 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true); 1754 } 1755 1756 // Call Frame Instructions 1757 emitCFIInstructions(frame.Instructions, frame.Begin); 1758 1759 // Padding 1760 // The size of a .eh_frame section has to be a multiple of the alignment 1761 // since a null CIE is interpreted as the end. Old systems overaligned 1762 // .eh_frame, so we do too and account for it in the last FDE. 1763 unsigned Alignment = LastInSection ? asmInfo->getCodePointerSize() : PCSize; 1764 Streamer.emitValueToAlignment(Align(Alignment)); 1765 1766 Streamer.emitLabel(fdeEnd); 1767 } 1768 1769 namespace { 1770 1771 struct CIEKey { 1772 static const CIEKey getEmptyKey() { 1773 return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX), 1774 false, false); 1775 } 1776 1777 static const CIEKey getTombstoneKey() { 1778 return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX), 1779 false, false); 1780 } 1781 1782 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding, 1783 unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple, 1784 unsigned RAReg, bool IsBKeyFrame, bool IsMTETaggedFrame) 1785 : Personality(Personality), PersonalityEncoding(PersonalityEncoding), 1786 LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame), 1787 IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame), 1788 IsMTETaggedFrame(IsMTETaggedFrame) {} 1789 1790 explicit CIEKey(const MCDwarfFrameInfo &Frame) 1791 : Personality(Frame.Personality), 1792 PersonalityEncoding(Frame.PersonalityEncoding), 1793 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame), 1794 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg), 1795 IsBKeyFrame(Frame.IsBKeyFrame), 1796 IsMTETaggedFrame(Frame.IsMTETaggedFrame) {} 1797 1798 StringRef PersonalityName() const { 1799 if (!Personality) 1800 return StringRef(); 1801 return Personality->getName(); 1802 } 1803 1804 bool operator<(const CIEKey &Other) const { 1805 return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding, 1806 IsSignalFrame, IsSimple, RAReg, IsBKeyFrame, 1807 IsMTETaggedFrame) < 1808 std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding, 1809 Other.LsdaEncoding, Other.IsSignalFrame, 1810 Other.IsSimple, Other.RAReg, Other.IsBKeyFrame, 1811 Other.IsMTETaggedFrame); 1812 } 1813 1814 const MCSymbol *Personality; 1815 unsigned PersonalityEncoding; 1816 unsigned LsdaEncoding; 1817 bool IsSignalFrame; 1818 bool IsSimple; 1819 unsigned RAReg; 1820 bool IsBKeyFrame; 1821 bool IsMTETaggedFrame; 1822 }; 1823 1824 } // end anonymous namespace 1825 1826 namespace llvm { 1827 1828 template <> struct DenseMapInfo<CIEKey> { 1829 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); } 1830 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); } 1831 1832 static unsigned getHashValue(const CIEKey &Key) { 1833 return static_cast<unsigned>( 1834 hash_combine(Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding, 1835 Key.IsSignalFrame, Key.IsSimple, Key.RAReg, 1836 Key.IsBKeyFrame, Key.IsMTETaggedFrame)); 1837 } 1838 1839 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) { 1840 return LHS.Personality == RHS.Personality && 1841 LHS.PersonalityEncoding == RHS.PersonalityEncoding && 1842 LHS.LsdaEncoding == RHS.LsdaEncoding && 1843 LHS.IsSignalFrame == RHS.IsSignalFrame && 1844 LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg && 1845 LHS.IsBKeyFrame == RHS.IsBKeyFrame && 1846 LHS.IsMTETaggedFrame == RHS.IsMTETaggedFrame; 1847 } 1848 }; 1849 1850 } // end namespace llvm 1851 1852 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB, 1853 bool IsEH) { 1854 MCContext &Context = Streamer.getContext(); 1855 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1856 const MCAsmInfo *AsmInfo = Context.getAsmInfo(); 1857 FrameEmitterImpl Emitter(IsEH, Streamer); 1858 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos(); 1859 1860 // Emit the compact unwind info if available. 1861 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame(); 1862 if (IsEH && MOFI->getCompactUnwindSection()) { 1863 Streamer.generateCompactUnwindEncodings(MAB); 1864 bool SectionEmitted = false; 1865 for (const MCDwarfFrameInfo &Frame : FrameArray) { 1866 if (Frame.CompactUnwindEncoding == 0) continue; 1867 if (!SectionEmitted) { 1868 Streamer.switchSection(MOFI->getCompactUnwindSection()); 1869 Streamer.emitValueToAlignment(Align(AsmInfo->getCodePointerSize())); 1870 SectionEmitted = true; 1871 } 1872 NeedsEHFrameSection |= 1873 Frame.CompactUnwindEncoding == 1874 MOFI->getCompactUnwindDwarfEHFrameOnly(); 1875 Emitter.EmitCompactUnwind(Frame); 1876 } 1877 } 1878 1879 if (!NeedsEHFrameSection) return; 1880 1881 MCSection &Section = 1882 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection() 1883 : *MOFI->getDwarfFrameSection(); 1884 1885 Streamer.switchSection(&Section); 1886 MCSymbol *SectionStart = Context.createTempSymbol(); 1887 Streamer.emitLabel(SectionStart); 1888 1889 DenseMap<CIEKey, const MCSymbol *> CIEStarts; 1890 1891 const MCSymbol *DummyDebugKey = nullptr; 1892 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind(); 1893 // Sort the FDEs by their corresponding CIE before we emit them. 1894 // This isn't technically necessary according to the DWARF standard, 1895 // but the Android libunwindstack rejects eh_frame sections where 1896 // an FDE refers to a CIE other than the closest previous CIE. 1897 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end()); 1898 llvm::stable_sort(FrameArrayX, 1899 [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) { 1900 return CIEKey(X) < CIEKey(Y); 1901 }); 1902 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) { 1903 const MCDwarfFrameInfo &Frame = *I; 1904 ++I; 1905 if (CanOmitDwarf && Frame.CompactUnwindEncoding != 1906 MOFI->getCompactUnwindDwarfEHFrameOnly()) 1907 // Don't generate an EH frame if we don't need one. I.e., it's taken care 1908 // of by the compact unwind encoding. 1909 continue; 1910 1911 CIEKey Key(Frame); 1912 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; 1913 if (!CIEStart) 1914 CIEStart = &Emitter.EmitCIE(Frame); 1915 1916 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart); 1917 } 1918 } 1919 1920 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer, 1921 uint64_t AddrDelta) { 1922 MCContext &Context = Streamer.getContext(); 1923 SmallString<256> Tmp; 1924 raw_svector_ostream OS(Tmp); 1925 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS); 1926 Streamer.emitBytes(OS.str()); 1927 } 1928 1929 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context, 1930 uint64_t AddrDelta, 1931 raw_ostream &OS) { 1932 // Scale the address delta by the minimum instruction length. 1933 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 1934 if (AddrDelta == 0) 1935 return; 1936 1937 support::endianness E = 1938 Context.getAsmInfo()->isLittleEndian() ? support::little : support::big; 1939 1940 if (isUIntN(6, AddrDelta)) { 1941 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; 1942 OS << Opcode; 1943 } else if (isUInt<8>(AddrDelta)) { 1944 OS << uint8_t(dwarf::DW_CFA_advance_loc1); 1945 OS << uint8_t(AddrDelta); 1946 } else if (isUInt<16>(AddrDelta)) { 1947 OS << uint8_t(dwarf::DW_CFA_advance_loc2); 1948 support::endian::write<uint16_t>(OS, AddrDelta, E); 1949 } else { 1950 assert(isUInt<32>(AddrDelta)); 1951 OS << uint8_t(dwarf::DW_CFA_advance_loc4); 1952 support::endian::write<uint32_t>(OS, AddrDelta, E); 1953 } 1954 } 1955