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, const 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, const 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 // Using the pointer Section create a temporary label at the end of the
183 // section and use that and the LastLabel to compute the address delta
184 // and use INT64_MAX as the line delta which is the signal that this is
185 // actually a DW_LNE_end_sequence.
187 // Switch to the section to be able to create a symbol at its end.
188 // TODO: keep track of the last subsection so that this symbol appears in the
190 MCOS->SwitchSection(Section);
192 MCContext &context = MCOS->getContext();
193 // Create a symbol at the end of the section.
194 MCSymbol *SectionEnd = context.CreateTempSymbol();
195 // Set the value of the symbol, as we are at the end of the section.
196 MCOS->EmitLabel(SectionEnd);
198 // Switch back the dwarf line section.
199 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
201 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
202 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
203 asmInfo->getPointerSize());
207 // This emits the Dwarf file and the line tables.
209 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS) {
210 MCContext &context = MCOS->getContext();
212 auto &LineTables = context.getMCDwarfLineTables();
214 // Bail out early so we don't switch to the debug_line section needlessly and
215 // in doing so create an unnecessary (if empty) section.
216 if (LineTables.empty())
219 // Switch to the section where the table will be emitted into.
220 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
222 // Handle the rest of the Compile Units.
223 for (const auto &CUIDTablePair : LineTables)
224 CUIDTablePair.second.EmitCU(MCOS);
227 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
228 MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
231 std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
232 static const char StandardOpcodeLengths[] = {
233 0, // length of DW_LNS_copy
234 1, // length of DW_LNS_advance_pc
235 1, // length of DW_LNS_advance_line
236 1, // length of DW_LNS_set_file
237 1, // length of DW_LNS_set_column
238 0, // length of DW_LNS_negate_stmt
239 0, // length of DW_LNS_set_basic_block
240 0, // length of DW_LNS_const_add_pc
241 1, // length of DW_LNS_fixed_advance_pc
242 0, // length of DW_LNS_set_prologue_end
243 0, // length of DW_LNS_set_epilogue_begin
246 assert(array_lengthof(StandardOpcodeLengths) == (DWARF2_LINE_OPCODE_BASE - 1));
247 return Emit(MCOS, StandardOpcodeLengths);
250 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
251 MCContext &Context = OS.getContext();
252 assert(!isa<MCSymbolRefExpr>(Expr));
253 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
256 MCSymbol *ABS = Context.CreateTempSymbol();
257 OS.EmitAssignment(ABS, Expr);
258 return MCSymbolRefExpr::Create(ABS, Context);
261 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
262 const MCExpr *ABS = forceExpAbs(OS, Value);
263 OS.EmitValue(ABS, Size);
266 std::pair<MCSymbol *, MCSymbol *>
267 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
268 ArrayRef<char> StandardOpcodeLengths) const {
270 MCContext &context = MCOS->getContext();
272 // Create a symbol at the beginning of the line table.
273 MCSymbol *LineStartSym = Label;
275 LineStartSym = context.CreateTempSymbol();
276 // Set the value of the symbol, as we are at the start of the line table.
277 MCOS->EmitLabel(LineStartSym);
279 // Create a symbol for the end of the section (to be set when we get there).
280 MCSymbol *LineEndSym = context.CreateTempSymbol();
282 // The first 4 bytes is the total length of the information for this
283 // compilation unit (not including these 4 bytes for the length).
285 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
287 // Next 2 bytes is the Version, which is Dwarf 2.
288 MCOS->EmitIntValue(2, 2);
290 // Create a symbol for the end of the prologue (to be set when we get there).
291 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
293 // Length of the prologue, is the next 4 bytes. Which is the start of the
294 // section to the end of the prologue. Not including the 4 bytes for the
295 // total length, the 2 bytes for the version, and these 4 bytes for the
296 // length of the prologue.
299 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
301 // Parameters of the state machine, are next.
302 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
303 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
304 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
305 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
306 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
308 // Standard opcode lengths
309 for (char Length : StandardOpcodeLengths)
310 MCOS->EmitIntValue(Length, 1);
312 // Put out the directory and file tables.
314 // First the directory table.
315 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
316 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
317 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
319 MCOS->EmitIntValue(0, 1); // Terminate the directory list
321 // Second the file table.
322 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
323 assert(!MCDwarfFiles[i].Name.empty());
324 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
325 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
327 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
328 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
329 MCOS->EmitIntValue(0, 1); // filesize (always 0)
331 MCOS->EmitIntValue(0, 1); // Terminate the file list
333 // This is the end of the prologue, so set the value of the symbol at the
334 // end of the prologue (that was used in a previous expression).
335 MCOS->EmitLabel(ProEndSym);
337 return std::make_pair(LineStartSym, LineEndSym);
340 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS) const {
341 MCSymbol *LineEndSym = Header.Emit(MCOS).second;
343 // Put out the line tables.
344 for (const auto &LineSec : MCLineSections.getMCLineEntries())
345 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
347 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
348 MCLineSections.getMCLineEntries().empty()) {
349 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
351 // total_length >= prologue_length + 10
352 // We are 4 bytes short, since we have total_length = 51 and
353 // prologue_length = 45
355 // The regular end_sequence should be sufficient.
356 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
359 // This is the end of the section, so set the value of the symbol at the end
360 // of this section (that was used in a previous expression).
361 MCOS->EmitLabel(LineEndSym);
364 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
365 unsigned FileNumber) {
366 return Header.getFile(Directory, FileName, FileNumber);
369 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
371 unsigned FileNumber) {
372 if (Directory == CompilationDir)
374 if (FileName.empty()) {
375 FileName = "<stdin>";
378 assert(!FileName.empty());
379 if (FileNumber == 0) {
380 FileNumber = SourceIdMap.size() + 1;
381 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
382 "Don't mix autonumbered and explicit numbered line table usage");
383 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(
384 (Directory + Twine('\0') + FileName).str(), FileNumber);
385 if (Ent.getValue() != FileNumber)
386 return Ent.getValue();
388 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
389 MCDwarfFiles.resize(FileNumber + 1);
391 // Get the new MCDwarfFile slot for this FileNumber.
392 MCDwarfFile &File = MCDwarfFiles[FileNumber];
394 // It is an error to use see the same number more than once.
395 if (!File.Name.empty())
398 if (Directory.empty()) {
399 // Separate the directory part from the basename of the FileName.
400 StringRef tFileName = sys::path::filename(FileName);
401 if (!tFileName.empty()) {
402 Directory = sys::path::parent_path(FileName);
403 if (!Directory.empty())
404 FileName = tFileName;
408 // Find or make an entry in the MCDwarfDirs vector for this Directory.
409 // Capture directory name.
411 if (Directory.empty()) {
412 // For FileNames with no directories a DirIndex of 0 is used.
416 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
417 if (Directory == MCDwarfDirs[DirIndex])
420 if (DirIndex >= MCDwarfDirs.size())
421 MCDwarfDirs.push_back(Directory);
422 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
423 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
424 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
425 // are stored at MCDwarfFiles[FileNumber].Name .
429 File.Name = FileName;
430 File.DirIndex = DirIndex;
432 // return the allocated FileNumber.
436 /// Utility function to emit the encoding to a streamer.
437 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
438 uint64_t AddrDelta) {
439 MCContext &Context = MCOS->getContext();
440 SmallString<256> Tmp;
441 raw_svector_ostream OS(Tmp);
442 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
443 MCOS->EmitBytes(OS.str());
446 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
447 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
448 uint64_t AddrDelta, raw_ostream &OS) {
449 uint64_t Temp, Opcode;
450 bool NeedCopy = false;
452 // Scale the address delta by the minimum instruction length.
453 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
455 // A LineDelta of INT64_MAX is a signal that this is actually a
456 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
457 // end_sequence to emit the matrix entry.
458 if (LineDelta == INT64_MAX) {
459 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
460 OS << char(dwarf::DW_LNS_const_add_pc);
462 OS << char(dwarf::DW_LNS_advance_pc);
463 encodeULEB128(AddrDelta, OS);
465 OS << char(dwarf::DW_LNS_extended_op);
467 OS << char(dwarf::DW_LNE_end_sequence);
471 // Bias the line delta by the base.
472 Temp = LineDelta - DWARF2_LINE_BASE;
474 // If the line increment is out of range of a special opcode, we must encode
475 // it with DW_LNS_advance_line.
476 if (Temp >= DWARF2_LINE_RANGE) {
477 OS << char(dwarf::DW_LNS_advance_line);
478 encodeSLEB128(LineDelta, OS);
481 Temp = 0 - DWARF2_LINE_BASE;
485 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
486 if (LineDelta == 0 && AddrDelta == 0) {
487 OS << char(dwarf::DW_LNS_copy);
491 // Bias the opcode by the special opcode base.
492 Temp += DWARF2_LINE_OPCODE_BASE;
494 // Avoid overflow when addr_delta is large.
495 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
496 // Try using a special opcode.
497 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
503 // Try using DW_LNS_const_add_pc followed by special op.
504 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
506 OS << char(dwarf::DW_LNS_const_add_pc);
512 // Otherwise use DW_LNS_advance_pc.
513 OS << char(dwarf::DW_LNS_advance_pc);
514 encodeULEB128(AddrDelta, OS);
517 OS << char(dwarf::DW_LNS_copy);
522 // Utility function to write a tuple for .debug_abbrev.
523 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
524 MCOS->EmitULEB128IntValue(Name);
525 MCOS->EmitULEB128IntValue(Form);
528 // When generating dwarf for assembly source files this emits
529 // the data for .debug_abbrev section which contains three DIEs.
530 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
531 MCContext &context = MCOS->getContext();
532 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
534 // DW_TAG_compile_unit DIE abbrev (1).
535 MCOS->EmitULEB128IntValue(1);
536 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
537 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
538 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
539 if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
540 MCOS->getContext().getDwarfVersion() >= 3) {
541 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
543 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
544 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
546 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
547 if (!context.getCompilationDir().empty())
548 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
549 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
550 if (!DwarfDebugFlags.empty())
551 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
552 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
553 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
554 EmitAbbrev(MCOS, 0, 0);
556 // DW_TAG_label DIE abbrev (2).
557 MCOS->EmitULEB128IntValue(2);
558 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
559 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
560 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
561 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
562 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
563 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
564 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
565 EmitAbbrev(MCOS, 0, 0);
567 // DW_TAG_unspecified_parameters DIE abbrev (3).
568 MCOS->EmitULEB128IntValue(3);
569 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
570 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
571 EmitAbbrev(MCOS, 0, 0);
573 // Terminate the abbreviations for this compilation unit.
574 MCOS->EmitIntValue(0, 1);
577 // When generating dwarf for assembly source files this emits the data for
578 // .debug_aranges section. This section contains a header and a table of pairs
579 // of PointerSize'ed values for the address and size of section(s) with line
581 static void EmitGenDwarfAranges(MCStreamer *MCOS,
582 const MCSymbol *InfoSectionSymbol) {
583 MCContext &context = MCOS->getContext();
585 auto &Sections = context.getGenDwarfSectionSyms();
587 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
589 // This will be the length of the .debug_aranges section, first account for
590 // the size of each item in the header (see below where we emit these items).
591 int Length = 4 + 2 + 4 + 1 + 1;
593 // Figure the padding after the header before the table of address and size
594 // pairs who's values are PointerSize'ed.
595 const MCAsmInfo *asmInfo = context.getAsmInfo();
596 int AddrSize = asmInfo->getPointerSize();
597 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
598 if (Pad == 2 * AddrSize)
602 // Add the size of the pair of PointerSize'ed values for the address and size
603 // of each section we have in the table.
604 Length += 2 * AddrSize * Sections.size();
605 // And the pair of terminating zeros.
606 Length += 2 * AddrSize;
609 // Emit the header for this section.
610 // The 4 byte length not including the 4 byte value for the length.
611 MCOS->EmitIntValue(Length - 4, 4);
612 // The 2 byte version, which is 2.
613 MCOS->EmitIntValue(2, 2);
614 // The 4 byte offset to the compile unit in the .debug_info from the start
615 // of the .debug_info.
616 if (InfoSectionSymbol)
617 MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
618 asmInfo->needsDwarfSectionOffsetDirective());
620 MCOS->EmitIntValue(0, 4);
621 // The 1 byte size of an address.
622 MCOS->EmitIntValue(AddrSize, 1);
623 // The 1 byte size of a segment descriptor, we use a value of zero.
624 MCOS->EmitIntValue(0, 1);
625 // Align the header with the padding if needed, before we put out the table.
626 for(int i = 0; i < Pad; i++)
627 MCOS->EmitIntValue(0, 1);
629 // Now emit the table of pairs of PointerSize'ed values for the section
630 // addresses and sizes.
631 for (const auto &sec : Sections) {
632 MCSymbol *StartSymbol = sec.second.first;
633 MCSymbol *EndSymbol = sec.second.second;
634 assert(StartSymbol && "StartSymbol must not be NULL");
635 assert(EndSymbol && "EndSymbol must not be NULL");
637 const MCExpr *Addr = MCSymbolRefExpr::Create(
638 StartSymbol, MCSymbolRefExpr::VK_None, context);
639 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
640 *StartSymbol, *EndSymbol, 0);
641 MCOS->EmitValue(Addr, AddrSize);
642 emitAbsValue(*MCOS, Size, AddrSize);
645 // And finally the pair of terminating zeros.
646 MCOS->EmitIntValue(0, AddrSize);
647 MCOS->EmitIntValue(0, AddrSize);
650 // When generating dwarf for assembly source files this emits the data for
651 // .debug_info section which contains three parts. The header, the compile_unit
652 // DIE and a list of label DIEs.
653 static void EmitGenDwarfInfo(MCStreamer *MCOS,
654 const MCSymbol *AbbrevSectionSymbol,
655 const MCSymbol *LineSectionSymbol,
656 const MCSymbol *RangesSectionSymbol) {
657 MCContext &context = MCOS->getContext();
659 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
661 // Create a symbol at the start and end of this section used in here for the
662 // expression to calculate the length in the header.
663 MCSymbol *InfoStart = context.CreateTempSymbol();
664 MCOS->EmitLabel(InfoStart);
665 MCSymbol *InfoEnd = context.CreateTempSymbol();
667 // First part: the header.
669 // The 4 byte total length of the information for this compilation unit, not
670 // including these 4 bytes.
671 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
672 emitAbsValue(*MCOS, Length, 4);
674 // The 2 byte DWARF version.
675 MCOS->EmitIntValue(context.getDwarfVersion(), 2);
677 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
678 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
679 // it is at the start of that section so this is zero.
680 if (AbbrevSectionSymbol == nullptr)
681 MCOS->EmitIntValue(0, 4);
683 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
684 AsmInfo.needsDwarfSectionOffsetDirective());
686 const MCAsmInfo *asmInfo = context.getAsmInfo();
687 int AddrSize = asmInfo->getPointerSize();
688 // The 1 byte size of an address.
689 MCOS->EmitIntValue(AddrSize, 1);
691 // Second part: the compile_unit DIE.
693 // The DW_TAG_compile_unit DIE abbrev (1).
694 MCOS->EmitULEB128IntValue(1);
696 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
697 // which is at the start of that section so this is zero.
698 if (LineSectionSymbol)
699 MCOS->EmitSymbolValue(LineSectionSymbol, 4,
700 AsmInfo.needsDwarfSectionOffsetDirective());
702 MCOS->EmitIntValue(0, 4);
704 if (RangesSectionSymbol) {
705 // There are multiple sections containing code, so we must use the
706 // .debug_ranges sections.
708 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
709 // to the address range list for this compilation unit.
710 MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
712 // If we only have one non-empty code section, we can use the simpler
713 // AT_low_pc and AT_high_pc attributes.
715 // Find the first (and only) non-empty text section
716 auto &Sections = context.getGenDwarfSectionSyms();
717 const auto TextSection = Sections.begin();
718 assert(TextSection != Sections.end() && "No text section found");
720 MCSymbol *StartSymbol = TextSection->second.first;
721 MCSymbol *EndSymbol = TextSection->second.second;
722 assert(StartSymbol && "StartSymbol must not be NULL");
723 assert(EndSymbol && "EndSymbol must not be NULL");
725 // AT_low_pc, the first address of the default .text section.
726 const MCExpr *Start = MCSymbolRefExpr::Create(
727 StartSymbol, MCSymbolRefExpr::VK_None, context);
728 MCOS->EmitValue(Start, AddrSize);
730 // AT_high_pc, the last address of the default .text section.
731 const MCExpr *End = MCSymbolRefExpr::Create(
732 EndSymbol, MCSymbolRefExpr::VK_None, context);
733 MCOS->EmitValue(End, AddrSize);
736 // AT_name, the name of the source file. Reconstruct from the first directory
737 // and file table entries.
738 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
739 if (MCDwarfDirs.size() > 0) {
740 MCOS->EmitBytes(MCDwarfDirs[0]);
741 MCOS->EmitBytes(sys::path::get_separator());
743 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
744 MCOS->getContext().getMCDwarfFiles();
745 MCOS->EmitBytes(MCDwarfFiles[1].Name);
746 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
748 // AT_comp_dir, the working directory the assembly was done in.
749 if (!context.getCompilationDir().empty()) {
750 MCOS->EmitBytes(context.getCompilationDir());
751 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
754 // AT_APPLE_flags, the command line arguments of the assembler tool.
755 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
756 if (!DwarfDebugFlags.empty()){
757 MCOS->EmitBytes(DwarfDebugFlags);
758 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
761 // AT_producer, the version of the assembler tool.
762 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
763 if (!DwarfDebugProducer.empty())
764 MCOS->EmitBytes(DwarfDebugProducer);
766 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
767 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
769 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
770 // draft has no standard code for assembler.
771 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
773 // Third part: the list of label DIEs.
775 // Loop on saved info for dwarf labels and create the DIEs for them.
776 const std::vector<MCGenDwarfLabelEntry> &Entries =
777 MCOS->getContext().getMCGenDwarfLabelEntries();
778 for (const auto &Entry : Entries) {
779 // The DW_TAG_label DIE abbrev (2).
780 MCOS->EmitULEB128IntValue(2);
782 // AT_name, of the label without any leading underbar.
783 MCOS->EmitBytes(Entry.getName());
784 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
786 // AT_decl_file, index into the file table.
787 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
789 // AT_decl_line, source line number.
790 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
792 // AT_low_pc, start address of the label.
793 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry.getLabel(),
794 MCSymbolRefExpr::VK_None, context);
795 MCOS->EmitValue(AT_low_pc, AddrSize);
797 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
798 MCOS->EmitIntValue(0, 1);
800 // The DW_TAG_unspecified_parameters DIE abbrev (3).
801 MCOS->EmitULEB128IntValue(3);
803 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
804 MCOS->EmitIntValue(0, 1);
807 // Add the NULL DIE terminating the Compile Unit DIE's.
808 MCOS->EmitIntValue(0, 1);
810 // Now set the value of the symbol at the end of the info section.
811 MCOS->EmitLabel(InfoEnd);
814 // When generating dwarf for assembly source files this emits the data for
815 // .debug_ranges section. We only emit one range list, which spans all of the
816 // executable sections of this file.
817 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
818 MCContext &context = MCOS->getContext();
819 auto &Sections = context.getGenDwarfSectionSyms();
821 const MCAsmInfo *AsmInfo = context.getAsmInfo();
822 int AddrSize = AsmInfo->getPointerSize();
824 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
826 for (const auto sec : Sections) {
828 MCSymbol *StartSymbol = sec.second.first;
829 MCSymbol *EndSymbol = sec.second.second;
830 assert(StartSymbol && "StartSymbol must not be NULL");
831 assert(EndSymbol && "EndSymbol must not be NULL");
833 // Emit a base address selection entry for the start of this section
834 const MCExpr *SectionStartAddr = MCSymbolRefExpr::Create(
835 StartSymbol, MCSymbolRefExpr::VK_None, context);
836 MCOS->EmitFill(AddrSize, 0xFF);
837 MCOS->EmitValue(SectionStartAddr, AddrSize);
839 // Emit a range list entry spanning this section
840 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
841 *StartSymbol, *EndSymbol, 0);
842 MCOS->EmitIntValue(0, AddrSize);
843 emitAbsValue(*MCOS, SectionSize, AddrSize);
846 // Emit end of list entry
847 MCOS->EmitIntValue(0, AddrSize);
848 MCOS->EmitIntValue(0, AddrSize);
852 // When generating dwarf for assembly source files this emits the Dwarf
855 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
856 MCContext &context = MCOS->getContext();
858 // Create the dwarf sections in this order (.debug_line already created).
859 const MCAsmInfo *AsmInfo = context.getAsmInfo();
860 bool CreateDwarfSectionSymbols =
861 AsmInfo->doesDwarfUseRelocationsAcrossSections();
862 MCSymbol *LineSectionSymbol = nullptr;
863 if (CreateDwarfSectionSymbols)
864 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
865 MCSymbol *AbbrevSectionSymbol = nullptr;
866 MCSymbol *InfoSectionSymbol = nullptr;
867 MCSymbol *RangesSectionSymbol = NULL;
869 // Create end symbols for each section, and remove empty sections
870 MCOS->getContext().finalizeDwarfSections(*MCOS);
872 // If there are no sections to generate debug info for, we don't need
874 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
877 // We only use the .debug_ranges section if we have multiple code sections,
878 // and we are emitting a DWARF version which supports it.
879 const bool UseRangesSection =
880 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
881 MCOS->getContext().getDwarfVersion() >= 3;
882 CreateDwarfSectionSymbols |= UseRangesSection;
884 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
885 if (CreateDwarfSectionSymbols) {
886 InfoSectionSymbol = context.CreateTempSymbol();
887 MCOS->EmitLabel(InfoSectionSymbol);
889 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
890 if (CreateDwarfSectionSymbols) {
891 AbbrevSectionSymbol = context.CreateTempSymbol();
892 MCOS->EmitLabel(AbbrevSectionSymbol);
894 if (UseRangesSection) {
895 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
896 if (CreateDwarfSectionSymbols) {
897 RangesSectionSymbol = context.CreateTempSymbol();
898 MCOS->EmitLabel(RangesSectionSymbol);
902 assert((RangesSectionSymbol != NULL) || !UseRangesSection);
904 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
906 // Output the data for .debug_aranges section.
907 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
909 if (UseRangesSection)
910 EmitGenDwarfRanges(MCOS);
912 // Output the data for .debug_abbrev section.
913 EmitGenDwarfAbbrev(MCOS);
915 // Output the data for .debug_info section.
916 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
917 RangesSectionSymbol);
921 // When generating dwarf for assembly source files this is called when symbol
922 // for a label is created. If this symbol is not a temporary and is in the
923 // section that dwarf is being generated for, save the needed info to create
926 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
927 SourceMgr &SrcMgr, SMLoc &Loc) {
928 // We won't create dwarf labels for temporary symbols.
929 if (Symbol->isTemporary())
931 MCContext &context = MCOS->getContext();
932 // We won't create dwarf labels for symbols in sections that we are not
933 // generating debug info for.
934 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
937 // The dwarf label's name does not have the symbol name's leading
939 StringRef Name = Symbol->getName();
940 if (Name.startswith("_"))
941 Name = Name.substr(1, Name.size()-1);
943 // Get the dwarf file number to be used for the dwarf label.
944 unsigned FileNumber = context.getGenDwarfFileNumber();
946 // Finding the line number is the expensive part which is why we just don't
947 // pass it in as for some symbols we won't create a dwarf label.
948 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
949 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
951 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
952 // values so that they don't have things like an ARM thumb bit from the
953 // original symbol. So when used they won't get a low bit set after
955 MCSymbol *Label = context.CreateTempSymbol();
956 MCOS->EmitLabel(Label);
958 // Create and entry for the info and add it to the other entries.
959 MCOS->getContext().addMCGenDwarfLabelEntry(
960 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
963 static int getDataAlignmentFactor(MCStreamer &streamer) {
964 MCContext &context = streamer.getContext();
965 const MCAsmInfo *asmInfo = context.getAsmInfo();
966 int size = asmInfo->getCalleeSaveStackSlotSize();
967 if (asmInfo->isStackGrowthDirectionUp())
973 static unsigned getSizeForEncoding(MCStreamer &streamer,
974 unsigned symbolEncoding) {
975 MCContext &context = streamer.getContext();
976 unsigned format = symbolEncoding & 0x0f;
978 default: llvm_unreachable("Unknown Encoding");
979 case dwarf::DW_EH_PE_absptr:
980 case dwarf::DW_EH_PE_signed:
981 return context.getAsmInfo()->getPointerSize();
982 case dwarf::DW_EH_PE_udata2:
983 case dwarf::DW_EH_PE_sdata2:
985 case dwarf::DW_EH_PE_udata4:
986 case dwarf::DW_EH_PE_sdata4:
988 case dwarf::DW_EH_PE_udata8:
989 case dwarf::DW_EH_PE_sdata8:
994 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
995 unsigned symbolEncoding, bool isEH) {
996 MCContext &context = streamer.getContext();
997 const MCAsmInfo *asmInfo = context.getAsmInfo();
998 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
1001 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1002 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1003 emitAbsValue(streamer, v, size);
1005 streamer.EmitValue(v, size);
1008 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1009 unsigned symbolEncoding) {
1010 MCContext &context = streamer.getContext();
1011 const MCAsmInfo *asmInfo = context.getAsmInfo();
1012 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1015 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1016 streamer.EmitValue(v, size);
1020 class FrameEmitterImpl {
1023 const MCSymbol *SectionStart;
1025 FrameEmitterImpl(bool isEH)
1026 : CFAOffset(0), IsEH(isEH), SectionStart(nullptr) {}
1028 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
1030 /// Emit the unwind information in a compact way.
1031 void EmitCompactUnwind(MCObjectStreamer &streamer,
1032 const MCDwarfFrameInfo &frame);
1034 const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
1035 const MCSymbol *personality,
1036 unsigned personalityEncoding,
1037 const MCSymbol *lsda,
1039 unsigned lsdaEncoding,
1041 MCSymbol *EmitFDE(MCObjectStreamer &streamer,
1042 const MCSymbol &cieStart,
1043 const MCDwarfFrameInfo &frame);
1044 void EmitCFIInstructions(MCObjectStreamer &streamer,
1045 ArrayRef<MCCFIInstruction> Instrs,
1046 MCSymbol *BaseLabel);
1047 void EmitCFIInstruction(MCObjectStreamer &Streamer,
1048 const MCCFIInstruction &Instr);
1051 } // end anonymous namespace
1053 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1054 Streamer.EmitIntValue(Encoding, 1);
1057 void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
1058 const MCCFIInstruction &Instr) {
1059 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1061 switch (Instr.getOperation()) {
1062 case MCCFIInstruction::OpRegister: {
1063 unsigned Reg1 = Instr.getRegister();
1064 unsigned Reg2 = Instr.getRegister2();
1065 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1066 Streamer.EmitULEB128IntValue(Reg1);
1067 Streamer.EmitULEB128IntValue(Reg2);
1070 case MCCFIInstruction::OpWindowSave: {
1071 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1074 case MCCFIInstruction::OpUndefined: {
1075 unsigned Reg = Instr.getRegister();
1076 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1077 Streamer.EmitULEB128IntValue(Reg);
1080 case MCCFIInstruction::OpAdjustCfaOffset:
1081 case MCCFIInstruction::OpDefCfaOffset: {
1082 const bool IsRelative =
1083 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1085 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1088 CFAOffset += Instr.getOffset();
1090 CFAOffset = -Instr.getOffset();
1092 Streamer.EmitULEB128IntValue(CFAOffset);
1096 case MCCFIInstruction::OpDefCfa: {
1097 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1098 Streamer.EmitULEB128IntValue(Instr.getRegister());
1099 CFAOffset = -Instr.getOffset();
1100 Streamer.EmitULEB128IntValue(CFAOffset);
1105 case MCCFIInstruction::OpDefCfaRegister: {
1106 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1107 Streamer.EmitULEB128IntValue(Instr.getRegister());
1112 case MCCFIInstruction::OpOffset:
1113 case MCCFIInstruction::OpRelOffset: {
1114 const bool IsRelative =
1115 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1117 unsigned Reg = Instr.getRegister();
1118 int Offset = Instr.getOffset();
1120 Offset -= CFAOffset;
1121 Offset = Offset / dataAlignmentFactor;
1124 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1125 Streamer.EmitULEB128IntValue(Reg);
1126 Streamer.EmitSLEB128IntValue(Offset);
1127 } else if (Reg < 64) {
1128 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1129 Streamer.EmitULEB128IntValue(Offset);
1131 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1132 Streamer.EmitULEB128IntValue(Reg);
1133 Streamer.EmitULEB128IntValue(Offset);
1137 case MCCFIInstruction::OpRememberState:
1138 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1140 case MCCFIInstruction::OpRestoreState:
1141 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1143 case MCCFIInstruction::OpSameValue: {
1144 unsigned Reg = Instr.getRegister();
1145 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1146 Streamer.EmitULEB128IntValue(Reg);
1149 case MCCFIInstruction::OpRestore: {
1150 unsigned Reg = Instr.getRegister();
1151 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1154 case MCCFIInstruction::OpEscape:
1155 Streamer.EmitBytes(Instr.getValues());
1158 llvm_unreachable("Unhandled case in switch");
1161 /// Emit frame instructions to describe the layout of the frame.
1162 void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
1163 ArrayRef<MCCFIInstruction> Instrs,
1164 MCSymbol *BaseLabel) {
1165 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1166 const MCCFIInstruction &Instr = Instrs[i];
1167 MCSymbol *Label = Instr.getLabel();
1168 // Throw out move if the label is invalid.
1169 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1171 // Advance row if new location.
1172 if (BaseLabel && Label) {
1173 MCSymbol *ThisSym = Label;
1174 if (ThisSym != BaseLabel) {
1175 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1176 BaseLabel = ThisSym;
1180 EmitCFIInstruction(streamer, Instr);
1184 /// Emit the unwind information in a compact way.
1185 void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
1186 const MCDwarfFrameInfo &Frame) {
1187 MCContext &Context = Streamer.getContext();
1188 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1190 // range-start range-length compact-unwind-enc personality-func lsda
1191 // _foo LfooEnd-_foo 0x00000023 0 0
1192 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1194 // .section __LD,__compact_unwind,regular,debug
1196 // # compact unwind for _foo
1198 // .set L1,LfooEnd-_foo
1204 // # compact unwind for _bar
1206 // .set L2,LbarEnd-_bar
1209 // .quad __gxx_personality
1210 // .quad except_tab1
1212 uint32_t Encoding = Frame.CompactUnwindEncoding;
1213 if (!Encoding) return;
1214 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1216 // The encoding needs to know we have an LSDA.
1217 if (!DwarfEHFrameOnly && Frame.Lsda)
1218 Encoding |= 0x40000000;
1221 unsigned FDEEncoding = MOFI->getFDEEncoding();
1222 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1223 Streamer.EmitSymbolValue(Frame.Begin, Size);
1226 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1228 emitAbsValue(Streamer, Range, 4);
1231 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1232 Streamer.EmitIntValue(Encoding, Size);
1234 // Personality Function
1235 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1236 if (!DwarfEHFrameOnly && Frame.Personality)
1237 Streamer.EmitSymbolValue(Frame.Personality, Size);
1239 Streamer.EmitIntValue(0, Size); // No personality fn
1242 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1243 if (!DwarfEHFrameOnly && Frame.Lsda)
1244 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1246 Streamer.EmitIntValue(0, Size); // No LSDA
1249 const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
1250 const MCSymbol *personality,
1251 unsigned personalityEncoding,
1252 const MCSymbol *lsda,
1254 unsigned lsdaEncoding,
1256 MCContext &context = streamer.getContext();
1257 const MCRegisterInfo *MRI = context.getRegisterInfo();
1258 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1260 MCSymbol *sectionStart = context.CreateTempSymbol();
1261 streamer.EmitLabel(sectionStart);
1263 MCSymbol *sectionEnd = context.CreateTempSymbol();
1266 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1268 emitAbsValue(streamer, Length, 4);
1271 unsigned CIE_ID = IsEH ? 0 : -1;
1272 streamer.EmitIntValue(CIE_ID, 4);
1275 // For DWARF2, we use CIE version 1
1276 // For DWARF3+, we use CIE version 3
1277 uint8_t CIEVersion = context.getDwarfVersion() <= 2 ? 1 : 3;
1278 streamer.EmitIntValue(CIEVersion, 1);
1280 // Augmentation String
1281 SmallString<8> Augmentation;
1283 Augmentation += "z";
1285 Augmentation += "P";
1287 Augmentation += "L";
1288 Augmentation += "R";
1290 Augmentation += "S";
1291 streamer.EmitBytes(Augmentation.str());
1293 streamer.EmitIntValue(0, 1);
1295 // Code Alignment Factor
1296 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1298 // Data Alignment Factor
1299 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1301 // Return Address Register
1302 if (CIEVersion == 1) {
1303 assert(MRI->getRARegister() <= 255 &&
1304 "DWARF 2 encodes return_address_register in one byte");
1305 streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true), 1);
1307 streamer.EmitULEB128IntValue(
1308 MRI->getDwarfRegNum(MRI->getRARegister(), true));
1311 // Augmentation Data Length (optional)
1313 unsigned augmentationLength = 0;
1316 // Personality Encoding
1317 augmentationLength += 1;
1319 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1322 augmentationLength += 1;
1323 // Encoding of the FDE pointers
1324 augmentationLength += 1;
1326 streamer.EmitULEB128IntValue(augmentationLength);
1328 // Augmentation Data (optional)
1330 // Personality Encoding
1331 emitEncodingByte(streamer, personalityEncoding);
1333 EmitPersonality(streamer, *personality, personalityEncoding);
1337 emitEncodingByte(streamer, lsdaEncoding);
1339 // Encoding of the FDE pointers
1340 emitEncodingByte(streamer, MOFI->getFDEEncoding());
1343 // Initial Instructions
1345 const MCAsmInfo *MAI = context.getAsmInfo();
1347 const std::vector<MCCFIInstruction> &Instructions =
1348 MAI->getInitialFrameState();
1349 EmitCFIInstructions(streamer, Instructions, nullptr);
1353 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1355 streamer.EmitLabel(sectionEnd);
1356 return *sectionStart;
1359 MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
1360 const MCSymbol &cieStart,
1361 const MCDwarfFrameInfo &frame) {
1362 MCContext &context = streamer.getContext();
1363 MCSymbol *fdeStart = context.CreateTempSymbol();
1364 MCSymbol *fdeEnd = context.CreateTempSymbol();
1365 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1368 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1369 emitAbsValue(streamer, Length, 4);
1371 streamer.EmitLabel(fdeStart);
1374 const MCAsmInfo *asmInfo = context.getAsmInfo();
1376 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1378 emitAbsValue(streamer, offset, 4);
1379 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1380 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1382 emitAbsValue(streamer, offset, 4);
1384 streamer.EmitSymbolValue(&cieStart, 4);
1388 unsigned PCEncoding =
1389 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1390 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1391 emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
1394 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1396 emitAbsValue(streamer, Range, PCSize);
1399 // Augmentation Data Length
1400 unsigned augmentationLength = 0;
1403 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1405 streamer.EmitULEB128IntValue(augmentationLength);
1407 // Augmentation Data
1409 emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
1412 // Call Frame Instructions
1413 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1416 streamer.EmitValueToAlignment(PCSize);
1423 static const CIEKey getEmptyKey() {
1424 return CIEKey(nullptr, 0, -1, false, false);
1426 static const CIEKey getTombstoneKey() {
1427 return CIEKey(nullptr, -1, 0, false, false);
1430 CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
1431 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
1432 : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1433 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1434 IsSimple(IsSimple_) {}
1435 const MCSymbol *Personality;
1436 unsigned PersonalityEncoding;
1437 unsigned LsdaEncoding;
1445 struct DenseMapInfo<CIEKey> {
1446 static CIEKey getEmptyKey() {
1447 return CIEKey::getEmptyKey();
1449 static CIEKey getTombstoneKey() {
1450 return CIEKey::getTombstoneKey();
1452 static unsigned getHashValue(const CIEKey &Key) {
1453 return static_cast<unsigned>(hash_combine(Key.Personality,
1454 Key.PersonalityEncoding,
1459 static bool isEqual(const CIEKey &LHS,
1460 const CIEKey &RHS) {
1461 return LHS.Personality == RHS.Personality &&
1462 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1463 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1464 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1465 LHS.IsSimple == RHS.IsSimple;
1470 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1472 Streamer.generateCompactUnwindEncodings(MAB);
1474 MCContext &Context = Streamer.getContext();
1475 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1476 FrameEmitterImpl Emitter(IsEH);
1477 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1479 // Emit the compact unwind info if available.
1480 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1481 if (IsEH && MOFI->getCompactUnwindSection()) {
1482 bool SectionEmitted = false;
1483 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1484 const MCDwarfFrameInfo &Frame = FrameArray[i];
1485 if (Frame.CompactUnwindEncoding == 0) continue;
1486 if (!SectionEmitted) {
1487 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1488 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1489 SectionEmitted = true;
1491 NeedsEHFrameSection |=
1492 Frame.CompactUnwindEncoding ==
1493 MOFI->getCompactUnwindDwarfEHFrameOnly();
1494 Emitter.EmitCompactUnwind(Streamer, Frame);
1498 if (!NeedsEHFrameSection) return;
1500 const MCSection &Section =
1501 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1502 *MOFI->getDwarfFrameSection();
1504 Streamer.SwitchSection(&Section);
1505 MCSymbol *SectionStart = Context.CreateTempSymbol();
1506 Streamer.EmitLabel(SectionStart);
1507 Emitter.setSectionStart(SectionStart);
1509 MCSymbol *FDEEnd = nullptr;
1510 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1512 const MCSymbol *DummyDebugKey = nullptr;
1513 NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1514 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1515 const MCDwarfFrameInfo &Frame = FrameArray[i];
1517 // Emit the label from the previous iteration
1519 Streamer.EmitLabel(FDEEnd);
1523 if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1524 MOFI->getCompactUnwindDwarfEHFrameOnly())
1525 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1526 // of by the compact unwind encoding.
1529 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1530 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1531 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1533 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1534 Frame.PersonalityEncoding, Frame.Lsda,
1535 Frame.IsSignalFrame,
1539 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1542 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1544 Streamer.EmitLabel(FDEEnd);
1547 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1548 uint64_t AddrDelta) {
1549 MCContext &Context = Streamer.getContext();
1550 SmallString<256> Tmp;
1551 raw_svector_ostream OS(Tmp);
1552 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1553 Streamer.EmitBytes(OS.str());
1556 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1559 // Scale the address delta by the minimum instruction length.
1560 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1562 if (AddrDelta == 0) {
1563 } else if (isUIntN(6, AddrDelta)) {
1564 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1566 } else if (isUInt<8>(AddrDelta)) {
1567 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1568 OS << uint8_t(AddrDelta);
1569 } else if (isUInt<16>(AddrDelta)) {
1570 // FIXME: check what is the correct behavior on a big endian machine.
1571 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1572 OS << uint8_t( AddrDelta & 0xff);
1573 OS << uint8_t((AddrDelta >> 8) & 0xff);
1575 // FIXME: check what is the correct behavior on a big endian machine.
1576 assert(isUInt<32>(AddrDelta));
1577 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1578 OS << uint8_t( AddrDelta & 0xff);
1579 OS << uint8_t((AddrDelta >> 8) & 0xff);
1580 OS << uint8_t((AddrDelta >> 16) & 0xff);
1581 OS << uint8_t((AddrDelta >> 24) & 0xff);