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/EndianStream.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LEB128.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/raw_ostream.h"
34 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
35 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
36 if (MinInsnLength == 1)
38 if (AddrDelta % MinInsnLength != 0) {
39 // TODO: report this error, but really only once.
42 return AddrDelta / MinInsnLength;
46 // This is called when an instruction is assembled into the specified section
47 // and if there is information from the last .loc directive that has yet to have
48 // a line entry made for it is made.
50 void MCDwarfLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
51 if (!MCOS->getContext().getDwarfLocSeen())
54 // Create a symbol at in the current section for use in the line entry.
55 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
56 // Set the value of the symbol to use for the MCDwarfLineEntry.
57 MCOS->EmitLabel(LineSym);
59 // Get the current .loc info saved in the context.
60 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
62 // Create a (local) line entry with the symbol and the current .loc info.
63 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
65 // clear DwarfLocSeen saying the current .loc info is now used.
66 MCOS->getContext().clearDwarfLocSeen();
68 // Add the line entry to this section's entries.
70 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
72 .addLineEntry(LineEntry, Section);
76 // This helper routine returns an expression of End - Start + IntVal .
78 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
79 const MCSymbol &Start,
82 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
84 MCSymbolRefExpr::create(&End, Variant, MCOS.getContext());
86 MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext());
88 MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
90 MCConstantExpr::create(IntVal, MCOS.getContext());
92 MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
97 // This emits the Dwarf line table for the specified section from the entries
98 // in the LineSection.
101 EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section,
102 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
103 unsigned FileNum = 1;
104 unsigned LastLine = 1;
106 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
108 unsigned Discriminator = 0;
109 MCSymbol *LastLabel = nullptr;
111 // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
112 for (const MCDwarfLineEntry &LineEntry : LineEntries) {
113 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
115 if (FileNum != LineEntry.getFileNum()) {
116 FileNum = LineEntry.getFileNum();
117 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
118 MCOS->EmitULEB128IntValue(FileNum);
120 if (Column != LineEntry.getColumn()) {
121 Column = LineEntry.getColumn();
122 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
123 MCOS->EmitULEB128IntValue(Column);
125 if (Discriminator != LineEntry.getDiscriminator() &&
126 MCOS->getContext().getDwarfVersion() >= 4) {
127 Discriminator = LineEntry.getDiscriminator();
128 unsigned Size = getULEB128Size(Discriminator);
129 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
130 MCOS->EmitULEB128IntValue(Size + 1);
131 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
132 MCOS->EmitULEB128IntValue(Discriminator);
134 if (Isa != LineEntry.getIsa()) {
135 Isa = LineEntry.getIsa();
136 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
137 MCOS->EmitULEB128IntValue(Isa);
139 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
140 Flags = LineEntry.getFlags();
141 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
143 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
144 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
145 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
146 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
147 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
148 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
150 MCSymbol *Label = LineEntry.getLabel();
152 // At this point we want to emit/create the sequence to encode the delta in
153 // line numbers and the increment of the address from the previous Label
154 // and the current Label.
155 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
156 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
157 asmInfo->getPointerSize());
160 LastLine = LineEntry.getLine();
164 // Emit a DW_LNE_end_sequence for the end of the section.
165 // Use the section end label to compute the address delta and use INT64_MAX
166 // as the line delta which is the signal that this is actually a
167 // DW_LNE_end_sequence.
168 MCSymbol *SectionEnd = MCOS->endSection(Section);
170 // Switch back the dwarf line section, in case endSection had to switch the
172 MCContext &Ctx = MCOS->getContext();
173 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
175 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
176 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
177 AsmInfo->getPointerSize());
181 // This emits the Dwarf file and the line tables.
183 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS,
184 MCDwarfLineTableParams Params) {
185 MCContext &context = MCOS->getContext();
187 auto &LineTables = context.getMCDwarfLineTables();
189 // Bail out early so we don't switch to the debug_line section needlessly and
190 // in doing so create an unnecessary (if empty) section.
191 if (LineTables.empty())
194 // Switch to the section where the table will be emitted into.
195 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
197 // Handle the rest of the Compile Units.
198 for (const auto &CUIDTablePair : LineTables)
199 CUIDTablePair.second.EmitCU(MCOS, Params);
202 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS,
203 MCDwarfLineTableParams Params) const {
204 MCOS.EmitLabel(Header.Emit(&MCOS, Params, None).second);
207 std::pair<MCSymbol *, MCSymbol *>
208 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
209 MCDwarfLineTableParams Params) const {
210 static const char StandardOpcodeLengths[] = {
211 0, // length of DW_LNS_copy
212 1, // length of DW_LNS_advance_pc
213 1, // length of DW_LNS_advance_line
214 1, // length of DW_LNS_set_file
215 1, // length of DW_LNS_set_column
216 0, // length of DW_LNS_negate_stmt
217 0, // length of DW_LNS_set_basic_block
218 0, // length of DW_LNS_const_add_pc
219 1, // length of DW_LNS_fixed_advance_pc
220 0, // length of DW_LNS_set_prologue_end
221 0, // length of DW_LNS_set_epilogue_begin
224 assert(array_lengthof(StandardOpcodeLengths) >=
225 (Params.DWARF2LineOpcodeBase - 1U));
226 return Emit(MCOS, Params, makeArrayRef(StandardOpcodeLengths,
227 Params.DWARF2LineOpcodeBase - 1));
230 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
231 MCContext &Context = OS.getContext();
232 assert(!isa<MCSymbolRefExpr>(Expr));
233 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
236 MCSymbol *ABS = Context.createTempSymbol();
237 OS.EmitAssignment(ABS, Expr);
238 return MCSymbolRefExpr::create(ABS, Context);
241 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
242 const MCExpr *ABS = forceExpAbs(OS, Value);
243 OS.EmitValue(ABS, Size);
246 std::pair<MCSymbol *, MCSymbol *>
247 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
248 ArrayRef<char> StandardOpcodeLengths) const {
249 MCContext &context = MCOS->getContext();
251 // Create a symbol at the beginning of the line table.
252 MCSymbol *LineStartSym = Label;
254 LineStartSym = context.createTempSymbol();
255 // Set the value of the symbol, as we are at the start of the line table.
256 MCOS->EmitLabel(LineStartSym);
258 // Create a symbol for the end of the section (to be set when we get there).
259 MCSymbol *LineEndSym = context.createTempSymbol();
261 // The first 4 bytes is the total length of the information for this
262 // compilation unit (not including these 4 bytes for the length).
264 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
266 // Next 2 bytes is the Version, which is Dwarf 2.
267 MCOS->EmitIntValue(2, 2);
269 // Create a symbol for the end of the prologue (to be set when we get there).
270 MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
272 // Length of the prologue, is the next 4 bytes. Which is the start of the
273 // section to the end of the prologue. Not including the 4 bytes for the
274 // total length, the 2 bytes for the version, and these 4 bytes for the
275 // length of the prologue.
278 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
280 // Parameters of the state machine, are next.
281 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
282 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
283 MCOS->EmitIntValue(Params.DWARF2LineBase, 1);
284 MCOS->EmitIntValue(Params.DWARF2LineRange, 1);
285 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
287 // Standard opcode lengths
288 for (char Length : StandardOpcodeLengths)
289 MCOS->EmitIntValue(Length, 1);
291 // Put out the directory and file tables.
293 // First the directory table.
294 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
295 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
296 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
298 MCOS->EmitIntValue(0, 1); // Terminate the directory list
300 // Second the file table.
301 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
302 assert(!MCDwarfFiles[i].Name.empty());
303 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
304 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
306 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
307 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
308 MCOS->EmitIntValue(0, 1); // filesize (always 0)
310 MCOS->EmitIntValue(0, 1); // Terminate the file list
312 // This is the end of the prologue, so set the value of the symbol at the
313 // end of the prologue (that was used in a previous expression).
314 MCOS->EmitLabel(ProEndSym);
316 return std::make_pair(LineStartSym, LineEndSym);
319 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS,
320 MCDwarfLineTableParams Params) const {
321 MCSymbol *LineEndSym = Header.Emit(MCOS, Params).second;
323 // Put out the line tables.
324 for (const auto &LineSec : MCLineSections.getMCLineEntries())
325 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
327 // This is the end of the section, so set the value of the symbol at the end
328 // of this section (that was used in a previous expression).
329 MCOS->EmitLabel(LineEndSym);
332 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
333 unsigned FileNumber) {
334 return Header.getFile(Directory, FileName, FileNumber);
337 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
339 unsigned FileNumber) {
340 if (Directory == CompilationDir)
342 if (FileName.empty()) {
343 FileName = "<stdin>";
346 assert(!FileName.empty());
347 if (FileNumber == 0) {
348 // File numbers start with 1 and/or after any file numbers
349 // allocated by inline-assembler .file directives.
350 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
351 SmallString<256> Buffer;
352 auto IterBool = SourceIdMap.insert(
353 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
355 if (!IterBool.second)
356 return IterBool.first->second;
358 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
359 MCDwarfFiles.resize(FileNumber + 1);
361 // Get the new MCDwarfFile slot for this FileNumber.
362 MCDwarfFile &File = MCDwarfFiles[FileNumber];
364 // It is an error to use see the same number more than once.
365 if (!File.Name.empty())
368 if (Directory.empty()) {
369 // Separate the directory part from the basename of the FileName.
370 StringRef tFileName = sys::path::filename(FileName);
371 if (!tFileName.empty()) {
372 Directory = sys::path::parent_path(FileName);
373 if (!Directory.empty())
374 FileName = tFileName;
378 // Find or make an entry in the MCDwarfDirs vector for this Directory.
379 // Capture directory name.
381 if (Directory.empty()) {
382 // For FileNames with no directories a DirIndex of 0 is used.
386 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
387 if (Directory == MCDwarfDirs[DirIndex])
390 if (DirIndex >= MCDwarfDirs.size())
391 MCDwarfDirs.push_back(Directory);
392 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
393 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
394 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
395 // are stored at MCDwarfFiles[FileNumber].Name .
399 File.Name = FileName;
400 File.DirIndex = DirIndex;
402 // return the allocated FileNumber.
406 /// Utility function to emit the encoding to a streamer.
407 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
408 int64_t LineDelta, uint64_t AddrDelta) {
409 MCContext &Context = MCOS->getContext();
410 SmallString<256> Tmp;
411 raw_svector_ostream OS(Tmp);
412 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
413 MCOS->EmitBytes(OS.str());
416 /// Given a special op, return the address skip amount (in units of
417 /// DWARF2_LINE_MIN_INSN_LENGTH).
418 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
419 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
422 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
423 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
424 int64_t LineDelta, uint64_t AddrDelta,
426 uint64_t Temp, Opcode;
427 bool NeedCopy = false;
429 // The maximum address skip amount that can be encoded with a special op.
430 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
432 // Scale the address delta by the minimum instruction length.
433 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
435 // A LineDelta of INT64_MAX is a signal that this is actually a
436 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
437 // end_sequence to emit the matrix entry.
438 if (LineDelta == INT64_MAX) {
439 if (AddrDelta == MaxSpecialAddrDelta)
440 OS << char(dwarf::DW_LNS_const_add_pc);
441 else if (AddrDelta) {
442 OS << char(dwarf::DW_LNS_advance_pc);
443 encodeULEB128(AddrDelta, OS);
445 OS << char(dwarf::DW_LNS_extended_op);
447 OS << char(dwarf::DW_LNE_end_sequence);
451 // Bias the line delta by the base.
452 Temp = LineDelta - Params.DWARF2LineBase;
454 // If the line increment is out of range of a special opcode, we must encode
455 // it with DW_LNS_advance_line.
456 if (Temp >= Params.DWARF2LineRange ||
457 Temp + Params.DWARF2LineOpcodeBase > 255) {
458 OS << char(dwarf::DW_LNS_advance_line);
459 encodeSLEB128(LineDelta, OS);
462 Temp = 0 - Params.DWARF2LineBase;
466 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
467 if (LineDelta == 0 && AddrDelta == 0) {
468 OS << char(dwarf::DW_LNS_copy);
472 // Bias the opcode by the special opcode base.
473 Temp += Params.DWARF2LineOpcodeBase;
475 // Avoid overflow when addr_delta is large.
476 if (AddrDelta < 256 + MaxSpecialAddrDelta) {
477 // Try using a special opcode.
478 Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
484 // Try using DW_LNS_const_add_pc followed by special op.
485 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
487 OS << char(dwarf::DW_LNS_const_add_pc);
493 // Otherwise use DW_LNS_advance_pc.
494 OS << char(dwarf::DW_LNS_advance_pc);
495 encodeULEB128(AddrDelta, OS);
498 OS << char(dwarf::DW_LNS_copy);
500 assert(Temp <= 255 && "Buggy special opcode encoding.");
505 // Utility function to write a tuple for .debug_abbrev.
506 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
507 MCOS->EmitULEB128IntValue(Name);
508 MCOS->EmitULEB128IntValue(Form);
511 // When generating dwarf for assembly source files this emits
512 // the data for .debug_abbrev section which contains three DIEs.
513 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
514 MCContext &context = MCOS->getContext();
515 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
517 // DW_TAG_compile_unit DIE abbrev (1).
518 MCOS->EmitULEB128IntValue(1);
519 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
520 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
521 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, context.getDwarfVersion() >= 4
522 ? dwarf::DW_FORM_sec_offset
523 : dwarf::DW_FORM_data4);
524 if (context.getGenDwarfSectionSyms().size() > 1 &&
525 context.getDwarfVersion() >= 3) {
526 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, context.getDwarfVersion() >= 4
527 ? dwarf::DW_FORM_sec_offset
528 : dwarf::DW_FORM_data4);
530 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
531 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
533 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
534 if (!context.getCompilationDir().empty())
535 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
536 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
537 if (!DwarfDebugFlags.empty())
538 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
539 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
540 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
541 EmitAbbrev(MCOS, 0, 0);
543 // DW_TAG_label DIE abbrev (2).
544 MCOS->EmitULEB128IntValue(2);
545 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
546 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
547 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
548 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
549 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
550 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
551 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
552 EmitAbbrev(MCOS, 0, 0);
554 // DW_TAG_unspecified_parameters DIE abbrev (3).
555 MCOS->EmitULEB128IntValue(3);
556 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
557 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
558 EmitAbbrev(MCOS, 0, 0);
560 // Terminate the abbreviations for this compilation unit.
561 MCOS->EmitIntValue(0, 1);
564 // When generating dwarf for assembly source files this emits the data for
565 // .debug_aranges section. This section contains a header and a table of pairs
566 // of PointerSize'ed values for the address and size of section(s) with line
568 static void EmitGenDwarfAranges(MCStreamer *MCOS,
569 const MCSymbol *InfoSectionSymbol) {
570 MCContext &context = MCOS->getContext();
572 auto &Sections = context.getGenDwarfSectionSyms();
574 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
576 // This will be the length of the .debug_aranges section, first account for
577 // the size of each item in the header (see below where we emit these items).
578 int Length = 4 + 2 + 4 + 1 + 1;
580 // Figure the padding after the header before the table of address and size
581 // pairs who's values are PointerSize'ed.
582 const MCAsmInfo *asmInfo = context.getAsmInfo();
583 int AddrSize = asmInfo->getPointerSize();
584 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
585 if (Pad == 2 * AddrSize)
589 // Add the size of the pair of PointerSize'ed values for the address and size
590 // of each section we have in the table.
591 Length += 2 * AddrSize * Sections.size();
592 // And the pair of terminating zeros.
593 Length += 2 * AddrSize;
596 // Emit the header for this section.
597 // The 4 byte length not including the 4 byte value for the length.
598 MCOS->EmitIntValue(Length - 4, 4);
599 // The 2 byte version, which is 2.
600 MCOS->EmitIntValue(2, 2);
601 // The 4 byte offset to the compile unit in the .debug_info from the start
602 // of the .debug_info.
603 if (InfoSectionSymbol)
604 MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
605 asmInfo->needsDwarfSectionOffsetDirective());
607 MCOS->EmitIntValue(0, 4);
608 // The 1 byte size of an address.
609 MCOS->EmitIntValue(AddrSize, 1);
610 // The 1 byte size of a segment descriptor, we use a value of zero.
611 MCOS->EmitIntValue(0, 1);
612 // Align the header with the padding if needed, before we put out the table.
613 for(int i = 0; i < Pad; i++)
614 MCOS->EmitIntValue(0, 1);
616 // Now emit the table of pairs of PointerSize'ed values for the section
617 // addresses and sizes.
618 for (MCSection *Sec : Sections) {
619 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
620 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
621 assert(StartSymbol && "StartSymbol must not be NULL");
622 assert(EndSymbol && "EndSymbol must not be NULL");
624 const MCExpr *Addr = MCSymbolRefExpr::create(
625 StartSymbol, MCSymbolRefExpr::VK_None, context);
626 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
627 *StartSymbol, *EndSymbol, 0);
628 MCOS->EmitValue(Addr, AddrSize);
629 emitAbsValue(*MCOS, Size, AddrSize);
632 // And finally the pair of terminating zeros.
633 MCOS->EmitIntValue(0, AddrSize);
634 MCOS->EmitIntValue(0, AddrSize);
637 // When generating dwarf for assembly source files this emits the data for
638 // .debug_info section which contains three parts. The header, the compile_unit
639 // DIE and a list of label DIEs.
640 static void EmitGenDwarfInfo(MCStreamer *MCOS,
641 const MCSymbol *AbbrevSectionSymbol,
642 const MCSymbol *LineSectionSymbol,
643 const MCSymbol *RangesSectionSymbol) {
644 MCContext &context = MCOS->getContext();
646 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
648 // Create a symbol at the start and end of this section used in here for the
649 // expression to calculate the length in the header.
650 MCSymbol *InfoStart = context.createTempSymbol();
651 MCOS->EmitLabel(InfoStart);
652 MCSymbol *InfoEnd = context.createTempSymbol();
654 // First part: the header.
656 // The 4 byte total length of the information for this compilation unit, not
657 // including these 4 bytes.
658 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
659 emitAbsValue(*MCOS, Length, 4);
661 // The 2 byte DWARF version.
662 MCOS->EmitIntValue(context.getDwarfVersion(), 2);
664 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
665 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
666 // it is at the start of that section so this is zero.
667 if (AbbrevSectionSymbol == nullptr)
668 MCOS->EmitIntValue(0, 4);
670 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
671 AsmInfo.needsDwarfSectionOffsetDirective());
673 const MCAsmInfo *asmInfo = context.getAsmInfo();
674 int AddrSize = asmInfo->getPointerSize();
675 // The 1 byte size of an address.
676 MCOS->EmitIntValue(AddrSize, 1);
678 // Second part: the compile_unit DIE.
680 // The DW_TAG_compile_unit DIE abbrev (1).
681 MCOS->EmitULEB128IntValue(1);
683 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
684 // which is at the start of that section so this is zero.
685 if (LineSectionSymbol)
686 MCOS->EmitSymbolValue(LineSectionSymbol, 4,
687 AsmInfo.needsDwarfSectionOffsetDirective());
689 MCOS->EmitIntValue(0, 4);
691 if (RangesSectionSymbol) {
692 // There are multiple sections containing code, so we must use the
693 // .debug_ranges sections.
695 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
696 // to the address range list for this compilation unit.
697 MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
699 // If we only have one non-empty code section, we can use the simpler
700 // AT_low_pc and AT_high_pc attributes.
702 // Find the first (and only) non-empty text section
703 auto &Sections = context.getGenDwarfSectionSyms();
704 const auto TextSection = Sections.begin();
705 assert(TextSection != Sections.end() && "No text section found");
707 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
708 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
709 assert(StartSymbol && "StartSymbol must not be NULL");
710 assert(EndSymbol && "EndSymbol must not be NULL");
712 // AT_low_pc, the first address of the default .text section.
713 const MCExpr *Start = MCSymbolRefExpr::create(
714 StartSymbol, MCSymbolRefExpr::VK_None, context);
715 MCOS->EmitValue(Start, AddrSize);
717 // AT_high_pc, the last address of the default .text section.
718 const MCExpr *End = MCSymbolRefExpr::create(
719 EndSymbol, MCSymbolRefExpr::VK_None, context);
720 MCOS->EmitValue(End, AddrSize);
723 // AT_name, the name of the source file. Reconstruct from the first directory
724 // and file table entries.
725 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
726 if (MCDwarfDirs.size() > 0) {
727 MCOS->EmitBytes(MCDwarfDirs[0]);
728 MCOS->EmitBytes(sys::path::get_separator());
730 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
731 MCOS->getContext().getMCDwarfFiles();
732 MCOS->EmitBytes(MCDwarfFiles[1].Name);
733 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
735 // AT_comp_dir, the working directory the assembly was done in.
736 if (!context.getCompilationDir().empty()) {
737 MCOS->EmitBytes(context.getCompilationDir());
738 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
741 // AT_APPLE_flags, the command line arguments of the assembler tool.
742 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
743 if (!DwarfDebugFlags.empty()){
744 MCOS->EmitBytes(DwarfDebugFlags);
745 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
748 // AT_producer, the version of the assembler tool.
749 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
750 if (!DwarfDebugProducer.empty())
751 MCOS->EmitBytes(DwarfDebugProducer);
753 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
754 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
756 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
757 // draft has no standard code for assembler.
758 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
760 // Third part: the list of label DIEs.
762 // Loop on saved info for dwarf labels and create the DIEs for them.
763 const std::vector<MCGenDwarfLabelEntry> &Entries =
764 MCOS->getContext().getMCGenDwarfLabelEntries();
765 for (const auto &Entry : Entries) {
766 // The DW_TAG_label DIE abbrev (2).
767 MCOS->EmitULEB128IntValue(2);
769 // AT_name, of the label without any leading underbar.
770 MCOS->EmitBytes(Entry.getName());
771 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
773 // AT_decl_file, index into the file table.
774 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
776 // AT_decl_line, source line number.
777 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
779 // AT_low_pc, start address of the label.
780 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
781 MCSymbolRefExpr::VK_None, context);
782 MCOS->EmitValue(AT_low_pc, AddrSize);
784 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
785 MCOS->EmitIntValue(0, 1);
787 // The DW_TAG_unspecified_parameters DIE abbrev (3).
788 MCOS->EmitULEB128IntValue(3);
790 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
791 MCOS->EmitIntValue(0, 1);
794 // Add the NULL DIE terminating the Compile Unit DIE's.
795 MCOS->EmitIntValue(0, 1);
797 // Now set the value of the symbol at the end of the info section.
798 MCOS->EmitLabel(InfoEnd);
801 // When generating dwarf for assembly source files this emits the data for
802 // .debug_ranges section. We only emit one range list, which spans all of the
803 // executable sections of this file.
804 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
805 MCContext &context = MCOS->getContext();
806 auto &Sections = context.getGenDwarfSectionSyms();
808 const MCAsmInfo *AsmInfo = context.getAsmInfo();
809 int AddrSize = AsmInfo->getPointerSize();
811 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
813 for (MCSection *Sec : Sections) {
814 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
815 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
816 assert(StartSymbol && "StartSymbol must not be NULL");
817 assert(EndSymbol && "EndSymbol must not be NULL");
819 // Emit a base address selection entry for the start of this section
820 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
821 StartSymbol, MCSymbolRefExpr::VK_None, context);
822 MCOS->emitFill(AddrSize, 0xFF);
823 MCOS->EmitValue(SectionStartAddr, AddrSize);
825 // Emit a range list entry spanning this section
826 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
827 *StartSymbol, *EndSymbol, 0);
828 MCOS->EmitIntValue(0, AddrSize);
829 emitAbsValue(*MCOS, SectionSize, AddrSize);
832 // Emit end of list entry
833 MCOS->EmitIntValue(0, AddrSize);
834 MCOS->EmitIntValue(0, AddrSize);
838 // When generating dwarf for assembly source files this emits the Dwarf
841 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
842 MCContext &context = MCOS->getContext();
844 // Create the dwarf sections in this order (.debug_line already created).
845 const MCAsmInfo *AsmInfo = context.getAsmInfo();
846 bool CreateDwarfSectionSymbols =
847 AsmInfo->doesDwarfUseRelocationsAcrossSections();
848 MCSymbol *LineSectionSymbol = nullptr;
849 if (CreateDwarfSectionSymbols)
850 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
851 MCSymbol *AbbrevSectionSymbol = nullptr;
852 MCSymbol *InfoSectionSymbol = nullptr;
853 MCSymbol *RangesSectionSymbol = nullptr;
855 // Create end symbols for each section, and remove empty sections
856 MCOS->getContext().finalizeDwarfSections(*MCOS);
858 // If there are no sections to generate debug info for, we don't need
860 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
863 // We only use the .debug_ranges section if we have multiple code sections,
864 // and we are emitting a DWARF version which supports it.
865 const bool UseRangesSection =
866 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
867 MCOS->getContext().getDwarfVersion() >= 3;
868 CreateDwarfSectionSymbols |= UseRangesSection;
870 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
871 if (CreateDwarfSectionSymbols) {
872 InfoSectionSymbol = context.createTempSymbol();
873 MCOS->EmitLabel(InfoSectionSymbol);
875 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
876 if (CreateDwarfSectionSymbols) {
877 AbbrevSectionSymbol = context.createTempSymbol();
878 MCOS->EmitLabel(AbbrevSectionSymbol);
880 if (UseRangesSection) {
881 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
882 if (CreateDwarfSectionSymbols) {
883 RangesSectionSymbol = context.createTempSymbol();
884 MCOS->EmitLabel(RangesSectionSymbol);
888 assert((RangesSectionSymbol != NULL) || !UseRangesSection);
890 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
892 // Output the data for .debug_aranges section.
893 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
895 if (UseRangesSection)
896 EmitGenDwarfRanges(MCOS);
898 // Output the data for .debug_abbrev section.
899 EmitGenDwarfAbbrev(MCOS);
901 // Output the data for .debug_info section.
902 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
903 RangesSectionSymbol);
907 // When generating dwarf for assembly source files this is called when symbol
908 // for a label is created. If this symbol is not a temporary and is in the
909 // section that dwarf is being generated for, save the needed info to create
912 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
913 SourceMgr &SrcMgr, SMLoc &Loc) {
914 // We won't create dwarf labels for temporary symbols.
915 if (Symbol->isTemporary())
917 MCContext &context = MCOS->getContext();
918 // We won't create dwarf labels for symbols in sections that we are not
919 // generating debug info for.
920 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
923 // The dwarf label's name does not have the symbol name's leading
925 StringRef Name = Symbol->getName();
926 if (Name.startswith("_"))
927 Name = Name.substr(1, Name.size()-1);
929 // Get the dwarf file number to be used for the dwarf label.
930 unsigned FileNumber = context.getGenDwarfFileNumber();
932 // Finding the line number is the expensive part which is why we just don't
933 // pass it in as for some symbols we won't create a dwarf label.
934 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
935 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
937 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
938 // values so that they don't have things like an ARM thumb bit from the
939 // original symbol. So when used they won't get a low bit set after
941 MCSymbol *Label = context.createTempSymbol();
942 MCOS->EmitLabel(Label);
944 // Create and entry for the info and add it to the other entries.
945 MCOS->getContext().addMCGenDwarfLabelEntry(
946 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
949 static int getDataAlignmentFactor(MCStreamer &streamer) {
950 MCContext &context = streamer.getContext();
951 const MCAsmInfo *asmInfo = context.getAsmInfo();
952 int size = asmInfo->getCalleeSaveStackSlotSize();
953 if (asmInfo->isStackGrowthDirectionUp())
959 static unsigned getSizeForEncoding(MCStreamer &streamer,
960 unsigned symbolEncoding) {
961 MCContext &context = streamer.getContext();
962 unsigned format = symbolEncoding & 0x0f;
964 default: llvm_unreachable("Unknown Encoding");
965 case dwarf::DW_EH_PE_absptr:
966 case dwarf::DW_EH_PE_signed:
967 return context.getAsmInfo()->getPointerSize();
968 case dwarf::DW_EH_PE_udata2:
969 case dwarf::DW_EH_PE_sdata2:
971 case dwarf::DW_EH_PE_udata4:
972 case dwarf::DW_EH_PE_sdata4:
974 case dwarf::DW_EH_PE_udata8:
975 case dwarf::DW_EH_PE_sdata8:
980 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
981 unsigned symbolEncoding, bool isEH) {
982 MCContext &context = streamer.getContext();
983 const MCAsmInfo *asmInfo = context.getAsmInfo();
984 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
987 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
988 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
989 emitAbsValue(streamer, v, size);
991 streamer.EmitValue(v, size);
994 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
995 unsigned symbolEncoding) {
996 MCContext &context = streamer.getContext();
997 const MCAsmInfo *asmInfo = context.getAsmInfo();
998 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1001 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1002 streamer.EmitValue(v, size);
1006 class FrameEmitterImpl {
1008 int InitialCFAOffset = 0;
1010 MCObjectStreamer &Streamer;
1013 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1014 : IsEH(IsEH), Streamer(Streamer) {}
1016 /// Emit the unwind information in a compact way.
1017 void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1019 const MCSymbol &EmitCIE(const MCSymbol *personality,
1020 unsigned personalityEncoding, const MCSymbol *lsda,
1021 bool IsSignalFrame, unsigned lsdaEncoding,
1023 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1024 bool LastInSection, const MCSymbol &SectionStart);
1025 void EmitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1026 MCSymbol *BaseLabel);
1027 void EmitCFIInstruction(const MCCFIInstruction &Instr);
1030 } // end anonymous namespace
1032 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1033 Streamer.EmitIntValue(Encoding, 1);
1036 void FrameEmitterImpl::EmitCFIInstruction(const MCCFIInstruction &Instr) {
1037 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1038 auto *MRI = Streamer.getContext().getRegisterInfo();
1040 switch (Instr.getOperation()) {
1041 case MCCFIInstruction::OpRegister: {
1042 unsigned Reg1 = Instr.getRegister();
1043 unsigned Reg2 = Instr.getRegister2();
1045 Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false);
1046 Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false);
1048 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1049 Streamer.EmitULEB128IntValue(Reg1);
1050 Streamer.EmitULEB128IntValue(Reg2);
1053 case MCCFIInstruction::OpWindowSave: {
1054 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1057 case MCCFIInstruction::OpUndefined: {
1058 unsigned Reg = Instr.getRegister();
1059 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1060 Streamer.EmitULEB128IntValue(Reg);
1063 case MCCFIInstruction::OpAdjustCfaOffset:
1064 case MCCFIInstruction::OpDefCfaOffset: {
1065 const bool IsRelative =
1066 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1068 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1071 CFAOffset += Instr.getOffset();
1073 CFAOffset = -Instr.getOffset();
1075 Streamer.EmitULEB128IntValue(CFAOffset);
1079 case MCCFIInstruction::OpDefCfa: {
1080 unsigned Reg = Instr.getRegister();
1082 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1083 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1084 Streamer.EmitULEB128IntValue(Reg);
1085 CFAOffset = -Instr.getOffset();
1086 Streamer.EmitULEB128IntValue(CFAOffset);
1091 case MCCFIInstruction::OpDefCfaRegister: {
1092 unsigned Reg = Instr.getRegister();
1094 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1095 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1096 Streamer.EmitULEB128IntValue(Reg);
1101 case MCCFIInstruction::OpOffset:
1102 case MCCFIInstruction::OpRelOffset: {
1103 const bool IsRelative =
1104 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1106 unsigned Reg = Instr.getRegister();
1108 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1110 int Offset = Instr.getOffset();
1112 Offset -= CFAOffset;
1113 Offset = Offset / dataAlignmentFactor;
1116 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1117 Streamer.EmitULEB128IntValue(Reg);
1118 Streamer.EmitSLEB128IntValue(Offset);
1119 } else if (Reg < 64) {
1120 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1121 Streamer.EmitULEB128IntValue(Offset);
1123 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1124 Streamer.EmitULEB128IntValue(Reg);
1125 Streamer.EmitULEB128IntValue(Offset);
1129 case MCCFIInstruction::OpRememberState:
1130 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1132 case MCCFIInstruction::OpRestoreState:
1133 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1135 case MCCFIInstruction::OpSameValue: {
1136 unsigned Reg = Instr.getRegister();
1137 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1138 Streamer.EmitULEB128IntValue(Reg);
1141 case MCCFIInstruction::OpRestore: {
1142 unsigned Reg = Instr.getRegister();
1144 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1145 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1148 case MCCFIInstruction::OpGnuArgsSize: {
1149 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_args_size, 1);
1150 Streamer.EmitULEB128IntValue(Instr.getOffset());
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(ArrayRef<MCCFIInstruction> Instrs,
1162 MCSymbol *BaseLabel) {
1163 for (const MCCFIInstruction &Instr : Instrs) {
1164 MCSymbol *Label = Instr.getLabel();
1165 // Throw out move if the label is invalid.
1166 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1168 // Advance row if new location.
1169 if (BaseLabel && Label) {
1170 MCSymbol *ThisSym = Label;
1171 if (ThisSym != BaseLabel) {
1172 Streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1173 BaseLabel = ThisSym;
1177 EmitCFIInstruction(Instr);
1181 /// Emit the unwind information in a compact way.
1182 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1183 MCContext &Context = Streamer.getContext();
1184 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1186 // range-start range-length compact-unwind-enc personality-func lsda
1187 // _foo LfooEnd-_foo 0x00000023 0 0
1188 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1190 // .section __LD,__compact_unwind,regular,debug
1192 // # compact unwind for _foo
1194 // .set L1,LfooEnd-_foo
1200 // # compact unwind for _bar
1202 // .set L2,LbarEnd-_bar
1205 // .quad __gxx_personality
1206 // .quad except_tab1
1208 uint32_t Encoding = Frame.CompactUnwindEncoding;
1209 if (!Encoding) return;
1210 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1212 // The encoding needs to know we have an LSDA.
1213 if (!DwarfEHFrameOnly && Frame.Lsda)
1214 Encoding |= 0x40000000;
1217 unsigned FDEEncoding = MOFI->getFDEEncoding();
1218 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1219 Streamer.EmitSymbolValue(Frame.Begin, Size);
1222 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1224 emitAbsValue(Streamer, Range, 4);
1227 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1228 Streamer.EmitIntValue(Encoding, Size);
1230 // Personality Function
1231 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1232 if (!DwarfEHFrameOnly && Frame.Personality)
1233 Streamer.EmitSymbolValue(Frame.Personality, Size);
1235 Streamer.EmitIntValue(0, Size); // No personality fn
1238 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1239 if (!DwarfEHFrameOnly && Frame.Lsda)
1240 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1242 Streamer.EmitIntValue(0, Size); // No LSDA
1245 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1248 switch (DwarfVersion) {
1257 llvm_unreachable("Unknown version");
1260 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCSymbol *personality,
1261 unsigned personalityEncoding,
1262 const MCSymbol *lsda,
1264 unsigned lsdaEncoding,
1266 MCContext &context = Streamer.getContext();
1267 const MCRegisterInfo *MRI = context.getRegisterInfo();
1268 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1270 MCSymbol *sectionStart = context.createTempSymbol();
1271 Streamer.EmitLabel(sectionStart);
1273 MCSymbol *sectionEnd = context.createTempSymbol();
1276 const MCExpr *Length =
1277 MakeStartMinusEndExpr(Streamer, *sectionStart, *sectionEnd, 4);
1278 emitAbsValue(Streamer, Length, 4);
1281 unsigned CIE_ID = IsEH ? 0 : -1;
1282 Streamer.EmitIntValue(CIE_ID, 4);
1285 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1286 Streamer.EmitIntValue(CIEVersion, 1);
1288 // Augmentation String
1289 SmallString<8> Augmentation;
1291 Augmentation += "z";
1293 Augmentation += "P";
1295 Augmentation += "L";
1296 Augmentation += "R";
1298 Augmentation += "S";
1299 Streamer.EmitBytes(Augmentation);
1301 Streamer.EmitIntValue(0, 1);
1303 if (CIEVersion >= 4) {
1305 Streamer.EmitIntValue(context.getAsmInfo()->getPointerSize(), 1);
1307 // Segment Descriptor Size
1308 Streamer.EmitIntValue(0, 1);
1311 // Code Alignment Factor
1312 Streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1314 // Data Alignment Factor
1315 Streamer.EmitSLEB128IntValue(getDataAlignmentFactor(Streamer));
1317 // Return Address Register
1318 if (CIEVersion == 1) {
1319 assert(MRI->getRARegister() <= 255 &&
1320 "DWARF 2 encodes return_address_register in one byte");
1321 Streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1);
1323 Streamer.EmitULEB128IntValue(
1324 MRI->getDwarfRegNum(MRI->getRARegister(), IsEH));
1327 // Augmentation Data Length (optional)
1329 unsigned augmentationLength = 0;
1332 // Personality Encoding
1333 augmentationLength += 1;
1335 augmentationLength += getSizeForEncoding(Streamer, personalityEncoding);
1338 augmentationLength += 1;
1339 // Encoding of the FDE pointers
1340 augmentationLength += 1;
1342 Streamer.EmitULEB128IntValue(augmentationLength);
1344 // Augmentation Data (optional)
1346 // Personality Encoding
1347 emitEncodingByte(Streamer, personalityEncoding);
1349 EmitPersonality(Streamer, *personality, personalityEncoding);
1353 emitEncodingByte(Streamer, lsdaEncoding);
1355 // Encoding of the FDE pointers
1356 emitEncodingByte(Streamer, MOFI->getFDEEncoding());
1359 // Initial Instructions
1361 const MCAsmInfo *MAI = context.getAsmInfo();
1363 const std::vector<MCCFIInstruction> &Instructions =
1364 MAI->getInitialFrameState();
1365 EmitCFIInstructions(Instructions, nullptr);
1368 InitialCFAOffset = CFAOffset;
1371 Streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1373 Streamer.EmitLabel(sectionEnd);
1374 return *sectionStart;
1377 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
1378 const MCDwarfFrameInfo &frame,
1380 const MCSymbol &SectionStart) {
1381 MCContext &context = Streamer.getContext();
1382 MCSymbol *fdeStart = context.createTempSymbol();
1383 MCSymbol *fdeEnd = context.createTempSymbol();
1384 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1386 CFAOffset = InitialCFAOffset;
1389 const MCExpr *Length = MakeStartMinusEndExpr(Streamer, *fdeStart, *fdeEnd, 0);
1390 emitAbsValue(Streamer, Length, 4);
1392 Streamer.EmitLabel(fdeStart);
1395 const MCAsmInfo *asmInfo = context.getAsmInfo();
1397 const MCExpr *offset =
1398 MakeStartMinusEndExpr(Streamer, cieStart, *fdeStart, 0);
1399 emitAbsValue(Streamer, offset, 4);
1400 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1401 const MCExpr *offset =
1402 MakeStartMinusEndExpr(Streamer, SectionStart, cieStart, 0);
1403 emitAbsValue(Streamer, offset, 4);
1405 Streamer.EmitSymbolValue(&cieStart, 4);
1409 unsigned PCEncoding =
1410 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1411 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
1412 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
1415 const MCExpr *Range =
1416 MakeStartMinusEndExpr(Streamer, *frame.Begin, *frame.End, 0);
1417 emitAbsValue(Streamer, Range, PCSize);
1420 // Augmentation Data Length
1421 unsigned augmentationLength = 0;
1424 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
1426 Streamer.EmitULEB128IntValue(augmentationLength);
1428 // Augmentation Data
1430 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
1433 // Call Frame Instructions
1434 EmitCFIInstructions(frame.Instructions, frame.Begin);
1437 // The size of a .eh_frame section has to be a multiple of the alignment
1438 // since a null CIE is interpreted as the end. Old systems overaligned
1439 // .eh_frame, so we do too and account for it in the last FDE.
1440 unsigned Align = LastInSection ? asmInfo->getPointerSize() : PCSize;
1441 Streamer.EmitValueToAlignment(Align);
1443 Streamer.EmitLabel(fdeEnd);
1448 static const CIEKey getEmptyKey() {
1449 return CIEKey(nullptr, 0, -1, false, false);
1451 static const CIEKey getTombstoneKey() {
1452 return CIEKey(nullptr, -1, 0, false, false);
1455 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
1456 unsigned LsdaEncoding, bool IsSignalFrame, bool IsSimple)
1457 : Personality(Personality), PersonalityEncoding(PersonalityEncoding),
1458 LsdaEncoding(LsdaEncoding), IsSignalFrame(IsSignalFrame),
1459 IsSimple(IsSimple) {}
1460 const MCSymbol *Personality;
1461 unsigned PersonalityEncoding;
1462 unsigned LsdaEncoding;
1466 } // anonymous namespace
1469 template <> struct DenseMapInfo<CIEKey> {
1470 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
1471 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
1472 static unsigned getHashValue(const CIEKey &Key) {
1473 return static_cast<unsigned>(
1474 hash_combine(Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
1475 Key.IsSignalFrame, Key.IsSimple));
1477 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
1478 return LHS.Personality == RHS.Personality &&
1479 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1480 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1481 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1482 LHS.IsSimple == RHS.IsSimple;
1487 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1489 Streamer.generateCompactUnwindEncodings(MAB);
1491 MCContext &Context = Streamer.getContext();
1492 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1493 FrameEmitterImpl Emitter(IsEH, Streamer);
1494 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1496 // Emit the compact unwind info if available.
1497 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1498 if (IsEH && MOFI->getCompactUnwindSection()) {
1499 bool SectionEmitted = false;
1500 for (const MCDwarfFrameInfo &Frame : FrameArray) {
1501 if (Frame.CompactUnwindEncoding == 0) continue;
1502 if (!SectionEmitted) {
1503 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1504 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1505 SectionEmitted = true;
1507 NeedsEHFrameSection |=
1508 Frame.CompactUnwindEncoding ==
1509 MOFI->getCompactUnwindDwarfEHFrameOnly();
1510 Emitter.EmitCompactUnwind(Frame);
1514 if (!NeedsEHFrameSection) return;
1516 MCSection &Section =
1517 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1518 : *MOFI->getDwarfFrameSection();
1520 Streamer.SwitchSection(&Section);
1521 MCSymbol *SectionStart = Context.createTempSymbol();
1522 Streamer.EmitLabel(SectionStart);
1524 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1526 const MCSymbol *DummyDebugKey = nullptr;
1527 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
1528 for (auto I = FrameArray.begin(), E = FrameArray.end(); I != E;) {
1529 const MCDwarfFrameInfo &Frame = *I;
1531 if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
1532 MOFI->getCompactUnwindDwarfEHFrameOnly())
1533 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1534 // of by the compact unwind encoding.
1537 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1538 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1539 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1541 CIEStart = &Emitter.EmitCIE(Frame.Personality, Frame.PersonalityEncoding,
1542 Frame.Lsda, Frame.IsSignalFrame,
1543 Frame.LsdaEncoding, Frame.IsSimple);
1545 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
1549 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1550 uint64_t AddrDelta) {
1551 MCContext &Context = Streamer.getContext();
1552 SmallString<256> Tmp;
1553 raw_svector_ostream OS(Tmp);
1554 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1555 Streamer.EmitBytes(OS.str());
1558 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1561 // Scale the address delta by the minimum instruction length.
1562 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1564 if (AddrDelta == 0) {
1565 } else if (isUIntN(6, AddrDelta)) {
1566 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1568 } else if (isUInt<8>(AddrDelta)) {
1569 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1570 OS << uint8_t(AddrDelta);
1571 } else if (isUInt<16>(AddrDelta)) {
1572 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1573 if (Context.getAsmInfo()->isLittleEndian())
1574 support::endian::Writer<support::little>(OS).write<uint16_t>(AddrDelta);
1576 support::endian::Writer<support::big>(OS).write<uint16_t>(AddrDelta);
1578 assert(isUInt<32>(AddrDelta));
1579 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1580 if (Context.getAsmInfo()->isLittleEndian())
1581 support::endian::Writer<support::little>(OS).write<uint32_t>(AddrDelta);
1583 support::endian::Writer<support::big>(OS).write<uint32_t>(AddrDelta);