1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
32 // Given a special op, return the address skip amount (in units of
33 // DWARF2_LINE_MIN_INSN_LENGTH.
34 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
36 // The maximum address skip amount that can be encoded with a special op.
37 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
39 // First special line opcode - leave room for the standard opcodes.
40 // Note: If you want to change this, you'll have to update the
41 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
42 #define DWARF2_LINE_OPCODE_BASE 13
44 // Minimum line offset in a special line info. opcode. This value
45 // was chosen to give a reasonable range of values.
46 #define DWARF2_LINE_BASE -5
48 // Range of line offsets in a special line info. opcode.
49 #define DWARF2_LINE_RANGE 14
51 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
52 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
53 if (MinInsnLength == 1)
55 if (AddrDelta % MinInsnLength != 0) {
56 // TODO: report this error, but really only once.
59 return AddrDelta / MinInsnLength;
63 // This is called when an instruction is assembled into the specified section
64 // and if there is information from the last .loc directive that has yet to have
65 // a line entry made for it is made.
67 void MCLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
68 if (!MCOS->getContext().getDwarfLocSeen())
71 // Create a symbol at in the current section for use in the line entry.
72 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
73 // Set the value of the symbol to use for the MCLineEntry.
74 MCOS->EmitLabel(LineSym);
76 // Get the current .loc info saved in the context.
77 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
79 // Create a (local) line entry with the symbol and the current .loc info.
80 MCLineEntry LineEntry(LineSym, DwarfLoc);
82 // clear DwarfLocSeen saying the current .loc info is now used.
83 MCOS->getContext().clearDwarfLocSeen();
85 // Add the line entry to this section's entries.
87 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
89 .addLineEntry(LineEntry, Section);
93 // This helper routine returns an expression of End - Start + IntVal .
95 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
96 const MCSymbol &Start,
99 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
101 MCSymbolRefExpr::create(&End, Variant, MCOS.getContext());
103 MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext());
105 MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
107 MCConstantExpr::create(IntVal, MCOS.getContext());
109 MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
114 // This emits the Dwarf line table for the specified section from the entries
115 // in the LineSection.
118 EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section,
119 const MCLineSection::MCLineEntryCollection &LineEntries) {
120 unsigned FileNum = 1;
121 unsigned LastLine = 1;
123 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
125 unsigned Discriminator = 0;
126 MCSymbol *LastLabel = nullptr;
128 // Loop through each MCLineEntry and encode the dwarf line number table.
129 for (auto it = LineEntries.begin(),
130 ie = LineEntries.end();
133 if (FileNum != it->getFileNum()) {
134 FileNum = it->getFileNum();
135 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
136 MCOS->EmitULEB128IntValue(FileNum);
138 if (Column != it->getColumn()) {
139 Column = it->getColumn();
140 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
141 MCOS->EmitULEB128IntValue(Column);
143 if (Discriminator != it->getDiscriminator()) {
144 Discriminator = it->getDiscriminator();
145 unsigned Size = getULEB128Size(Discriminator);
146 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
147 MCOS->EmitULEB128IntValue(Size + 1);
148 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
149 MCOS->EmitULEB128IntValue(Discriminator);
151 if (Isa != it->getIsa()) {
153 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
154 MCOS->EmitULEB128IntValue(Isa);
156 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
157 Flags = it->getFlags();
158 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
160 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
161 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
162 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
164 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
165 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
167 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
168 MCSymbol *Label = it->getLabel();
170 // At this point we want to emit/create the sequence to encode the delta in
171 // line numbers and the increment of the address from the previous Label
172 // and the current Label.
173 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
174 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
175 asmInfo->getPointerSize());
177 LastLine = it->getLine();
181 // Emit a DW_LNE_end_sequence for the end of the section.
182 // Use the section end label to compute the address delta and use INT64_MAX
183 // as the line delta which is the signal that this is actually a
184 // DW_LNE_end_sequence.
185 MCSymbol *SectionEnd = MCOS->endSection(Section);
187 // Switch back the dwarf line section, in case endSection had to switch the
189 MCContext &Ctx = MCOS->getContext();
190 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
192 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
193 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
194 AsmInfo->getPointerSize());
198 // This emits the Dwarf file and the line tables.
200 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS) {
201 MCContext &context = MCOS->getContext();
203 auto &LineTables = context.getMCDwarfLineTables();
205 // Bail out early so we don't switch to the debug_line section needlessly and
206 // in doing so create an unnecessary (if empty) section.
207 if (LineTables.empty())
210 // Switch to the section where the table will be emitted into.
211 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
213 // Handle the rest of the Compile Units.
214 for (const auto &CUIDTablePair : LineTables)
215 CUIDTablePair.second.EmitCU(MCOS);
218 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
219 MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
222 std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
223 static const char StandardOpcodeLengths[] = {
224 0, // length of DW_LNS_copy
225 1, // length of DW_LNS_advance_pc
226 1, // length of DW_LNS_advance_line
227 1, // length of DW_LNS_set_file
228 1, // length of DW_LNS_set_column
229 0, // length of DW_LNS_negate_stmt
230 0, // length of DW_LNS_set_basic_block
231 0, // length of DW_LNS_const_add_pc
232 1, // length of DW_LNS_fixed_advance_pc
233 0, // length of DW_LNS_set_prologue_end
234 0, // length of DW_LNS_set_epilogue_begin
237 assert(array_lengthof(StandardOpcodeLengths) ==
238 (DWARF2_LINE_OPCODE_BASE - 1));
239 return Emit(MCOS, StandardOpcodeLengths);
242 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
243 MCContext &Context = OS.getContext();
244 assert(!isa<MCSymbolRefExpr>(Expr));
245 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
248 MCSymbol *ABS = Context.createTempSymbol();
249 OS.EmitAssignment(ABS, Expr);
250 return MCSymbolRefExpr::create(ABS, Context);
253 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
254 const MCExpr *ABS = forceExpAbs(OS, Value);
255 OS.EmitValue(ABS, Size);
258 std::pair<MCSymbol *, MCSymbol *>
259 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
260 ArrayRef<char> StandardOpcodeLengths) const {
262 MCContext &context = MCOS->getContext();
264 // Create a symbol at the beginning of the line table.
265 MCSymbol *LineStartSym = Label;
267 LineStartSym = context.createTempSymbol();
268 // Set the value of the symbol, as we are at the start of the line table.
269 MCOS->EmitLabel(LineStartSym);
271 // Create a symbol for the end of the section (to be set when we get there).
272 MCSymbol *LineEndSym = context.createTempSymbol();
274 // The first 4 bytes is the total length of the information for this
275 // compilation unit (not including these 4 bytes for the length).
277 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
279 // Next 2 bytes is the Version, which is Dwarf 2.
280 MCOS->EmitIntValue(2, 2);
282 // Create a symbol for the end of the prologue (to be set when we get there).
283 MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
285 // Length of the prologue, is the next 4 bytes. Which is the start of the
286 // section to the end of the prologue. Not including the 4 bytes for the
287 // total length, the 2 bytes for the version, and these 4 bytes for the
288 // length of the prologue.
291 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
293 // Parameters of the state machine, are next.
294 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
295 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
296 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
297 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
298 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
300 // Standard opcode lengths
301 for (char Length : StandardOpcodeLengths)
302 MCOS->EmitIntValue(Length, 1);
304 // Put out the directory and file tables.
306 // First the directory table.
307 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
308 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
309 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
311 MCOS->EmitIntValue(0, 1); // Terminate the directory list
313 // Second the file table.
314 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
315 assert(!MCDwarfFiles[i].Name.empty());
316 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
317 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
319 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
320 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
321 MCOS->EmitIntValue(0, 1); // filesize (always 0)
323 MCOS->EmitIntValue(0, 1); // Terminate the file list
325 // This is the end of the prologue, so set the value of the symbol at the
326 // end of the prologue (that was used in a previous expression).
327 MCOS->EmitLabel(ProEndSym);
329 return std::make_pair(LineStartSym, LineEndSym);
332 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS) const {
333 MCSymbol *LineEndSym = Header.Emit(MCOS).second;
335 // Put out the line tables.
336 for (const auto &LineSec : MCLineSections.getMCLineEntries())
337 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
339 // This is the end of the section, so set the value of the symbol at the end
340 // of this section (that was used in a previous expression).
341 MCOS->EmitLabel(LineEndSym);
344 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
345 unsigned FileNumber) {
346 return Header.getFile(Directory, FileName, FileNumber);
349 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
351 unsigned FileNumber) {
352 if (Directory == CompilationDir)
354 if (FileName.empty()) {
355 FileName = "<stdin>";
358 assert(!FileName.empty());
359 if (FileNumber == 0) {
360 FileNumber = SourceIdMap.size() + 1;
361 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
362 "Don't mix autonumbered and explicit numbered line table usage");
363 SmallString<256> Buffer;
364 auto IterBool = SourceIdMap.insert(
365 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
367 if (!IterBool.second)
368 return IterBool.first->second;
370 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
371 MCDwarfFiles.resize(FileNumber + 1);
373 // Get the new MCDwarfFile slot for this FileNumber.
374 MCDwarfFile &File = MCDwarfFiles[FileNumber];
376 // It is an error to use see the same number more than once.
377 if (!File.Name.empty())
380 if (Directory.empty()) {
381 // Separate the directory part from the basename of the FileName.
382 StringRef tFileName = sys::path::filename(FileName);
383 if (!tFileName.empty()) {
384 Directory = sys::path::parent_path(FileName);
385 if (!Directory.empty())
386 FileName = tFileName;
390 // Find or make an entry in the MCDwarfDirs vector for this Directory.
391 // Capture directory name.
393 if (Directory.empty()) {
394 // For FileNames with no directories a DirIndex of 0 is used.
398 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
399 if (Directory == MCDwarfDirs[DirIndex])
402 if (DirIndex >= MCDwarfDirs.size())
403 MCDwarfDirs.push_back(Directory);
404 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
405 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
406 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
407 // are stored at MCDwarfFiles[FileNumber].Name .
411 File.Name = FileName;
412 File.DirIndex = DirIndex;
414 // return the allocated FileNumber.
418 /// Utility function to emit the encoding to a streamer.
419 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
420 uint64_t AddrDelta) {
421 MCContext &Context = MCOS->getContext();
422 SmallString<256> Tmp;
423 raw_svector_ostream OS(Tmp);
424 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
425 MCOS->EmitBytes(OS.str());
428 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
429 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
430 uint64_t AddrDelta, raw_ostream &OS) {
431 uint64_t Temp, Opcode;
432 bool NeedCopy = false;
434 // Scale the address delta by the minimum instruction length.
435 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
437 // A LineDelta of INT64_MAX is a signal that this is actually a
438 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
439 // end_sequence to emit the matrix entry.
440 if (LineDelta == INT64_MAX) {
441 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
442 OS << char(dwarf::DW_LNS_const_add_pc);
443 else if (AddrDelta) {
444 OS << char(dwarf::DW_LNS_advance_pc);
445 encodeULEB128(AddrDelta, OS);
447 OS << char(dwarf::DW_LNS_extended_op);
449 OS << char(dwarf::DW_LNE_end_sequence);
453 // Bias the line delta by the base.
454 Temp = LineDelta - DWARF2_LINE_BASE;
456 // If the line increment is out of range of a special opcode, we must encode
457 // it with DW_LNS_advance_line.
458 if (Temp >= DWARF2_LINE_RANGE) {
459 OS << char(dwarf::DW_LNS_advance_line);
460 encodeSLEB128(LineDelta, OS);
463 Temp = 0 - DWARF2_LINE_BASE;
467 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
468 if (LineDelta == 0 && AddrDelta == 0) {
469 OS << char(dwarf::DW_LNS_copy);
473 // Bias the opcode by the special opcode base.
474 Temp += DWARF2_LINE_OPCODE_BASE;
476 // Avoid overflow when addr_delta is large.
477 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
478 // Try using a special opcode.
479 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
485 // Try using DW_LNS_const_add_pc followed by special op.
486 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
488 OS << char(dwarf::DW_LNS_const_add_pc);
494 // Otherwise use DW_LNS_advance_pc.
495 OS << char(dwarf::DW_LNS_advance_pc);
496 encodeULEB128(AddrDelta, OS);
499 OS << char(dwarf::DW_LNS_copy);
504 // Utility function to write a tuple for .debug_abbrev.
505 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
506 MCOS->EmitULEB128IntValue(Name);
507 MCOS->EmitULEB128IntValue(Form);
510 // When generating dwarf for assembly source files this emits
511 // the data for .debug_abbrev section which contains three DIEs.
512 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
513 MCContext &context = MCOS->getContext();
514 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
516 // DW_TAG_compile_unit DIE abbrev (1).
517 MCOS->EmitULEB128IntValue(1);
518 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
519 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
520 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
521 if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
522 MCOS->getContext().getDwarfVersion() >= 3) {
523 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
525 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
526 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
528 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
529 if (!context.getCompilationDir().empty())
530 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
531 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
532 if (!DwarfDebugFlags.empty())
533 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
534 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
535 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
536 EmitAbbrev(MCOS, 0, 0);
538 // DW_TAG_label DIE abbrev (2).
539 MCOS->EmitULEB128IntValue(2);
540 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
541 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
542 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
543 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
544 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
545 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
546 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
547 EmitAbbrev(MCOS, 0, 0);
549 // DW_TAG_unspecified_parameters DIE abbrev (3).
550 MCOS->EmitULEB128IntValue(3);
551 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
552 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
553 EmitAbbrev(MCOS, 0, 0);
555 // Terminate the abbreviations for this compilation unit.
556 MCOS->EmitIntValue(0, 1);
559 // When generating dwarf for assembly source files this emits the data for
560 // .debug_aranges section. This section contains a header and a table of pairs
561 // of PointerSize'ed values for the address and size of section(s) with line
563 static void EmitGenDwarfAranges(MCStreamer *MCOS,
564 const MCSymbol *InfoSectionSymbol) {
565 MCContext &context = MCOS->getContext();
567 auto &Sections = context.getGenDwarfSectionSyms();
569 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
571 // This will be the length of the .debug_aranges section, first account for
572 // the size of each item in the header (see below where we emit these items).
573 int Length = 4 + 2 + 4 + 1 + 1;
575 // Figure the padding after the header before the table of address and size
576 // pairs who's values are PointerSize'ed.
577 const MCAsmInfo *asmInfo = context.getAsmInfo();
578 int AddrSize = asmInfo->getPointerSize();
579 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
580 if (Pad == 2 * AddrSize)
584 // Add the size of the pair of PointerSize'ed values for the address and size
585 // of each section we have in the table.
586 Length += 2 * AddrSize * Sections.size();
587 // And the pair of terminating zeros.
588 Length += 2 * AddrSize;
591 // Emit the header for this section.
592 // The 4 byte length not including the 4 byte value for the length.
593 MCOS->EmitIntValue(Length - 4, 4);
594 // The 2 byte version, which is 2.
595 MCOS->EmitIntValue(2, 2);
596 // The 4 byte offset to the compile unit in the .debug_info from the start
597 // of the .debug_info.
598 if (InfoSectionSymbol)
599 MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
600 asmInfo->needsDwarfSectionOffsetDirective());
602 MCOS->EmitIntValue(0, 4);
603 // The 1 byte size of an address.
604 MCOS->EmitIntValue(AddrSize, 1);
605 // The 1 byte size of a segment descriptor, we use a value of zero.
606 MCOS->EmitIntValue(0, 1);
607 // Align the header with the padding if needed, before we put out the table.
608 for(int i = 0; i < Pad; i++)
609 MCOS->EmitIntValue(0, 1);
611 // Now emit the table of pairs of PointerSize'ed values for the section
612 // addresses and sizes.
613 for (MCSection *Sec : Sections) {
614 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
615 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
616 assert(StartSymbol && "StartSymbol must not be NULL");
617 assert(EndSymbol && "EndSymbol must not be NULL");
619 const MCExpr *Addr = MCSymbolRefExpr::create(
620 StartSymbol, MCSymbolRefExpr::VK_None, context);
621 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
622 *StartSymbol, *EndSymbol, 0);
623 MCOS->EmitValue(Addr, AddrSize);
624 emitAbsValue(*MCOS, Size, AddrSize);
627 // And finally the pair of terminating zeros.
628 MCOS->EmitIntValue(0, AddrSize);
629 MCOS->EmitIntValue(0, AddrSize);
632 // When generating dwarf for assembly source files this emits the data for
633 // .debug_info section which contains three parts. The header, the compile_unit
634 // DIE and a list of label DIEs.
635 static void EmitGenDwarfInfo(MCStreamer *MCOS,
636 const MCSymbol *AbbrevSectionSymbol,
637 const MCSymbol *LineSectionSymbol,
638 const MCSymbol *RangesSectionSymbol) {
639 MCContext &context = MCOS->getContext();
641 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
643 // Create a symbol at the start and end of this section used in here for the
644 // expression to calculate the length in the header.
645 MCSymbol *InfoStart = context.createTempSymbol();
646 MCOS->EmitLabel(InfoStart);
647 MCSymbol *InfoEnd = context.createTempSymbol();
649 // First part: the header.
651 // The 4 byte total length of the information for this compilation unit, not
652 // including these 4 bytes.
653 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
654 emitAbsValue(*MCOS, Length, 4);
656 // The 2 byte DWARF version.
657 MCOS->EmitIntValue(context.getDwarfVersion(), 2);
659 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
660 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
661 // it is at the start of that section so this is zero.
662 if (AbbrevSectionSymbol == nullptr)
663 MCOS->EmitIntValue(0, 4);
665 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
666 AsmInfo.needsDwarfSectionOffsetDirective());
668 const MCAsmInfo *asmInfo = context.getAsmInfo();
669 int AddrSize = asmInfo->getPointerSize();
670 // The 1 byte size of an address.
671 MCOS->EmitIntValue(AddrSize, 1);
673 // Second part: the compile_unit DIE.
675 // The DW_TAG_compile_unit DIE abbrev (1).
676 MCOS->EmitULEB128IntValue(1);
678 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
679 // which is at the start of that section so this is zero.
680 if (LineSectionSymbol)
681 MCOS->EmitSymbolValue(LineSectionSymbol, 4,
682 AsmInfo.needsDwarfSectionOffsetDirective());
684 MCOS->EmitIntValue(0, 4);
686 if (RangesSectionSymbol) {
687 // There are multiple sections containing code, so we must use the
688 // .debug_ranges sections.
690 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
691 // to the address range list for this compilation unit.
692 MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
694 // If we only have one non-empty code section, we can use the simpler
695 // AT_low_pc and AT_high_pc attributes.
697 // Find the first (and only) non-empty text section
698 auto &Sections = context.getGenDwarfSectionSyms();
699 const auto TextSection = Sections.begin();
700 assert(TextSection != Sections.end() && "No text section found");
702 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
703 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
704 assert(StartSymbol && "StartSymbol must not be NULL");
705 assert(EndSymbol && "EndSymbol must not be NULL");
707 // AT_low_pc, the first address of the default .text section.
708 const MCExpr *Start = MCSymbolRefExpr::create(
709 StartSymbol, MCSymbolRefExpr::VK_None, context);
710 MCOS->EmitValue(Start, AddrSize);
712 // AT_high_pc, the last address of the default .text section.
713 const MCExpr *End = MCSymbolRefExpr::create(
714 EndSymbol, MCSymbolRefExpr::VK_None, context);
715 MCOS->EmitValue(End, AddrSize);
718 // AT_name, the name of the source file. Reconstruct from the first directory
719 // and file table entries.
720 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
721 if (MCDwarfDirs.size() > 0) {
722 MCOS->EmitBytes(MCDwarfDirs[0]);
723 MCOS->EmitBytes(sys::path::get_separator());
725 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
726 MCOS->getContext().getMCDwarfFiles();
727 MCOS->EmitBytes(MCDwarfFiles[1].Name);
728 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
730 // AT_comp_dir, the working directory the assembly was done in.
731 if (!context.getCompilationDir().empty()) {
732 MCOS->EmitBytes(context.getCompilationDir());
733 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
736 // AT_APPLE_flags, the command line arguments of the assembler tool.
737 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
738 if (!DwarfDebugFlags.empty()){
739 MCOS->EmitBytes(DwarfDebugFlags);
740 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
743 // AT_producer, the version of the assembler tool.
744 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
745 if (!DwarfDebugProducer.empty())
746 MCOS->EmitBytes(DwarfDebugProducer);
748 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
749 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
751 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
752 // draft has no standard code for assembler.
753 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
755 // Third part: the list of label DIEs.
757 // Loop on saved info for dwarf labels and create the DIEs for them.
758 const std::vector<MCGenDwarfLabelEntry> &Entries =
759 MCOS->getContext().getMCGenDwarfLabelEntries();
760 for (const auto &Entry : Entries) {
761 // The DW_TAG_label DIE abbrev (2).
762 MCOS->EmitULEB128IntValue(2);
764 // AT_name, of the label without any leading underbar.
765 MCOS->EmitBytes(Entry.getName());
766 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
768 // AT_decl_file, index into the file table.
769 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
771 // AT_decl_line, source line number.
772 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
774 // AT_low_pc, start address of the label.
775 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
776 MCSymbolRefExpr::VK_None, context);
777 MCOS->EmitValue(AT_low_pc, AddrSize);
779 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
780 MCOS->EmitIntValue(0, 1);
782 // The DW_TAG_unspecified_parameters DIE abbrev (3).
783 MCOS->EmitULEB128IntValue(3);
785 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
786 MCOS->EmitIntValue(0, 1);
789 // Add the NULL DIE terminating the Compile Unit DIE's.
790 MCOS->EmitIntValue(0, 1);
792 // Now set the value of the symbol at the end of the info section.
793 MCOS->EmitLabel(InfoEnd);
796 // When generating dwarf for assembly source files this emits the data for
797 // .debug_ranges section. We only emit one range list, which spans all of the
798 // executable sections of this file.
799 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
800 MCContext &context = MCOS->getContext();
801 auto &Sections = context.getGenDwarfSectionSyms();
803 const MCAsmInfo *AsmInfo = context.getAsmInfo();
804 int AddrSize = AsmInfo->getPointerSize();
806 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
808 for (MCSection *Sec : Sections) {
809 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
810 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
811 assert(StartSymbol && "StartSymbol must not be NULL");
812 assert(EndSymbol && "EndSymbol must not be NULL");
814 // Emit a base address selection entry for the start of this section
815 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
816 StartSymbol, MCSymbolRefExpr::VK_None, context);
817 MCOS->EmitFill(AddrSize, 0xFF);
818 MCOS->EmitValue(SectionStartAddr, AddrSize);
820 // Emit a range list entry spanning this section
821 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
822 *StartSymbol, *EndSymbol, 0);
823 MCOS->EmitIntValue(0, AddrSize);
824 emitAbsValue(*MCOS, SectionSize, AddrSize);
827 // Emit end of list entry
828 MCOS->EmitIntValue(0, AddrSize);
829 MCOS->EmitIntValue(0, AddrSize);
833 // When generating dwarf for assembly source files this emits the Dwarf
836 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
837 MCContext &context = MCOS->getContext();
839 // Create the dwarf sections in this order (.debug_line already created).
840 const MCAsmInfo *AsmInfo = context.getAsmInfo();
841 bool CreateDwarfSectionSymbols =
842 AsmInfo->doesDwarfUseRelocationsAcrossSections();
843 MCSymbol *LineSectionSymbol = nullptr;
844 if (CreateDwarfSectionSymbols)
845 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
846 MCSymbol *AbbrevSectionSymbol = nullptr;
847 MCSymbol *InfoSectionSymbol = nullptr;
848 MCSymbol *RangesSectionSymbol = NULL;
850 // Create end symbols for each section, and remove empty sections
851 MCOS->getContext().finalizeDwarfSections(*MCOS);
853 // If there are no sections to generate debug info for, we don't need
855 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
858 // We only use the .debug_ranges section if we have multiple code sections,
859 // and we are emitting a DWARF version which supports it.
860 const bool UseRangesSection =
861 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
862 MCOS->getContext().getDwarfVersion() >= 3;
863 CreateDwarfSectionSymbols |= UseRangesSection;
865 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
866 if (CreateDwarfSectionSymbols) {
867 InfoSectionSymbol = context.createTempSymbol();
868 MCOS->EmitLabel(InfoSectionSymbol);
870 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
871 if (CreateDwarfSectionSymbols) {
872 AbbrevSectionSymbol = context.createTempSymbol();
873 MCOS->EmitLabel(AbbrevSectionSymbol);
875 if (UseRangesSection) {
876 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
877 if (CreateDwarfSectionSymbols) {
878 RangesSectionSymbol = context.createTempSymbol();
879 MCOS->EmitLabel(RangesSectionSymbol);
883 assert((RangesSectionSymbol != NULL) || !UseRangesSection);
885 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
887 // Output the data for .debug_aranges section.
888 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
890 if (UseRangesSection)
891 EmitGenDwarfRanges(MCOS);
893 // Output the data for .debug_abbrev section.
894 EmitGenDwarfAbbrev(MCOS);
896 // Output the data for .debug_info section.
897 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
898 RangesSectionSymbol);
902 // When generating dwarf for assembly source files this is called when symbol
903 // for a label is created. If this symbol is not a temporary and is in the
904 // section that dwarf is being generated for, save the needed info to create
907 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
908 SourceMgr &SrcMgr, SMLoc &Loc) {
909 // We won't create dwarf labels for temporary symbols.
910 if (Symbol->isTemporary())
912 MCContext &context = MCOS->getContext();
913 // We won't create dwarf labels for symbols in sections that we are not
914 // generating debug info for.
915 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
918 // The dwarf label's name does not have the symbol name's leading
920 StringRef Name = Symbol->getName();
921 if (Name.startswith("_"))
922 Name = Name.substr(1, Name.size()-1);
924 // Get the dwarf file number to be used for the dwarf label.
925 unsigned FileNumber = context.getGenDwarfFileNumber();
927 // Finding the line number is the expensive part which is why we just don't
928 // pass it in as for some symbols we won't create a dwarf label.
929 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
930 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
932 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
933 // values so that they don't have things like an ARM thumb bit from the
934 // original symbol. So when used they won't get a low bit set after
936 MCSymbol *Label = context.createTempSymbol();
937 MCOS->EmitLabel(Label);
939 // Create and entry for the info and add it to the other entries.
940 MCOS->getContext().addMCGenDwarfLabelEntry(
941 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
944 static int getDataAlignmentFactor(MCStreamer &streamer) {
945 MCContext &context = streamer.getContext();
946 const MCAsmInfo *asmInfo = context.getAsmInfo();
947 int size = asmInfo->getCalleeSaveStackSlotSize();
948 if (asmInfo->isStackGrowthDirectionUp())
954 static unsigned getSizeForEncoding(MCStreamer &streamer,
955 unsigned symbolEncoding) {
956 MCContext &context = streamer.getContext();
957 unsigned format = symbolEncoding & 0x0f;
959 default: llvm_unreachable("Unknown Encoding");
960 case dwarf::DW_EH_PE_absptr:
961 case dwarf::DW_EH_PE_signed:
962 return context.getAsmInfo()->getPointerSize();
963 case dwarf::DW_EH_PE_udata2:
964 case dwarf::DW_EH_PE_sdata2:
966 case dwarf::DW_EH_PE_udata4:
967 case dwarf::DW_EH_PE_sdata4:
969 case dwarf::DW_EH_PE_udata8:
970 case dwarf::DW_EH_PE_sdata8:
975 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
976 unsigned symbolEncoding, bool isEH) {
977 MCContext &context = streamer.getContext();
978 const MCAsmInfo *asmInfo = context.getAsmInfo();
979 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
982 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
983 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
984 emitAbsValue(streamer, v, size);
986 streamer.EmitValue(v, size);
989 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
990 unsigned symbolEncoding) {
991 MCContext &context = streamer.getContext();
992 const MCAsmInfo *asmInfo = context.getAsmInfo();
993 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
996 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
997 streamer.EmitValue(v, size);
1001 class FrameEmitterImpl {
1003 int InitialCFAOffset;
1005 const MCSymbol *SectionStart;
1007 FrameEmitterImpl(bool isEH)
1008 : CFAOffset(0), InitialCFAOffset(0), IsEH(isEH), SectionStart(nullptr) {
1011 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
1013 /// Emit the unwind information in a compact way.
1014 void EmitCompactUnwind(MCObjectStreamer &streamer,
1015 const MCDwarfFrameInfo &frame);
1017 const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
1018 const MCSymbol *personality,
1019 unsigned personalityEncoding,
1020 const MCSymbol *lsda,
1022 unsigned lsdaEncoding,
1024 MCSymbol *EmitFDE(MCObjectStreamer &streamer,
1025 const MCSymbol &cieStart,
1026 const MCDwarfFrameInfo &frame);
1027 void EmitCFIInstructions(MCObjectStreamer &streamer,
1028 ArrayRef<MCCFIInstruction> Instrs,
1029 MCSymbol *BaseLabel);
1030 void EmitCFIInstruction(MCObjectStreamer &Streamer,
1031 const MCCFIInstruction &Instr);
1034 } // end anonymous namespace
1036 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1037 Streamer.EmitIntValue(Encoding, 1);
1040 void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
1041 const MCCFIInstruction &Instr) {
1042 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1043 auto *MRI = Streamer.getContext().getRegisterInfo();
1045 switch (Instr.getOperation()) {
1046 case MCCFIInstruction::OpRegister: {
1047 unsigned Reg1 = Instr.getRegister();
1048 unsigned Reg2 = Instr.getRegister2();
1050 Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false);
1051 Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false);
1053 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1054 Streamer.EmitULEB128IntValue(Reg1);
1055 Streamer.EmitULEB128IntValue(Reg2);
1058 case MCCFIInstruction::OpWindowSave: {
1059 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1062 case MCCFIInstruction::OpUndefined: {
1063 unsigned Reg = Instr.getRegister();
1064 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1065 Streamer.EmitULEB128IntValue(Reg);
1068 case MCCFIInstruction::OpAdjustCfaOffset:
1069 case MCCFIInstruction::OpDefCfaOffset: {
1070 const bool IsRelative =
1071 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1073 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1076 CFAOffset += Instr.getOffset();
1078 CFAOffset = -Instr.getOffset();
1080 Streamer.EmitULEB128IntValue(CFAOffset);
1084 case MCCFIInstruction::OpDefCfa: {
1085 unsigned Reg = Instr.getRegister();
1087 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1088 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1089 Streamer.EmitULEB128IntValue(Reg);
1090 CFAOffset = -Instr.getOffset();
1091 Streamer.EmitULEB128IntValue(CFAOffset);
1096 case MCCFIInstruction::OpDefCfaRegister: {
1097 unsigned Reg = Instr.getRegister();
1099 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1100 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1101 Streamer.EmitULEB128IntValue(Reg);
1106 case MCCFIInstruction::OpOffset:
1107 case MCCFIInstruction::OpRelOffset: {
1108 const bool IsRelative =
1109 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1111 unsigned Reg = Instr.getRegister();
1113 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1115 int Offset = Instr.getOffset();
1117 Offset -= CFAOffset;
1118 Offset = Offset / dataAlignmentFactor;
1121 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1122 Streamer.EmitULEB128IntValue(Reg);
1123 Streamer.EmitSLEB128IntValue(Offset);
1124 } else if (Reg < 64) {
1125 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1126 Streamer.EmitULEB128IntValue(Offset);
1128 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1129 Streamer.EmitULEB128IntValue(Reg);
1130 Streamer.EmitULEB128IntValue(Offset);
1134 case MCCFIInstruction::OpRememberState:
1135 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1137 case MCCFIInstruction::OpRestoreState:
1138 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1140 case MCCFIInstruction::OpSameValue: {
1141 unsigned Reg = Instr.getRegister();
1142 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1143 Streamer.EmitULEB128IntValue(Reg);
1146 case MCCFIInstruction::OpRestore: {
1147 unsigned Reg = Instr.getRegister();
1149 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1150 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1153 case MCCFIInstruction::OpEscape:
1154 Streamer.EmitBytes(Instr.getValues());
1157 llvm_unreachable("Unhandled case in switch");
1160 /// Emit frame instructions to describe the layout of the frame.
1161 void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
1162 ArrayRef<MCCFIInstruction> Instrs,
1163 MCSymbol *BaseLabel) {
1164 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1165 const MCCFIInstruction &Instr = Instrs[i];
1166 MCSymbol *Label = Instr.getLabel();
1167 // Throw out move if the label is invalid.
1168 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1170 // Advance row if new location.
1171 if (BaseLabel && Label) {
1172 MCSymbol *ThisSym = Label;
1173 if (ThisSym != BaseLabel) {
1174 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1175 BaseLabel = ThisSym;
1179 EmitCFIInstruction(streamer, Instr);
1183 /// Emit the unwind information in a compact way.
1184 void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
1185 const MCDwarfFrameInfo &Frame) {
1186 MCContext &Context = Streamer.getContext();
1187 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1189 // range-start range-length compact-unwind-enc personality-func lsda
1190 // _foo LfooEnd-_foo 0x00000023 0 0
1191 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1193 // .section __LD,__compact_unwind,regular,debug
1195 // # compact unwind for _foo
1197 // .set L1,LfooEnd-_foo
1203 // # compact unwind for _bar
1205 // .set L2,LbarEnd-_bar
1208 // .quad __gxx_personality
1209 // .quad except_tab1
1211 uint32_t Encoding = Frame.CompactUnwindEncoding;
1212 if (!Encoding) return;
1213 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1215 // The encoding needs to know we have an LSDA.
1216 if (!DwarfEHFrameOnly && Frame.Lsda)
1217 Encoding |= 0x40000000;
1220 unsigned FDEEncoding = MOFI->getFDEEncoding();
1221 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1222 Streamer.EmitSymbolValue(Frame.Begin, Size);
1225 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1227 emitAbsValue(Streamer, Range, 4);
1230 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1231 Streamer.EmitIntValue(Encoding, Size);
1233 // Personality Function
1234 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1235 if (!DwarfEHFrameOnly && Frame.Personality)
1236 Streamer.EmitSymbolValue(Frame.Personality, Size);
1238 Streamer.EmitIntValue(0, Size); // No personality fn
1241 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1242 if (!DwarfEHFrameOnly && Frame.Lsda)
1243 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1245 Streamer.EmitIntValue(0, Size); // No LSDA
1248 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1251 switch (DwarfVersion) {
1259 llvm_unreachable("Unknown version");
1262 const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
1263 const MCSymbol *personality,
1264 unsigned personalityEncoding,
1265 const MCSymbol *lsda,
1267 unsigned lsdaEncoding,
1269 MCContext &context = streamer.getContext();
1270 const MCRegisterInfo *MRI = context.getRegisterInfo();
1271 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1273 MCSymbol *sectionStart = context.createTempSymbol();
1274 streamer.EmitLabel(sectionStart);
1276 MCSymbol *sectionEnd = context.createTempSymbol();
1279 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1281 emitAbsValue(streamer, Length, 4);
1284 unsigned CIE_ID = IsEH ? 0 : -1;
1285 streamer.EmitIntValue(CIE_ID, 4);
1288 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1289 streamer.EmitIntValue(CIEVersion, 1);
1291 // Augmentation String
1292 SmallString<8> Augmentation;
1294 Augmentation += "z";
1296 Augmentation += "P";
1298 Augmentation += "L";
1299 Augmentation += "R";
1301 Augmentation += "S";
1302 streamer.EmitBytes(Augmentation);
1304 streamer.EmitIntValue(0, 1);
1306 if (CIEVersion >= 4) {
1308 streamer.EmitIntValue(context.getAsmInfo()->getPointerSize(), 1);
1310 // Segment Descriptor Size
1311 streamer.EmitIntValue(0, 1);
1314 // Code Alignment Factor
1315 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1317 // Data Alignment Factor
1318 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1320 // Return Address Register
1321 if (CIEVersion == 1) {
1322 assert(MRI->getRARegister() <= 255 &&
1323 "DWARF 2 encodes return_address_register in one byte");
1324 streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1);
1326 streamer.EmitULEB128IntValue(
1327 MRI->getDwarfRegNum(MRI->getRARegister(), IsEH));
1330 // Augmentation Data Length (optional)
1332 unsigned augmentationLength = 0;
1335 // Personality Encoding
1336 augmentationLength += 1;
1338 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1341 augmentationLength += 1;
1342 // Encoding of the FDE pointers
1343 augmentationLength += 1;
1345 streamer.EmitULEB128IntValue(augmentationLength);
1347 // Augmentation Data (optional)
1349 // Personality Encoding
1350 emitEncodingByte(streamer, personalityEncoding);
1352 EmitPersonality(streamer, *personality, personalityEncoding);
1356 emitEncodingByte(streamer, lsdaEncoding);
1358 // Encoding of the FDE pointers
1359 emitEncodingByte(streamer, MOFI->getFDEEncoding());
1362 // Initial Instructions
1364 const MCAsmInfo *MAI = context.getAsmInfo();
1366 const std::vector<MCCFIInstruction> &Instructions =
1367 MAI->getInitialFrameState();
1368 EmitCFIInstructions(streamer, Instructions, nullptr);
1371 InitialCFAOffset = CFAOffset;
1374 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1376 streamer.EmitLabel(sectionEnd);
1377 return *sectionStart;
1380 MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
1381 const MCSymbol &cieStart,
1382 const MCDwarfFrameInfo &frame) {
1383 MCContext &context = streamer.getContext();
1384 MCSymbol *fdeStart = context.createTempSymbol();
1385 MCSymbol *fdeEnd = context.createTempSymbol();
1386 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1388 CFAOffset = InitialCFAOffset;
1391 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1392 emitAbsValue(streamer, Length, 4);
1394 streamer.EmitLabel(fdeStart);
1397 const MCAsmInfo *asmInfo = context.getAsmInfo();
1399 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1401 emitAbsValue(streamer, offset, 4);
1402 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1403 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1405 emitAbsValue(streamer, offset, 4);
1407 streamer.EmitSymbolValue(&cieStart, 4);
1411 unsigned PCEncoding =
1412 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1413 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1414 emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
1417 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1419 emitAbsValue(streamer, Range, PCSize);
1422 // Augmentation Data Length
1423 unsigned augmentationLength = 0;
1426 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1428 streamer.EmitULEB128IntValue(augmentationLength);
1430 // Augmentation Data
1432 emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
1435 // Call Frame Instructions
1436 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1439 streamer.EmitValueToAlignment(PCSize);
1446 static const CIEKey getEmptyKey() {
1447 return CIEKey(nullptr, 0, -1, false, false);
1449 static const CIEKey getTombstoneKey() {
1450 return CIEKey(nullptr, -1, 0, false, false);
1453 CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
1454 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
1455 : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1456 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1457 IsSimple(IsSimple_) {}
1458 const MCSymbol *Personality;
1459 unsigned PersonalityEncoding;
1460 unsigned LsdaEncoding;
1468 struct DenseMapInfo<CIEKey> {
1469 static CIEKey getEmptyKey() {
1470 return CIEKey::getEmptyKey();
1472 static CIEKey getTombstoneKey() {
1473 return CIEKey::getTombstoneKey();
1475 static unsigned getHashValue(const CIEKey &Key) {
1476 return static_cast<unsigned>(hash_combine(Key.Personality,
1477 Key.PersonalityEncoding,
1482 static bool isEqual(const CIEKey &LHS,
1483 const CIEKey &RHS) {
1484 return LHS.Personality == RHS.Personality &&
1485 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1486 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1487 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1488 LHS.IsSimple == RHS.IsSimple;
1493 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1495 Streamer.generateCompactUnwindEncodings(MAB);
1497 MCContext &Context = Streamer.getContext();
1498 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1499 FrameEmitterImpl Emitter(IsEH);
1500 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1502 // Emit the compact unwind info if available.
1503 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1504 if (IsEH && MOFI->getCompactUnwindSection()) {
1505 bool SectionEmitted = false;
1506 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1507 const MCDwarfFrameInfo &Frame = FrameArray[i];
1508 if (Frame.CompactUnwindEncoding == 0) continue;
1509 if (!SectionEmitted) {
1510 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1511 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1512 SectionEmitted = true;
1514 NeedsEHFrameSection |=
1515 Frame.CompactUnwindEncoding ==
1516 MOFI->getCompactUnwindDwarfEHFrameOnly();
1517 Emitter.EmitCompactUnwind(Streamer, Frame);
1521 if (!NeedsEHFrameSection) return;
1523 MCSection &Section =
1524 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1525 : *MOFI->getDwarfFrameSection();
1527 Streamer.SwitchSection(&Section);
1528 MCSymbol *SectionStart = Context.createTempSymbol();
1529 Streamer.EmitLabel(SectionStart);
1530 Emitter.setSectionStart(SectionStart);
1532 MCSymbol *FDEEnd = nullptr;
1533 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1535 const MCSymbol *DummyDebugKey = nullptr;
1536 NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1537 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1538 const MCDwarfFrameInfo &Frame = FrameArray[i];
1540 // Emit the label from the previous iteration
1542 Streamer.EmitLabel(FDEEnd);
1546 if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1547 MOFI->getCompactUnwindDwarfEHFrameOnly())
1548 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1549 // of by the compact unwind encoding.
1552 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1553 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1554 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1556 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1557 Frame.PersonalityEncoding, Frame.Lsda,
1558 Frame.IsSignalFrame,
1562 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1565 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1567 Streamer.EmitLabel(FDEEnd);
1570 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1571 uint64_t AddrDelta) {
1572 MCContext &Context = Streamer.getContext();
1573 SmallString<256> Tmp;
1574 raw_svector_ostream OS(Tmp);
1575 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1576 Streamer.EmitBytes(OS.str());
1579 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1582 // Scale the address delta by the minimum instruction length.
1583 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1585 if (AddrDelta == 0) {
1586 } else if (isUIntN(6, AddrDelta)) {
1587 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1589 } else if (isUInt<8>(AddrDelta)) {
1590 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1591 OS << uint8_t(AddrDelta);
1592 } else if (isUInt<16>(AddrDelta)) {
1593 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1594 if (Context.getAsmInfo()->isLittleEndian())
1595 support::endian::Writer<support::little>(OS).write<uint16_t>(AddrDelta);
1597 support::endian::Writer<support::big>(OS).write<uint16_t>(AddrDelta);
1599 assert(isUInt<32>(AddrDelta));
1600 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1601 if (Context.getAsmInfo()->isLittleEndian())
1602 support::endian::Writer<support::little>(OS).write<uint32_t>(AddrDelta);
1604 support::endian::Writer<support::big>(OS).write<uint32_t>(AddrDelta);