1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/MC/MCDwarf.h" 11 #include "llvm/ADT/Hashing.h" 12 #include "llvm/ADT/STLExtras.h" 13 #include "llvm/ADT/SmallString.h" 14 #include "llvm/ADT/Twine.h" 15 #include "llvm/Config/config.h" 16 #include "llvm/MC/MCAsmInfo.h" 17 #include "llvm/MC/MCContext.h" 18 #include "llvm/MC/MCExpr.h" 19 #include "llvm/MC/MCObjectFileInfo.h" 20 #include "llvm/MC/MCObjectStreamer.h" 21 #include "llvm/MC/MCRegisterInfo.h" 22 #include "llvm/MC/MCSection.h" 23 #include "llvm/MC/MCSymbol.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/LEB128.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/SourceMgr.h" 29 #include "llvm/Support/raw_ostream.h" 30 31 using namespace llvm; 32 33 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) { 34 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment(); 35 if (MinInsnLength == 1) 36 return AddrDelta; 37 if (AddrDelta % MinInsnLength != 0) { 38 // TODO: report this error, but really only once. 39 ; 40 } 41 return AddrDelta / MinInsnLength; 42 } 43 44 // 45 // This is called when an instruction is assembled into the specified section 46 // and if there is information from the last .loc directive that has yet to have 47 // a line entry made for it is made. 48 // 49 void MCDwarfLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) { 50 if (!MCOS->getContext().getDwarfLocSeen()) 51 return; 52 53 // Create a symbol at in the current section for use in the line entry. 54 MCSymbol *LineSym = MCOS->getContext().createTempSymbol(); 55 // Set the value of the symbol to use for the MCDwarfLineEntry. 56 MCOS->EmitLabel(LineSym); 57 58 // Get the current .loc info saved in the context. 59 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); 60 61 // Create a (local) line entry with the symbol and the current .loc info. 62 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc); 63 64 // clear DwarfLocSeen saying the current .loc info is now used. 65 MCOS->getContext().clearDwarfLocSeen(); 66 67 // Add the line entry to this section's entries. 68 MCOS->getContext() 69 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID()) 70 .getMCLineSections() 71 .addLineEntry(LineEntry, Section); 72 } 73 74 // 75 // This helper routine returns an expression of End - Start + IntVal . 76 // 77 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS, 78 const MCSymbol &Start, 79 const MCSymbol &End, 80 int IntVal) { 81 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 82 const MCExpr *Res = 83 MCSymbolRefExpr::create(&End, Variant, MCOS.getContext()); 84 const MCExpr *RHS = 85 MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext()); 86 const MCExpr *Res1 = 87 MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext()); 88 const MCExpr *Res2 = 89 MCConstantExpr::create(IntVal, MCOS.getContext()); 90 const MCExpr *Res3 = 91 MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext()); 92 return Res3; 93 } 94 95 // 96 // This emits the Dwarf line table for the specified section from the entries 97 // in the LineSection. 98 // 99 static inline void 100 EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section, 101 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) { 102 unsigned FileNum = 1; 103 unsigned LastLine = 1; 104 unsigned Column = 0; 105 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 106 unsigned Isa = 0; 107 unsigned Discriminator = 0; 108 MCSymbol *LastLabel = nullptr; 109 110 // Loop through each MCDwarfLineEntry and encode the dwarf line number table. 111 for (auto it = LineEntries.begin(), 112 ie = LineEntries.end(); 113 it != ie; ++it) { 114 115 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine; 116 117 // Discriminator will be cleared if there is line change. 118 if (LineDelta != 0) 119 Discriminator = 0; 120 121 if (FileNum != it->getFileNum()) { 122 FileNum = it->getFileNum(); 123 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1); 124 MCOS->EmitULEB128IntValue(FileNum); 125 } 126 if (Column != it->getColumn()) { 127 Column = it->getColumn(); 128 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1); 129 MCOS->EmitULEB128IntValue(Column); 130 } 131 if (Discriminator != it->getDiscriminator()) { 132 Discriminator = it->getDiscriminator(); 133 unsigned Size = getULEB128Size(Discriminator); 134 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1); 135 MCOS->EmitULEB128IntValue(Size + 1); 136 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1); 137 MCOS->EmitULEB128IntValue(Discriminator); 138 } 139 if (Isa != it->getIsa()) { 140 Isa = it->getIsa(); 141 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1); 142 MCOS->EmitULEB128IntValue(Isa); 143 } 144 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 145 Flags = it->getFlags(); 146 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1); 147 } 148 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK) 149 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1); 150 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END) 151 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1); 152 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 153 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); 154 155 MCSymbol *Label = it->getLabel(); 156 157 // At this point we want to emit/create the sequence to encode the delta in 158 // line numbers and the increment of the address from the previous Label 159 // and the current Label. 160 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo(); 161 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 162 asmInfo->getPointerSize()); 163 164 LastLine = it->getLine(); 165 LastLabel = Label; 166 } 167 168 // Emit a DW_LNE_end_sequence for the end of the section. 169 // Use the section end label to compute the address delta and use INT64_MAX 170 // as the line delta which is the signal that this is actually a 171 // DW_LNE_end_sequence. 172 MCSymbol *SectionEnd = MCOS->endSection(Section); 173 174 // Switch back the dwarf line section, in case endSection had to switch the 175 // section. 176 MCContext &Ctx = MCOS->getContext(); 177 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection()); 178 179 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo(); 180 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd, 181 AsmInfo->getPointerSize()); 182 } 183 184 // 185 // This emits the Dwarf file and the line tables. 186 // 187 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS, 188 MCDwarfLineTableParams Params) { 189 MCContext &context = MCOS->getContext(); 190 191 auto &LineTables = context.getMCDwarfLineTables(); 192 193 // Bail out early so we don't switch to the debug_line section needlessly and 194 // in doing so create an unnecessary (if empty) section. 195 if (LineTables.empty()) 196 return; 197 198 // Switch to the section where the table will be emitted into. 199 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); 200 201 // Handle the rest of the Compile Units. 202 for (const auto &CUIDTablePair : LineTables) 203 CUIDTablePair.second.EmitCU(MCOS, Params); 204 } 205 206 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, 207 MCDwarfLineTableParams Params) const { 208 MCOS.EmitLabel(Header.Emit(&MCOS, Params, None).second); 209 } 210 211 std::pair<MCSymbol *, MCSymbol *> 212 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, 213 MCDwarfLineTableParams Params) const { 214 static const char StandardOpcodeLengths[] = { 215 0, // length of DW_LNS_copy 216 1, // length of DW_LNS_advance_pc 217 1, // length of DW_LNS_advance_line 218 1, // length of DW_LNS_set_file 219 1, // length of DW_LNS_set_column 220 0, // length of DW_LNS_negate_stmt 221 0, // length of DW_LNS_set_basic_block 222 0, // length of DW_LNS_const_add_pc 223 1, // length of DW_LNS_fixed_advance_pc 224 0, // length of DW_LNS_set_prologue_end 225 0, // length of DW_LNS_set_epilogue_begin 226 1 // DW_LNS_set_isa 227 }; 228 assert(array_lengthof(StandardOpcodeLengths) >= 229 (Params.DWARF2LineOpcodeBase - 1U)); 230 return Emit(MCOS, Params, makeArrayRef(StandardOpcodeLengths, 231 Params.DWARF2LineOpcodeBase - 1)); 232 } 233 234 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) { 235 MCContext &Context = OS.getContext(); 236 assert(!isa<MCSymbolRefExpr>(Expr)); 237 if (Context.getAsmInfo()->hasAggressiveSymbolFolding()) 238 return Expr; 239 240 MCSymbol *ABS = Context.createTempSymbol(); 241 OS.EmitAssignment(ABS, Expr); 242 return MCSymbolRefExpr::create(ABS, Context); 243 } 244 245 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) { 246 const MCExpr *ABS = forceExpAbs(OS, Value); 247 OS.EmitValue(ABS, Size); 248 } 249 250 std::pair<MCSymbol *, MCSymbol *> 251 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 252 ArrayRef<char> StandardOpcodeLengths) const { 253 MCContext &context = MCOS->getContext(); 254 255 // Create a symbol at the beginning of the line table. 256 MCSymbol *LineStartSym = Label; 257 if (!LineStartSym) 258 LineStartSym = context.createTempSymbol(); 259 // Set the value of the symbol, as we are at the start of the line table. 260 MCOS->EmitLabel(LineStartSym); 261 262 // Create a symbol for the end of the section (to be set when we get there). 263 MCSymbol *LineEndSym = context.createTempSymbol(); 264 265 // The first 4 bytes is the total length of the information for this 266 // compilation unit (not including these 4 bytes for the length). 267 emitAbsValue(*MCOS, 268 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4); 269 270 // Next 2 bytes is the Version, which is Dwarf 2. 271 MCOS->EmitIntValue(2, 2); 272 273 // Create a symbol for the end of the prologue (to be set when we get there). 274 MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end 275 276 // Length of the prologue, is the next 4 bytes. Which is the start of the 277 // section to the end of the prologue. Not including the 4 bytes for the 278 // total length, the 2 bytes for the version, and these 4 bytes for the 279 // length of the prologue. 280 emitAbsValue( 281 *MCOS, 282 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4); 283 284 // Parameters of the state machine, are next. 285 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1); 286 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1); 287 MCOS->EmitIntValue(Params.DWARF2LineBase, 1); 288 MCOS->EmitIntValue(Params.DWARF2LineRange, 1); 289 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1); 290 291 // Standard opcode lengths 292 for (char Length : StandardOpcodeLengths) 293 MCOS->EmitIntValue(Length, 1); 294 295 // Put out the directory and file tables. 296 297 // First the directory table. 298 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) { 299 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName 300 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string 301 } 302 MCOS->EmitIntValue(0, 1); // Terminate the directory list 303 304 // Second the file table. 305 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { 306 assert(!MCDwarfFiles[i].Name.empty()); 307 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName 308 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string 309 // the Directory num 310 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex); 311 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0) 312 MCOS->EmitIntValue(0, 1); // filesize (always 0) 313 } 314 MCOS->EmitIntValue(0, 1); // Terminate the file list 315 316 // This is the end of the prologue, so set the value of the symbol at the 317 // end of the prologue (that was used in a previous expression). 318 MCOS->EmitLabel(ProEndSym); 319 320 return std::make_pair(LineStartSym, LineEndSym); 321 } 322 323 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS, 324 MCDwarfLineTableParams Params) const { 325 MCSymbol *LineEndSym = Header.Emit(MCOS, Params).second; 326 327 // Put out the line tables. 328 for (const auto &LineSec : MCLineSections.getMCLineEntries()) 329 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second); 330 331 // This is the end of the section, so set the value of the symbol at the end 332 // of this section (that was used in a previous expression). 333 MCOS->EmitLabel(LineEndSym); 334 } 335 336 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName, 337 unsigned FileNumber) { 338 return Header.getFile(Directory, FileName, FileNumber); 339 } 340 341 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory, 342 StringRef &FileName, 343 unsigned FileNumber) { 344 if (Directory == CompilationDir) 345 Directory = ""; 346 if (FileName.empty()) { 347 FileName = "<stdin>"; 348 Directory = ""; 349 } 350 assert(!FileName.empty()); 351 if (FileNumber == 0) { 352 // File numbers start with 1 and/or after any file numbers 353 // allocated by inline-assembler .file directives. 354 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size(); 355 SmallString<256> Buffer; 356 auto IterBool = SourceIdMap.insert( 357 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer), 358 FileNumber)); 359 if (!IterBool.second) 360 return IterBool.first->second; 361 } 362 // Make space for this FileNumber in the MCDwarfFiles vector if needed. 363 MCDwarfFiles.resize(FileNumber + 1); 364 365 // Get the new MCDwarfFile slot for this FileNumber. 366 MCDwarfFile &File = MCDwarfFiles[FileNumber]; 367 368 // It is an error to use see the same number more than once. 369 if (!File.Name.empty()) 370 return 0; 371 372 if (Directory.empty()) { 373 // Separate the directory part from the basename of the FileName. 374 StringRef tFileName = sys::path::filename(FileName); 375 if (!tFileName.empty()) { 376 Directory = sys::path::parent_path(FileName); 377 if (!Directory.empty()) 378 FileName = tFileName; 379 } 380 } 381 382 // Find or make an entry in the MCDwarfDirs vector for this Directory. 383 // Capture directory name. 384 unsigned DirIndex; 385 if (Directory.empty()) { 386 // For FileNames with no directories a DirIndex of 0 is used. 387 DirIndex = 0; 388 } else { 389 DirIndex = 0; 390 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) { 391 if (Directory == MCDwarfDirs[DirIndex]) 392 break; 393 } 394 if (DirIndex >= MCDwarfDirs.size()) 395 MCDwarfDirs.push_back(Directory); 396 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with 397 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the 398 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames 399 // are stored at MCDwarfFiles[FileNumber].Name . 400 DirIndex++; 401 } 402 403 File.Name = FileName; 404 File.DirIndex = DirIndex; 405 406 // return the allocated FileNumber. 407 return FileNumber; 408 } 409 410 /// Utility function to emit the encoding to a streamer. 411 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 412 int64_t LineDelta, uint64_t AddrDelta) { 413 MCContext &Context = MCOS->getContext(); 414 SmallString<256> Tmp; 415 raw_svector_ostream OS(Tmp); 416 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS); 417 MCOS->EmitBytes(OS.str()); 418 } 419 420 /// Given a special op, return the address skip amount (in units of 421 /// DWARF2_LINE_MIN_INSN_LENGTH). 422 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) { 423 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange; 424 } 425 426 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. 427 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params, 428 int64_t LineDelta, uint64_t AddrDelta, 429 raw_ostream &OS) { 430 uint64_t Temp, Opcode; 431 bool NeedCopy = false; 432 433 // The maximum address skip amount that can be encoded with a special op. 434 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255); 435 436 // Scale the address delta by the minimum instruction length. 437 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 438 439 // A LineDelta of INT64_MAX is a signal that this is actually a 440 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 441 // end_sequence to emit the matrix entry. 442 if (LineDelta == INT64_MAX) { 443 if (AddrDelta == MaxSpecialAddrDelta) 444 OS << char(dwarf::DW_LNS_const_add_pc); 445 else if (AddrDelta) { 446 OS << char(dwarf::DW_LNS_advance_pc); 447 encodeULEB128(AddrDelta, OS); 448 } 449 OS << char(dwarf::DW_LNS_extended_op); 450 OS << char(1); 451 OS << char(dwarf::DW_LNE_end_sequence); 452 return; 453 } 454 455 // Bias the line delta by the base. 456 Temp = LineDelta - Params.DWARF2LineBase; 457 458 // If the line increment is out of range of a special opcode, we must encode 459 // it with DW_LNS_advance_line. 460 if (Temp >= Params.DWARF2LineRange || 461 Temp + Params.DWARF2LineOpcodeBase > 255) { 462 OS << char(dwarf::DW_LNS_advance_line); 463 encodeSLEB128(LineDelta, OS); 464 465 LineDelta = 0; 466 Temp = 0 - Params.DWARF2LineBase; 467 NeedCopy = true; 468 } 469 470 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. 471 if (LineDelta == 0 && AddrDelta == 0) { 472 OS << char(dwarf::DW_LNS_copy); 473 return; 474 } 475 476 // Bias the opcode by the special opcode base. 477 Temp += Params.DWARF2LineOpcodeBase; 478 479 // Avoid overflow when addr_delta is large. 480 if (AddrDelta < 256 + MaxSpecialAddrDelta) { 481 // Try using a special opcode. 482 Opcode = Temp + AddrDelta * Params.DWARF2LineRange; 483 if (Opcode <= 255) { 484 OS << char(Opcode); 485 return; 486 } 487 488 // Try using DW_LNS_const_add_pc followed by special op. 489 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange; 490 if (Opcode <= 255) { 491 OS << char(dwarf::DW_LNS_const_add_pc); 492 OS << char(Opcode); 493 return; 494 } 495 } 496 497 // Otherwise use DW_LNS_advance_pc. 498 OS << char(dwarf::DW_LNS_advance_pc); 499 encodeULEB128(AddrDelta, OS); 500 501 if (NeedCopy) 502 OS << char(dwarf::DW_LNS_copy); 503 else { 504 assert(Temp <= 255 && "Buggy special opcode encoding."); 505 OS << char(Temp); 506 } 507 } 508 509 // Utility function to write a tuple for .debug_abbrev. 510 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { 511 MCOS->EmitULEB128IntValue(Name); 512 MCOS->EmitULEB128IntValue(Form); 513 } 514 515 // When generating dwarf for assembly source files this emits 516 // the data for .debug_abbrev section which contains three DIEs. 517 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { 518 MCContext &context = MCOS->getContext(); 519 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 520 521 // DW_TAG_compile_unit DIE abbrev (1). 522 MCOS->EmitULEB128IntValue(1); 523 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit); 524 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); 525 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, context.getDwarfVersion() >= 4 526 ? dwarf::DW_FORM_sec_offset 527 : dwarf::DW_FORM_data4); 528 if (context.getGenDwarfSectionSyms().size() > 1 && 529 context.getDwarfVersion() >= 3) { 530 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, context.getDwarfVersion() >= 4 531 ? dwarf::DW_FORM_sec_offset 532 : dwarf::DW_FORM_data4); 533 } else { 534 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 535 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); 536 } 537 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 538 if (!context.getCompilationDir().empty()) 539 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); 540 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 541 if (!DwarfDebugFlags.empty()) 542 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); 543 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); 544 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); 545 EmitAbbrev(MCOS, 0, 0); 546 547 // DW_TAG_label DIE abbrev (2). 548 MCOS->EmitULEB128IntValue(2); 549 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label); 550 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); 551 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 552 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); 553 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); 554 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 555 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag); 556 EmitAbbrev(MCOS, 0, 0); 557 558 // DW_TAG_unspecified_parameters DIE abbrev (3). 559 MCOS->EmitULEB128IntValue(3); 560 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters); 561 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1); 562 EmitAbbrev(MCOS, 0, 0); 563 564 // Terminate the abbreviations for this compilation unit. 565 MCOS->EmitIntValue(0, 1); 566 } 567 568 // When generating dwarf for assembly source files this emits the data for 569 // .debug_aranges section. This section contains a header and a table of pairs 570 // of PointerSize'ed values for the address and size of section(s) with line 571 // table entries. 572 static void EmitGenDwarfAranges(MCStreamer *MCOS, 573 const MCSymbol *InfoSectionSymbol) { 574 MCContext &context = MCOS->getContext(); 575 576 auto &Sections = context.getGenDwarfSectionSyms(); 577 578 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 579 580 // This will be the length of the .debug_aranges section, first account for 581 // the size of each item in the header (see below where we emit these items). 582 int Length = 4 + 2 + 4 + 1 + 1; 583 584 // Figure the padding after the header before the table of address and size 585 // pairs who's values are PointerSize'ed. 586 const MCAsmInfo *asmInfo = context.getAsmInfo(); 587 int AddrSize = asmInfo->getPointerSize(); 588 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); 589 if (Pad == 2 * AddrSize) 590 Pad = 0; 591 Length += Pad; 592 593 // Add the size of the pair of PointerSize'ed values for the address and size 594 // of each section we have in the table. 595 Length += 2 * AddrSize * Sections.size(); 596 // And the pair of terminating zeros. 597 Length += 2 * AddrSize; 598 599 600 // Emit the header for this section. 601 // The 4 byte length not including the 4 byte value for the length. 602 MCOS->EmitIntValue(Length - 4, 4); 603 // The 2 byte version, which is 2. 604 MCOS->EmitIntValue(2, 2); 605 // The 4 byte offset to the compile unit in the .debug_info from the start 606 // of the .debug_info. 607 if (InfoSectionSymbol) 608 MCOS->EmitSymbolValue(InfoSectionSymbol, 4, 609 asmInfo->needsDwarfSectionOffsetDirective()); 610 else 611 MCOS->EmitIntValue(0, 4); 612 // The 1 byte size of an address. 613 MCOS->EmitIntValue(AddrSize, 1); 614 // The 1 byte size of a segment descriptor, we use a value of zero. 615 MCOS->EmitIntValue(0, 1); 616 // Align the header with the padding if needed, before we put out the table. 617 for(int i = 0; i < Pad; i++) 618 MCOS->EmitIntValue(0, 1); 619 620 // Now emit the table of pairs of PointerSize'ed values for the section 621 // addresses and sizes. 622 for (MCSection *Sec : Sections) { 623 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 624 MCSymbol *EndSymbol = Sec->getEndSymbol(context); 625 assert(StartSymbol && "StartSymbol must not be NULL"); 626 assert(EndSymbol && "EndSymbol must not be NULL"); 627 628 const MCExpr *Addr = MCSymbolRefExpr::create( 629 StartSymbol, MCSymbolRefExpr::VK_None, context); 630 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS, 631 *StartSymbol, *EndSymbol, 0); 632 MCOS->EmitValue(Addr, AddrSize); 633 emitAbsValue(*MCOS, Size, AddrSize); 634 } 635 636 // And finally the pair of terminating zeros. 637 MCOS->EmitIntValue(0, AddrSize); 638 MCOS->EmitIntValue(0, AddrSize); 639 } 640 641 // When generating dwarf for assembly source files this emits the data for 642 // .debug_info section which contains three parts. The header, the compile_unit 643 // DIE and a list of label DIEs. 644 static void EmitGenDwarfInfo(MCStreamer *MCOS, 645 const MCSymbol *AbbrevSectionSymbol, 646 const MCSymbol *LineSectionSymbol, 647 const MCSymbol *RangesSectionSymbol) { 648 MCContext &context = MCOS->getContext(); 649 650 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 651 652 // Create a symbol at the start and end of this section used in here for the 653 // expression to calculate the length in the header. 654 MCSymbol *InfoStart = context.createTempSymbol(); 655 MCOS->EmitLabel(InfoStart); 656 MCSymbol *InfoEnd = context.createTempSymbol(); 657 658 // First part: the header. 659 660 // The 4 byte total length of the information for this compilation unit, not 661 // including these 4 bytes. 662 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4); 663 emitAbsValue(*MCOS, Length, 4); 664 665 // The 2 byte DWARF version. 666 MCOS->EmitIntValue(context.getDwarfVersion(), 2); 667 668 const MCAsmInfo &AsmInfo = *context.getAsmInfo(); 669 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev, 670 // it is at the start of that section so this is zero. 671 if (AbbrevSectionSymbol == nullptr) 672 MCOS->EmitIntValue(0, 4); 673 else 674 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4, 675 AsmInfo.needsDwarfSectionOffsetDirective()); 676 677 const MCAsmInfo *asmInfo = context.getAsmInfo(); 678 int AddrSize = asmInfo->getPointerSize(); 679 // The 1 byte size of an address. 680 MCOS->EmitIntValue(AddrSize, 1); 681 682 // Second part: the compile_unit DIE. 683 684 // The DW_TAG_compile_unit DIE abbrev (1). 685 MCOS->EmitULEB128IntValue(1); 686 687 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section, 688 // which is at the start of that section so this is zero. 689 if (LineSectionSymbol) 690 MCOS->EmitSymbolValue(LineSectionSymbol, 4, 691 AsmInfo.needsDwarfSectionOffsetDirective()); 692 else 693 MCOS->EmitIntValue(0, 4); 694 695 if (RangesSectionSymbol) { 696 // There are multiple sections containing code, so we must use the 697 // .debug_ranges sections. 698 699 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section 700 // to the address range list for this compilation unit. 701 MCOS->EmitSymbolValue(RangesSectionSymbol, 4); 702 } else { 703 // If we only have one non-empty code section, we can use the simpler 704 // AT_low_pc and AT_high_pc attributes. 705 706 // Find the first (and only) non-empty text section 707 auto &Sections = context.getGenDwarfSectionSyms(); 708 const auto TextSection = Sections.begin(); 709 assert(TextSection != Sections.end() && "No text section found"); 710 711 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol(); 712 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context); 713 assert(StartSymbol && "StartSymbol must not be NULL"); 714 assert(EndSymbol && "EndSymbol must not be NULL"); 715 716 // AT_low_pc, the first address of the default .text section. 717 const MCExpr *Start = MCSymbolRefExpr::create( 718 StartSymbol, MCSymbolRefExpr::VK_None, context); 719 MCOS->EmitValue(Start, AddrSize); 720 721 // AT_high_pc, the last address of the default .text section. 722 const MCExpr *End = MCSymbolRefExpr::create( 723 EndSymbol, MCSymbolRefExpr::VK_None, context); 724 MCOS->EmitValue(End, AddrSize); 725 } 726 727 // AT_name, the name of the source file. Reconstruct from the first directory 728 // and file table entries. 729 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs(); 730 if (MCDwarfDirs.size() > 0) { 731 MCOS->EmitBytes(MCDwarfDirs[0]); 732 MCOS->EmitBytes(sys::path::get_separator()); 733 } 734 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = 735 MCOS->getContext().getMCDwarfFiles(); 736 MCOS->EmitBytes(MCDwarfFiles[1].Name); 737 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 738 739 // AT_comp_dir, the working directory the assembly was done in. 740 if (!context.getCompilationDir().empty()) { 741 MCOS->EmitBytes(context.getCompilationDir()); 742 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 743 } 744 745 // AT_APPLE_flags, the command line arguments of the assembler tool. 746 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 747 if (!DwarfDebugFlags.empty()){ 748 MCOS->EmitBytes(DwarfDebugFlags); 749 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 750 } 751 752 // AT_producer, the version of the assembler tool. 753 StringRef DwarfDebugProducer = context.getDwarfDebugProducer(); 754 if (!DwarfDebugProducer.empty()) 755 MCOS->EmitBytes(DwarfDebugProducer); 756 else 757 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")")); 758 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 759 760 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 761 // draft has no standard code for assembler. 762 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2); 763 764 // Third part: the list of label DIEs. 765 766 // Loop on saved info for dwarf labels and create the DIEs for them. 767 const std::vector<MCGenDwarfLabelEntry> &Entries = 768 MCOS->getContext().getMCGenDwarfLabelEntries(); 769 for (const auto &Entry : Entries) { 770 // The DW_TAG_label DIE abbrev (2). 771 MCOS->EmitULEB128IntValue(2); 772 773 // AT_name, of the label without any leading underbar. 774 MCOS->EmitBytes(Entry.getName()); 775 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 776 777 // AT_decl_file, index into the file table. 778 MCOS->EmitIntValue(Entry.getFileNumber(), 4); 779 780 // AT_decl_line, source line number. 781 MCOS->EmitIntValue(Entry.getLineNumber(), 4); 782 783 // AT_low_pc, start address of the label. 784 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(), 785 MCSymbolRefExpr::VK_None, context); 786 MCOS->EmitValue(AT_low_pc, AddrSize); 787 788 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype. 789 MCOS->EmitIntValue(0, 1); 790 791 // The DW_TAG_unspecified_parameters DIE abbrev (3). 792 MCOS->EmitULEB128IntValue(3); 793 794 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's. 795 MCOS->EmitIntValue(0, 1); 796 } 797 798 // Add the NULL DIE terminating the Compile Unit DIE's. 799 MCOS->EmitIntValue(0, 1); 800 801 // Now set the value of the symbol at the end of the info section. 802 MCOS->EmitLabel(InfoEnd); 803 } 804 805 // When generating dwarf for assembly source files this emits the data for 806 // .debug_ranges section. We only emit one range list, which spans all of the 807 // executable sections of this file. 808 static void EmitGenDwarfRanges(MCStreamer *MCOS) { 809 MCContext &context = MCOS->getContext(); 810 auto &Sections = context.getGenDwarfSectionSyms(); 811 812 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 813 int AddrSize = AsmInfo->getPointerSize(); 814 815 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection()); 816 817 for (MCSection *Sec : Sections) { 818 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 819 MCSymbol *EndSymbol = Sec->getEndSymbol(context); 820 assert(StartSymbol && "StartSymbol must not be NULL"); 821 assert(EndSymbol && "EndSymbol must not be NULL"); 822 823 // Emit a base address selection entry for the start of this section 824 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 825 StartSymbol, MCSymbolRefExpr::VK_None, context); 826 MCOS->EmitFill(AddrSize, 0xFF); 827 MCOS->EmitValue(SectionStartAddr, AddrSize); 828 829 // Emit a range list entry spanning this section 830 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS, 831 *StartSymbol, *EndSymbol, 0); 832 MCOS->EmitIntValue(0, AddrSize); 833 emitAbsValue(*MCOS, SectionSize, AddrSize); 834 } 835 836 // Emit end of list entry 837 MCOS->EmitIntValue(0, AddrSize); 838 MCOS->EmitIntValue(0, AddrSize); 839 } 840 841 // 842 // When generating dwarf for assembly source files this emits the Dwarf 843 // sections. 844 // 845 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) { 846 MCContext &context = MCOS->getContext(); 847 848 // Create the dwarf sections in this order (.debug_line already created). 849 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 850 bool CreateDwarfSectionSymbols = 851 AsmInfo->doesDwarfUseRelocationsAcrossSections(); 852 MCSymbol *LineSectionSymbol = nullptr; 853 if (CreateDwarfSectionSymbols) 854 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0); 855 MCSymbol *AbbrevSectionSymbol = nullptr; 856 MCSymbol *InfoSectionSymbol = nullptr; 857 MCSymbol *RangesSectionSymbol = nullptr; 858 859 // Create end symbols for each section, and remove empty sections 860 MCOS->getContext().finalizeDwarfSections(*MCOS); 861 862 // If there are no sections to generate debug info for, we don't need 863 // to do anything 864 if (MCOS->getContext().getGenDwarfSectionSyms().empty()) 865 return; 866 867 // We only use the .debug_ranges section if we have multiple code sections, 868 // and we are emitting a DWARF version which supports it. 869 const bool UseRangesSection = 870 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 && 871 MCOS->getContext().getDwarfVersion() >= 3; 872 CreateDwarfSectionSymbols |= UseRangesSection; 873 874 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 875 if (CreateDwarfSectionSymbols) { 876 InfoSectionSymbol = context.createTempSymbol(); 877 MCOS->EmitLabel(InfoSectionSymbol); 878 } 879 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 880 if (CreateDwarfSectionSymbols) { 881 AbbrevSectionSymbol = context.createTempSymbol(); 882 MCOS->EmitLabel(AbbrevSectionSymbol); 883 } 884 if (UseRangesSection) { 885 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection()); 886 if (CreateDwarfSectionSymbols) { 887 RangesSectionSymbol = context.createTempSymbol(); 888 MCOS->EmitLabel(RangesSectionSymbol); 889 } 890 } 891 892 assert((RangesSectionSymbol != NULL) || !UseRangesSection); 893 894 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 895 896 // Output the data for .debug_aranges section. 897 EmitGenDwarfAranges(MCOS, InfoSectionSymbol); 898 899 if (UseRangesSection) 900 EmitGenDwarfRanges(MCOS); 901 902 // Output the data for .debug_abbrev section. 903 EmitGenDwarfAbbrev(MCOS); 904 905 // Output the data for .debug_info section. 906 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, 907 RangesSectionSymbol); 908 } 909 910 // 911 // When generating dwarf for assembly source files this is called when symbol 912 // for a label is created. If this symbol is not a temporary and is in the 913 // section that dwarf is being generated for, save the needed info to create 914 // a dwarf label. 915 // 916 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, 917 SourceMgr &SrcMgr, SMLoc &Loc) { 918 // We won't create dwarf labels for temporary symbols. 919 if (Symbol->isTemporary()) 920 return; 921 MCContext &context = MCOS->getContext(); 922 // We won't create dwarf labels for symbols in sections that we are not 923 // generating debug info for. 924 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first)) 925 return; 926 927 // The dwarf label's name does not have the symbol name's leading 928 // underbar if any. 929 StringRef Name = Symbol->getName(); 930 if (Name.startswith("_")) 931 Name = Name.substr(1, Name.size()-1); 932 933 // Get the dwarf file number to be used for the dwarf label. 934 unsigned FileNumber = context.getGenDwarfFileNumber(); 935 936 // Finding the line number is the expensive part which is why we just don't 937 // pass it in as for some symbols we won't create a dwarf label. 938 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); 939 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); 940 941 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc 942 // values so that they don't have things like an ARM thumb bit from the 943 // original symbol. So when used they won't get a low bit set after 944 // relocation. 945 MCSymbol *Label = context.createTempSymbol(); 946 MCOS->EmitLabel(Label); 947 948 // Create and entry for the info and add it to the other entries. 949 MCOS->getContext().addMCGenDwarfLabelEntry( 950 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label)); 951 } 952 953 static int getDataAlignmentFactor(MCStreamer &streamer) { 954 MCContext &context = streamer.getContext(); 955 const MCAsmInfo *asmInfo = context.getAsmInfo(); 956 int size = asmInfo->getCalleeSaveStackSlotSize(); 957 if (asmInfo->isStackGrowthDirectionUp()) 958 return size; 959 else 960 return -size; 961 } 962 963 static unsigned getSizeForEncoding(MCStreamer &streamer, 964 unsigned symbolEncoding) { 965 MCContext &context = streamer.getContext(); 966 unsigned format = symbolEncoding & 0x0f; 967 switch (format) { 968 default: llvm_unreachable("Unknown Encoding"); 969 case dwarf::DW_EH_PE_absptr: 970 case dwarf::DW_EH_PE_signed: 971 return context.getAsmInfo()->getPointerSize(); 972 case dwarf::DW_EH_PE_udata2: 973 case dwarf::DW_EH_PE_sdata2: 974 return 2; 975 case dwarf::DW_EH_PE_udata4: 976 case dwarf::DW_EH_PE_sdata4: 977 return 4; 978 case dwarf::DW_EH_PE_udata8: 979 case dwarf::DW_EH_PE_sdata8: 980 return 8; 981 } 982 } 983 984 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol, 985 unsigned symbolEncoding, bool isEH) { 986 MCContext &context = streamer.getContext(); 987 const MCAsmInfo *asmInfo = context.getAsmInfo(); 988 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol, 989 symbolEncoding, 990 streamer); 991 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 992 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH) 993 emitAbsValue(streamer, v, size); 994 else 995 streamer.EmitValue(v, size); 996 } 997 998 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, 999 unsigned symbolEncoding) { 1000 MCContext &context = streamer.getContext(); 1001 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1002 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol, 1003 symbolEncoding, 1004 streamer); 1005 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1006 streamer.EmitValue(v, size); 1007 } 1008 1009 namespace { 1010 class FrameEmitterImpl { 1011 int CFAOffset = 0; 1012 int InitialCFAOffset = 0; 1013 bool IsEH; 1014 MCObjectStreamer &Streamer; 1015 1016 public: 1017 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer) 1018 : IsEH(IsEH), Streamer(Streamer) {} 1019 1020 /// Emit the unwind information in a compact way. 1021 void EmitCompactUnwind(const MCDwarfFrameInfo &frame); 1022 1023 const MCSymbol &EmitCIE(const MCSymbol *personality, 1024 unsigned personalityEncoding, const MCSymbol *lsda, 1025 bool IsSignalFrame, unsigned lsdaEncoding, 1026 bool IsSimple); 1027 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame, 1028 bool LastInSection, const MCSymbol &SectionStart); 1029 void EmitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1030 MCSymbol *BaseLabel); 1031 void EmitCFIInstruction(const MCCFIInstruction &Instr); 1032 }; 1033 1034 } // end anonymous namespace 1035 1036 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) { 1037 Streamer.EmitIntValue(Encoding, 1); 1038 } 1039 1040 void FrameEmitterImpl::EmitCFIInstruction(const MCCFIInstruction &Instr) { 1041 int dataAlignmentFactor = getDataAlignmentFactor(Streamer); 1042 auto *MRI = Streamer.getContext().getRegisterInfo(); 1043 1044 switch (Instr.getOperation()) { 1045 case MCCFIInstruction::OpRegister: { 1046 unsigned Reg1 = Instr.getRegister(); 1047 unsigned Reg2 = Instr.getRegister2(); 1048 if (!IsEH) { 1049 Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false); 1050 Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false); 1051 } 1052 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1); 1053 Streamer.EmitULEB128IntValue(Reg1); 1054 Streamer.EmitULEB128IntValue(Reg2); 1055 return; 1056 } 1057 case MCCFIInstruction::OpWindowSave: { 1058 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1); 1059 return; 1060 } 1061 case MCCFIInstruction::OpUndefined: { 1062 unsigned Reg = Instr.getRegister(); 1063 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1); 1064 Streamer.EmitULEB128IntValue(Reg); 1065 return; 1066 } 1067 case MCCFIInstruction::OpAdjustCfaOffset: 1068 case MCCFIInstruction::OpDefCfaOffset: { 1069 const bool IsRelative = 1070 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset; 1071 1072 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1); 1073 1074 if (IsRelative) 1075 CFAOffset += Instr.getOffset(); 1076 else 1077 CFAOffset = -Instr.getOffset(); 1078 1079 Streamer.EmitULEB128IntValue(CFAOffset); 1080 1081 return; 1082 } 1083 case MCCFIInstruction::OpDefCfa: { 1084 unsigned Reg = Instr.getRegister(); 1085 if (!IsEH) 1086 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false); 1087 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1); 1088 Streamer.EmitULEB128IntValue(Reg); 1089 CFAOffset = -Instr.getOffset(); 1090 Streamer.EmitULEB128IntValue(CFAOffset); 1091 1092 return; 1093 } 1094 1095 case MCCFIInstruction::OpDefCfaRegister: { 1096 unsigned Reg = Instr.getRegister(); 1097 if (!IsEH) 1098 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false); 1099 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1); 1100 Streamer.EmitULEB128IntValue(Reg); 1101 1102 return; 1103 } 1104 1105 case MCCFIInstruction::OpOffset: 1106 case MCCFIInstruction::OpRelOffset: { 1107 const bool IsRelative = 1108 Instr.getOperation() == MCCFIInstruction::OpRelOffset; 1109 1110 unsigned Reg = Instr.getRegister(); 1111 if (!IsEH) 1112 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false); 1113 1114 int Offset = Instr.getOffset(); 1115 if (IsRelative) 1116 Offset -= CFAOffset; 1117 Offset = Offset / dataAlignmentFactor; 1118 1119 if (Offset < 0) { 1120 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1); 1121 Streamer.EmitULEB128IntValue(Reg); 1122 Streamer.EmitSLEB128IntValue(Offset); 1123 } else if (Reg < 64) { 1124 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1); 1125 Streamer.EmitULEB128IntValue(Offset); 1126 } else { 1127 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1); 1128 Streamer.EmitULEB128IntValue(Reg); 1129 Streamer.EmitULEB128IntValue(Offset); 1130 } 1131 return; 1132 } 1133 case MCCFIInstruction::OpRememberState: 1134 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1); 1135 return; 1136 case MCCFIInstruction::OpRestoreState: 1137 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1); 1138 return; 1139 case MCCFIInstruction::OpSameValue: { 1140 unsigned Reg = Instr.getRegister(); 1141 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1); 1142 Streamer.EmitULEB128IntValue(Reg); 1143 return; 1144 } 1145 case MCCFIInstruction::OpRestore: { 1146 unsigned Reg = Instr.getRegister(); 1147 if (!IsEH) 1148 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false); 1149 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1); 1150 return; 1151 } 1152 case MCCFIInstruction::OpGnuArgsSize: { 1153 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_args_size, 1); 1154 Streamer.EmitULEB128IntValue(Instr.getOffset()); 1155 return; 1156 } 1157 case MCCFIInstruction::OpEscape: 1158 Streamer.EmitBytes(Instr.getValues()); 1159 return; 1160 } 1161 llvm_unreachable("Unhandled case in switch"); 1162 } 1163 1164 /// Emit frame instructions to describe the layout of the frame. 1165 void FrameEmitterImpl::EmitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1166 MCSymbol *BaseLabel) { 1167 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) { 1168 const MCCFIInstruction &Instr = Instrs[i]; 1169 MCSymbol *Label = Instr.getLabel(); 1170 // Throw out move if the label is invalid. 1171 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. 1172 1173 // Advance row if new location. 1174 if (BaseLabel && Label) { 1175 MCSymbol *ThisSym = Label; 1176 if (ThisSym != BaseLabel) { 1177 Streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); 1178 BaseLabel = ThisSym; 1179 } 1180 } 1181 1182 EmitCFIInstruction(Instr); 1183 } 1184 } 1185 1186 /// Emit the unwind information in a compact way. 1187 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) { 1188 MCContext &Context = Streamer.getContext(); 1189 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1190 1191 // range-start range-length compact-unwind-enc personality-func lsda 1192 // _foo LfooEnd-_foo 0x00000023 0 0 1193 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 1194 // 1195 // .section __LD,__compact_unwind,regular,debug 1196 // 1197 // # compact unwind for _foo 1198 // .quad _foo 1199 // .set L1,LfooEnd-_foo 1200 // .long L1 1201 // .long 0x01010001 1202 // .quad 0 1203 // .quad 0 1204 // 1205 // # compact unwind for _bar 1206 // .quad _bar 1207 // .set L2,LbarEnd-_bar 1208 // .long L2 1209 // .long 0x01020011 1210 // .quad __gxx_personality 1211 // .quad except_tab1 1212 1213 uint32_t Encoding = Frame.CompactUnwindEncoding; 1214 if (!Encoding) return; 1215 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly()); 1216 1217 // The encoding needs to know we have an LSDA. 1218 if (!DwarfEHFrameOnly && Frame.Lsda) 1219 Encoding |= 0x40000000; 1220 1221 // Range Start 1222 unsigned FDEEncoding = MOFI->getFDEEncoding(); 1223 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); 1224 Streamer.EmitSymbolValue(Frame.Begin, Size); 1225 1226 // Range Length 1227 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin, 1228 *Frame.End, 0); 1229 emitAbsValue(Streamer, Range, 4); 1230 1231 // Compact Encoding 1232 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); 1233 Streamer.EmitIntValue(Encoding, Size); 1234 1235 // Personality Function 1236 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); 1237 if (!DwarfEHFrameOnly && Frame.Personality) 1238 Streamer.EmitSymbolValue(Frame.Personality, Size); 1239 else 1240 Streamer.EmitIntValue(0, Size); // No personality fn 1241 1242 // LSDA 1243 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); 1244 if (!DwarfEHFrameOnly && Frame.Lsda) 1245 Streamer.EmitSymbolValue(Frame.Lsda, Size); 1246 else 1247 Streamer.EmitIntValue(0, Size); // No LSDA 1248 } 1249 1250 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) { 1251 if (IsEH) 1252 return 1; 1253 switch (DwarfVersion) { 1254 case 2: 1255 return 1; 1256 case 3: 1257 return 3; 1258 case 4: 1259 case 5: 1260 return 4; 1261 } 1262 llvm_unreachable("Unknown version"); 1263 } 1264 1265 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCSymbol *personality, 1266 unsigned personalityEncoding, 1267 const MCSymbol *lsda, 1268 bool IsSignalFrame, 1269 unsigned lsdaEncoding, 1270 bool IsSimple) { 1271 MCContext &context = Streamer.getContext(); 1272 const MCRegisterInfo *MRI = context.getRegisterInfo(); 1273 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1274 1275 MCSymbol *sectionStart = context.createTempSymbol(); 1276 Streamer.EmitLabel(sectionStart); 1277 1278 MCSymbol *sectionEnd = context.createTempSymbol(); 1279 1280 // Length 1281 const MCExpr *Length = 1282 MakeStartMinusEndExpr(Streamer, *sectionStart, *sectionEnd, 4); 1283 emitAbsValue(Streamer, Length, 4); 1284 1285 // CIE ID 1286 unsigned CIE_ID = IsEH ? 0 : -1; 1287 Streamer.EmitIntValue(CIE_ID, 4); 1288 1289 // Version 1290 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion()); 1291 Streamer.EmitIntValue(CIEVersion, 1); 1292 1293 // Augmentation String 1294 SmallString<8> Augmentation; 1295 if (IsEH) { 1296 Augmentation += "z"; 1297 if (personality) 1298 Augmentation += "P"; 1299 if (lsda) 1300 Augmentation += "L"; 1301 Augmentation += "R"; 1302 if (IsSignalFrame) 1303 Augmentation += "S"; 1304 Streamer.EmitBytes(Augmentation); 1305 } 1306 Streamer.EmitIntValue(0, 1); 1307 1308 if (CIEVersion >= 4) { 1309 // Address Size 1310 Streamer.EmitIntValue(context.getAsmInfo()->getPointerSize(), 1); 1311 1312 // Segment Descriptor Size 1313 Streamer.EmitIntValue(0, 1); 1314 } 1315 1316 // Code Alignment Factor 1317 Streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment()); 1318 1319 // Data Alignment Factor 1320 Streamer.EmitSLEB128IntValue(getDataAlignmentFactor(Streamer)); 1321 1322 // Return Address Register 1323 if (CIEVersion == 1) { 1324 assert(MRI->getRARegister() <= 255 && 1325 "DWARF 2 encodes return_address_register in one byte"); 1326 Streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1); 1327 } else { 1328 Streamer.EmitULEB128IntValue( 1329 MRI->getDwarfRegNum(MRI->getRARegister(), IsEH)); 1330 } 1331 1332 // Augmentation Data Length (optional) 1333 1334 unsigned augmentationLength = 0; 1335 if (IsEH) { 1336 if (personality) { 1337 // Personality Encoding 1338 augmentationLength += 1; 1339 // Personality 1340 augmentationLength += getSizeForEncoding(Streamer, personalityEncoding); 1341 } 1342 if (lsda) 1343 augmentationLength += 1; 1344 // Encoding of the FDE pointers 1345 augmentationLength += 1; 1346 1347 Streamer.EmitULEB128IntValue(augmentationLength); 1348 1349 // Augmentation Data (optional) 1350 if (personality) { 1351 // Personality Encoding 1352 emitEncodingByte(Streamer, personalityEncoding); 1353 // Personality 1354 EmitPersonality(Streamer, *personality, personalityEncoding); 1355 } 1356 1357 if (lsda) 1358 emitEncodingByte(Streamer, lsdaEncoding); 1359 1360 // Encoding of the FDE pointers 1361 emitEncodingByte(Streamer, MOFI->getFDEEncoding()); 1362 } 1363 1364 // Initial Instructions 1365 1366 const MCAsmInfo *MAI = context.getAsmInfo(); 1367 if (!IsSimple) { 1368 const std::vector<MCCFIInstruction> &Instructions = 1369 MAI->getInitialFrameState(); 1370 EmitCFIInstructions(Instructions, nullptr); 1371 } 1372 1373 InitialCFAOffset = CFAOffset; 1374 1375 // Padding 1376 Streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize()); 1377 1378 Streamer.EmitLabel(sectionEnd); 1379 return *sectionStart; 1380 } 1381 1382 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart, 1383 const MCDwarfFrameInfo &frame, 1384 bool LastInSection, 1385 const MCSymbol &SectionStart) { 1386 MCContext &context = Streamer.getContext(); 1387 MCSymbol *fdeStart = context.createTempSymbol(); 1388 MCSymbol *fdeEnd = context.createTempSymbol(); 1389 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1390 1391 CFAOffset = InitialCFAOffset; 1392 1393 // Length 1394 const MCExpr *Length = MakeStartMinusEndExpr(Streamer, *fdeStart, *fdeEnd, 0); 1395 emitAbsValue(Streamer, Length, 4); 1396 1397 Streamer.EmitLabel(fdeStart); 1398 1399 // CIE Pointer 1400 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1401 if (IsEH) { 1402 const MCExpr *offset = 1403 MakeStartMinusEndExpr(Streamer, cieStart, *fdeStart, 0); 1404 emitAbsValue(Streamer, offset, 4); 1405 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) { 1406 const MCExpr *offset = 1407 MakeStartMinusEndExpr(Streamer, SectionStart, cieStart, 0); 1408 emitAbsValue(Streamer, offset, 4); 1409 } else { 1410 Streamer.EmitSymbolValue(&cieStart, 4); 1411 } 1412 1413 // PC Begin 1414 unsigned PCEncoding = 1415 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr; 1416 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding); 1417 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH); 1418 1419 // PC Range 1420 const MCExpr *Range = 1421 MakeStartMinusEndExpr(Streamer, *frame.Begin, *frame.End, 0); 1422 emitAbsValue(Streamer, Range, PCSize); 1423 1424 if (IsEH) { 1425 // Augmentation Data Length 1426 unsigned augmentationLength = 0; 1427 1428 if (frame.Lsda) 1429 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding); 1430 1431 Streamer.EmitULEB128IntValue(augmentationLength); 1432 1433 // Augmentation Data 1434 if (frame.Lsda) 1435 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true); 1436 } 1437 1438 // Call Frame Instructions 1439 EmitCFIInstructions(frame.Instructions, frame.Begin); 1440 1441 // Padding 1442 // The size of a .eh_frame section has to be a multiple of the alignment 1443 // since a null CIE is interpreted as the end. Old systems overaligned 1444 // .eh_frame, so we do too and account for it in the last FDE. 1445 unsigned Align = LastInSection ? asmInfo->getPointerSize() : PCSize; 1446 Streamer.EmitValueToAlignment(Align); 1447 1448 Streamer.EmitLabel(fdeEnd); 1449 } 1450 1451 namespace { 1452 struct CIEKey { 1453 static const CIEKey getEmptyKey() { 1454 return CIEKey(nullptr, 0, -1, false, false); 1455 } 1456 static const CIEKey getTombstoneKey() { 1457 return CIEKey(nullptr, -1, 0, false, false); 1458 } 1459 1460 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding, 1461 unsigned LsdaEncoding, bool IsSignalFrame, bool IsSimple) 1462 : Personality(Personality), PersonalityEncoding(PersonalityEncoding), 1463 LsdaEncoding(LsdaEncoding), IsSignalFrame(IsSignalFrame), 1464 IsSimple(IsSimple) {} 1465 const MCSymbol *Personality; 1466 unsigned PersonalityEncoding; 1467 unsigned LsdaEncoding; 1468 bool IsSignalFrame; 1469 bool IsSimple; 1470 }; 1471 } // anonymous namespace 1472 1473 namespace llvm { 1474 template <> struct DenseMapInfo<CIEKey> { 1475 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); } 1476 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); } 1477 static unsigned getHashValue(const CIEKey &Key) { 1478 return static_cast<unsigned>( 1479 hash_combine(Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding, 1480 Key.IsSignalFrame, Key.IsSimple)); 1481 } 1482 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) { 1483 return LHS.Personality == RHS.Personality && 1484 LHS.PersonalityEncoding == RHS.PersonalityEncoding && 1485 LHS.LsdaEncoding == RHS.LsdaEncoding && 1486 LHS.IsSignalFrame == RHS.IsSignalFrame && 1487 LHS.IsSimple == RHS.IsSimple; 1488 } 1489 }; 1490 } // namespace llvm 1491 1492 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB, 1493 bool IsEH) { 1494 Streamer.generateCompactUnwindEncodings(MAB); 1495 1496 MCContext &Context = Streamer.getContext(); 1497 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1498 FrameEmitterImpl Emitter(IsEH, Streamer); 1499 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos(); 1500 1501 // Emit the compact unwind info if available. 1502 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame(); 1503 if (IsEH && MOFI->getCompactUnwindSection()) { 1504 bool SectionEmitted = false; 1505 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) { 1506 const MCDwarfFrameInfo &Frame = FrameArray[i]; 1507 if (Frame.CompactUnwindEncoding == 0) continue; 1508 if (!SectionEmitted) { 1509 Streamer.SwitchSection(MOFI->getCompactUnwindSection()); 1510 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize()); 1511 SectionEmitted = true; 1512 } 1513 NeedsEHFrameSection |= 1514 Frame.CompactUnwindEncoding == 1515 MOFI->getCompactUnwindDwarfEHFrameOnly(); 1516 Emitter.EmitCompactUnwind(Frame); 1517 } 1518 } 1519 1520 if (!NeedsEHFrameSection) return; 1521 1522 MCSection &Section = 1523 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection() 1524 : *MOFI->getDwarfFrameSection(); 1525 1526 Streamer.SwitchSection(&Section); 1527 MCSymbol *SectionStart = Context.createTempSymbol(); 1528 Streamer.EmitLabel(SectionStart); 1529 1530 DenseMap<CIEKey, const MCSymbol *> CIEStarts; 1531 1532 const MCSymbol *DummyDebugKey = nullptr; 1533 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind(); 1534 for (auto I = FrameArray.begin(), E = FrameArray.end(); I != E;) { 1535 const MCDwarfFrameInfo &Frame = *I; 1536 ++I; 1537 if (CanOmitDwarf && Frame.CompactUnwindEncoding != 1538 MOFI->getCompactUnwindDwarfEHFrameOnly()) 1539 // Don't generate an EH frame if we don't need one. I.e., it's taken care 1540 // of by the compact unwind encoding. 1541 continue; 1542 1543 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding, 1544 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple); 1545 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; 1546 if (!CIEStart) 1547 CIEStart = &Emitter.EmitCIE(Frame.Personality, Frame.PersonalityEncoding, 1548 Frame.Lsda, Frame.IsSignalFrame, 1549 Frame.LsdaEncoding, Frame.IsSimple); 1550 1551 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart); 1552 } 1553 } 1554 1555 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer, 1556 uint64_t AddrDelta) { 1557 MCContext &Context = Streamer.getContext(); 1558 SmallString<256> Tmp; 1559 raw_svector_ostream OS(Tmp); 1560 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS); 1561 Streamer.EmitBytes(OS.str()); 1562 } 1563 1564 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context, 1565 uint64_t AddrDelta, 1566 raw_ostream &OS) { 1567 // Scale the address delta by the minimum instruction length. 1568 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 1569 1570 if (AddrDelta == 0) { 1571 } else if (isUIntN(6, AddrDelta)) { 1572 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; 1573 OS << Opcode; 1574 } else if (isUInt<8>(AddrDelta)) { 1575 OS << uint8_t(dwarf::DW_CFA_advance_loc1); 1576 OS << uint8_t(AddrDelta); 1577 } else if (isUInt<16>(AddrDelta)) { 1578 OS << uint8_t(dwarf::DW_CFA_advance_loc2); 1579 if (Context.getAsmInfo()->isLittleEndian()) 1580 support::endian::Writer<support::little>(OS).write<uint16_t>(AddrDelta); 1581 else 1582 support::endian::Writer<support::big>(OS).write<uint16_t>(AddrDelta); 1583 } else { 1584 assert(isUInt<32>(AddrDelta)); 1585 OS << uint8_t(dwarf::DW_CFA_advance_loc4); 1586 if (Context.getAsmInfo()->isLittleEndian()) 1587 support::endian::Writer<support::little>(OS).write<uint32_t>(AddrDelta); 1588 else 1589 support::endian::Writer<support::big>(OS).write<uint32_t>(AddrDelta); 1590 } 1591 } 1592