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