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/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCObjectFileInfo.h"
14 #include "llvm/MC/MCObjectWriter.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/config.h"
30 // Given a special op, return the address skip amount (in units of
31 // DWARF2_LINE_MIN_INSN_LENGTH.
32 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
34 // The maximum address skip amount that can be encoded with a special op.
35 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
37 // First special line opcode - leave room for the standard opcodes.
38 // Note: If you want to change this, you'll have to update the
39 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
40 #define DWARF2_LINE_OPCODE_BASE 13
42 // Minimum line offset in a special line info. opcode. This value
43 // was chosen to give a reasonable range of values.
44 #define DWARF2_LINE_BASE -5
46 // Range of line offsets in a special line info. opcode.
47 #define DWARF2_LINE_RANGE 14
49 // Define the architecture-dependent minimum instruction length (in bytes).
50 // This value should be rather too small than too big.
51 #define DWARF2_LINE_MIN_INSN_LENGTH 1
53 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
54 // this routine is a nop and will be optimized away.
55 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
56 if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
58 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
59 // TODO: report this error, but really only once.
62 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
66 // This is called when an instruction is assembled into the specified section
67 // and if there is information from the last .loc directive that has yet to have
68 // a line entry made for it is made.
70 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
71 if (!MCOS->getContext().getDwarfLocSeen())
74 // Create a symbol at in the current section for use in the line entry.
75 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
76 // Set the value of the symbol to use for the MCLineEntry.
77 MCOS->EmitLabel(LineSym);
79 // Get the current .loc info saved in the context.
80 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
82 // Create a (local) line entry with the symbol and the current .loc info.
83 MCLineEntry LineEntry(LineSym, DwarfLoc);
85 // clear DwarfLocSeen saying the current .loc info is now used.
86 MCOS->getContext().ClearDwarfLocSeen();
88 // Get the MCLineSection for this section, if one does not exist for this
90 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
91 MCOS->getContext().getMCLineSections();
92 MCLineSection *LineSection = MCLineSections.lookup(Section);
94 // Create a new MCLineSection. This will be deleted after the dwarf line
95 // table is created using it by iterating through the MCLineSections
97 LineSection = new MCLineSection;
98 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
99 MCOS->getContext().addMCLineSection(Section, LineSection);
102 // Add the line entry to this section's entries.
103 LineSection->addLineEntry(LineEntry);
107 // This helper routine returns an expression of End - Start + IntVal .
109 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
110 const MCSymbol &Start,
113 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
115 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
117 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
119 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
121 MCConstantExpr::Create(IntVal, MCOS.getContext());
123 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
128 // This emits the Dwarf line table for the specified section from the entries
129 // in the LineSection.
131 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
132 const MCSection *Section,
133 const MCLineSection *LineSection) {
134 unsigned FileNum = 1;
135 unsigned LastLine = 1;
137 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
139 MCSymbol *LastLabel = NULL;
141 // Loop through each MCLineEntry and encode the dwarf line number table.
142 for (MCLineSection::const_iterator
143 it = LineSection->getMCLineEntries()->begin(),
144 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
146 if (FileNum != it->getFileNum()) {
147 FileNum = it->getFileNum();
148 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
149 MCOS->EmitULEB128IntValue(FileNum);
151 if (Column != it->getColumn()) {
152 Column = it->getColumn();
153 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
154 MCOS->EmitULEB128IntValue(Column);
156 if (Isa != it->getIsa()) {
158 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
159 MCOS->EmitULEB128IntValue(Isa);
161 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
162 Flags = it->getFlags();
163 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
165 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
166 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
167 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
168 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
169 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
170 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
172 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
173 MCSymbol *Label = it->getLabel();
175 // At this point we want to emit/create the sequence to encode the delta in
176 // line numbers and the increment of the address from the previous Label
177 // and the current Label.
178 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
179 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
180 asmInfo.getPointerSize());
182 LastLine = it->getLine();
186 // Emit a DW_LNE_end_sequence for the end of the section.
187 // Using the pointer Section create a temporary label at the end of the
188 // section and use that and the LastLabel to compute the address delta
189 // and use INT64_MAX as the line delta which is the signal that this is
190 // actually a DW_LNE_end_sequence.
192 // Switch to the section to be able to create a symbol at its end.
193 MCOS->SwitchSection(Section);
195 MCContext &context = MCOS->getContext();
196 // Create a symbol at the end of the section.
197 MCSymbol *SectionEnd = context.CreateTempSymbol();
198 // Set the value of the symbol, as we are at the end of the section.
199 MCOS->EmitLabel(SectionEnd);
201 // Switch back the the dwarf line section.
202 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
204 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
205 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
206 asmInfo.getPointerSize());
210 // This emits the Dwarf file and the line tables.
212 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
213 MCContext &context = MCOS->getContext();
214 // Switch to the section where the table will be emitted into.
215 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
217 // Create a symbol at the beginning of this section.
218 MCSymbol *LineStartSym = context.CreateTempSymbol();
219 // Set the value of the symbol, as we are at the start of the section.
220 MCOS->EmitLabel(LineStartSym);
222 // Create a symbol for the end of the section (to be set when we get there).
223 MCSymbol *LineEndSym = context.CreateTempSymbol();
225 // The first 4 bytes is the total length of the information for this
226 // compilation unit (not including these 4 bytes for the length).
227 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
230 // Next 2 bytes is the Version, which is Dwarf 2.
231 MCOS->EmitIntValue(2, 2);
233 // Create a symbol for the end of the prologue (to be set when we get there).
234 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
236 // Length of the prologue, is the next 4 bytes. Which is the start of the
237 // section to the end of the prologue. Not including the 4 bytes for the
238 // total length, the 2 bytes for the version, and these 4 bytes for the
239 // length of the prologue.
240 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
244 // Parameters of the state machine, are next.
245 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
246 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
247 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
248 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
249 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
251 // Standard opcode lengths
252 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
253 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
254 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
255 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
256 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
257 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
258 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
259 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
260 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
261 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
262 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
263 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
265 // Put out the directory and file tables.
267 // First the directory table.
268 const std::vector<StringRef> &MCDwarfDirs =
269 context.getMCDwarfDirs();
270 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
271 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
272 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
274 MCOS->EmitIntValue(0, 1); // Terminate the directory list
276 // Second the file table.
277 const std::vector<MCDwarfFile *> &MCDwarfFiles =
278 MCOS->getContext().getMCDwarfFiles();
279 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
280 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
281 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
283 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
284 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
285 MCOS->EmitIntValue(0, 1); // filesize (always 0)
287 MCOS->EmitIntValue(0, 1); // Terminate the file list
289 // This is the end of the prologue, so set the value of the symbol at the
290 // end of the prologue (that was used in a previous expression).
291 MCOS->EmitLabel(ProEndSym);
293 // Put out the line tables.
294 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
295 MCOS->getContext().getMCLineSections();
296 const std::vector<const MCSection *> &MCLineSectionOrder =
297 MCOS->getContext().getMCLineSectionOrder();
298 for (std::vector<const MCSection*>::const_iterator it =
299 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
301 const MCSection *Sec = *it;
302 const MCLineSection *Line = MCLineSections.lookup(Sec);
303 EmitDwarfLineTable(MCOS, Sec, Line);
305 // Now delete the MCLineSections that were created in MCLineEntry::Make()
306 // and used to emit the line table.
310 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
311 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
312 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
314 // total_length >= prologue_length + 10
315 // We are 4 bytes short, since we have total_length = 51 and
316 // prologue_length = 45
318 // The regular end_sequence should be sufficient.
319 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
322 // This is the end of the section, so set the value of the symbol at the end
323 // of this section (that was used in a previous expression).
324 MCOS->EmitLabel(LineEndSym);
329 /// Utility function to write the encoding to an object writer.
330 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
331 uint64_t AddrDelta) {
332 SmallString<256> Tmp;
333 raw_svector_ostream OS(Tmp);
334 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
335 OW->WriteBytes(OS.str());
338 /// Utility function to emit the encoding to a streamer.
339 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
340 uint64_t AddrDelta) {
341 SmallString<256> Tmp;
342 raw_svector_ostream OS(Tmp);
343 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
344 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
347 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
348 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
350 uint64_t Temp, Opcode;
351 bool NeedCopy = false;
353 // Scale the address delta by the minimum instruction length.
354 AddrDelta = ScaleAddrDelta(AddrDelta);
356 // A LineDelta of INT64_MAX is a signal that this is actually a
357 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
358 // end_sequence to emit the matrix entry.
359 if (LineDelta == INT64_MAX) {
360 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
361 OS << char(dwarf::DW_LNS_const_add_pc);
363 OS << char(dwarf::DW_LNS_advance_pc);
364 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
366 OS << char(dwarf::DW_LNS_extended_op);
368 OS << char(dwarf::DW_LNE_end_sequence);
372 // Bias the line delta by the base.
373 Temp = LineDelta - DWARF2_LINE_BASE;
375 // If the line increment is out of range of a special opcode, we must encode
376 // it with DW_LNS_advance_line.
377 if (Temp >= DWARF2_LINE_RANGE) {
378 OS << char(dwarf::DW_LNS_advance_line);
379 MCObjectWriter::EncodeSLEB128(LineDelta, OS);
382 Temp = 0 - DWARF2_LINE_BASE;
386 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
387 if (LineDelta == 0 && AddrDelta == 0) {
388 OS << char(dwarf::DW_LNS_copy);
392 // Bias the opcode by the special opcode base.
393 Temp += DWARF2_LINE_OPCODE_BASE;
395 // Avoid overflow when addr_delta is large.
396 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
397 // Try using a special opcode.
398 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
404 // Try using DW_LNS_const_add_pc followed by special op.
405 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
407 OS << char(dwarf::DW_LNS_const_add_pc);
413 // Otherwise use DW_LNS_advance_pc.
414 OS << char(dwarf::DW_LNS_advance_pc);
415 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
418 OS << char(dwarf::DW_LNS_copy);
423 void MCDwarfFile::print(raw_ostream &OS) const {
424 OS << '"' << getName() << '"';
427 void MCDwarfFile::dump() const {
431 // Utility function to write a tuple for .debug_abbrev.
432 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
433 MCOS->EmitULEB128IntValue(Name);
434 MCOS->EmitULEB128IntValue(Form);
437 // When generating dwarf for assembly source files this emits
438 // the data for .debug_abbrev section which contains three DIEs.
439 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
440 MCContext &context = MCOS->getContext();
441 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
443 // DW_TAG_compile_unit DIE abbrev (1).
444 MCOS->EmitULEB128IntValue(1);
445 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
446 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
447 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
448 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
449 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
450 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
451 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
452 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
453 if (!DwarfDebugFlags.empty())
454 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
455 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
456 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
457 EmitAbbrev(MCOS, 0, 0);
459 // DW_TAG_label DIE abbrev (2).
460 MCOS->EmitULEB128IntValue(2);
461 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
462 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
463 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
464 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
465 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
466 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
467 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
468 EmitAbbrev(MCOS, 0, 0);
470 // DW_TAG_unspecified_parameters DIE abbrev (3).
471 MCOS->EmitULEB128IntValue(3);
472 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
473 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
474 EmitAbbrev(MCOS, 0, 0);
476 // Terminate the abbreviations for this compilation unit.
477 MCOS->EmitIntValue(0, 1);
480 // When generating dwarf for assembly source files this emits the data for
481 // .debug_aranges section. Which contains a header and a table of pairs of
482 // PointerSize'ed values for the address and size of section(s) with line table
483 // entries (just the default .text in our case) and a terminating pair of zeros.
484 static void EmitGenDwarfAranges(MCStreamer *MCOS) {
485 MCContext &context = MCOS->getContext();
487 // Create a symbol at the end of the section that we are creating the dwarf
488 // debugging info to use later in here as part of the expression to calculate
489 // the size of the section for the table.
490 MCOS->SwitchSection(context.getGenDwarfSection());
491 MCSymbol *SectionEndSym = context.CreateTempSymbol();
492 MCOS->EmitLabel(SectionEndSym);
493 context.setGenDwarfSectionEndSym(SectionEndSym);
495 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
497 // This will be the length of the .debug_aranges section, first account for
498 // the size of each item in the header (see below where we emit these items).
499 int Length = 4 + 2 + 4 + 1 + 1;
501 // Figure the padding after the header before the table of address and size
502 // pairs who's values are PointerSize'ed.
503 const MCAsmInfo &asmInfo = context.getAsmInfo();
504 int AddrSize = asmInfo.getPointerSize();
505 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
506 if (Pad == 2 * AddrSize)
510 // Add the size of the pair of PointerSize'ed values for the address and size
511 // of the one default .text section we have in the table.
512 Length += 2 * AddrSize;
513 // And the pair of terminating zeros.
514 Length += 2 * AddrSize;
517 // Emit the header for this section.
518 // The 4 byte length not including the 4 byte value for the length.
519 MCOS->EmitIntValue(Length - 4, 4);
520 // The 2 byte version, which is 2.
521 MCOS->EmitIntValue(2, 2);
522 // The 4 byte offset to the compile unit in the .debug_info from the start
523 // of the .debug_info, it is at the start of that section so this is zero.
524 MCOS->EmitIntValue(0, 4);
525 // The 1 byte size of an address.
526 MCOS->EmitIntValue(AddrSize, 1);
527 // The 1 byte size of a segment descriptor, we use a value of zero.
528 MCOS->EmitIntValue(0, 1);
529 // Align the header with the padding if needed, before we put out the table.
530 for(int i = 0; i < Pad; i++)
531 MCOS->EmitIntValue(0, 1);
533 // Now emit the table of pairs of PointerSize'ed values for the section(s)
534 // address and size, in our case just the one default .text section.
535 const MCExpr *Addr = MCSymbolRefExpr::Create(
536 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
537 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
538 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
539 MCOS->EmitAbsValue(Addr, AddrSize);
540 MCOS->EmitAbsValue(Size, AddrSize);
542 // And finally the pair of terminating zeros.
543 MCOS->EmitIntValue(0, AddrSize);
544 MCOS->EmitIntValue(0, AddrSize);
547 // When generating dwarf for assembly source files this emits the data for
548 // .debug_info section which contains three parts. The header, the compile_unit
549 // DIE and a list of label DIEs.
550 static void EmitGenDwarfInfo(MCStreamer *MCOS,
551 const MCSymbol *AbbrevSectionSymbol,
552 const MCSymbol *LineSectionSymbol) {
553 MCContext &context = MCOS->getContext();
555 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
557 // Create a symbol at the start and end of this section used in here for the
558 // expression to calculate the length in the header.
559 MCSymbol *InfoStart = context.CreateTempSymbol();
560 MCOS->EmitLabel(InfoStart);
561 MCSymbol *InfoEnd = context.CreateTempSymbol();
563 // First part: the header.
565 // The 4 byte total length of the information for this compilation unit, not
566 // including these 4 bytes.
567 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
568 MCOS->EmitAbsValue(Length, 4);
570 // The 2 byte DWARF version, which is 2.
571 MCOS->EmitIntValue(2, 2);
573 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
574 // it is at the start of that section so this is zero.
575 if (AbbrevSectionSymbol) {
576 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
578 MCOS->EmitIntValue(0, 4);
581 const MCAsmInfo &asmInfo = context.getAsmInfo();
582 int AddrSize = asmInfo.getPointerSize();
583 // The 1 byte size of an address.
584 MCOS->EmitIntValue(AddrSize, 1);
586 // Second part: the compile_unit DIE.
588 // The DW_TAG_compile_unit DIE abbrev (1).
589 MCOS->EmitULEB128IntValue(1);
591 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
592 // which is at the start of that section so this is zero.
593 if (LineSectionSymbol) {
594 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
596 MCOS->EmitIntValue(0, 4);
599 // AT_low_pc, the first address of the default .text section.
600 const MCExpr *Start = MCSymbolRefExpr::Create(
601 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
602 MCOS->EmitAbsValue(Start, AddrSize);
604 // AT_high_pc, the last address of the default .text section.
605 const MCExpr *End = MCSymbolRefExpr::Create(
606 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
607 MCOS->EmitAbsValue(End, AddrSize);
609 // AT_name, the name of the source file. Reconstruct from the first directory
610 // and file table entries.
611 const std::vector<StringRef> &MCDwarfDirs =
612 context.getMCDwarfDirs();
613 if (MCDwarfDirs.size() > 0) {
614 MCOS->EmitBytes(MCDwarfDirs[0], 0);
615 MCOS->EmitBytes("/", 0);
617 const std::vector<MCDwarfFile *> &MCDwarfFiles =
618 MCOS->getContext().getMCDwarfFiles();
619 MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0);
620 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
622 // AT_comp_dir, the working directory the assembly was done in.
623 llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
624 MCOS->EmitBytes(StringRef(CWD.c_str()), 0);
625 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
627 // AT_APPLE_flags, the command line arguments of the assembler tool.
628 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
629 if (!DwarfDebugFlags.empty()){
630 MCOS->EmitBytes(DwarfDebugFlags, 0);
631 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
634 // AT_producer, the version of the assembler tool.
635 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0);
636 MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0);
637 MCOS->EmitBytes(StringRef(")"), 0);
638 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
640 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
641 // draft has no standard code for assembler.
642 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
644 // Third part: the list of label DIEs.
646 // Loop on saved info for dwarf labels and create the DIEs for them.
647 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
648 MCOS->getContext().getMCGenDwarfLabelEntries();
649 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
650 Entries.begin(), ie = Entries.end(); it != ie;
652 const MCGenDwarfLabelEntry *Entry = *it;
654 // The DW_TAG_label DIE abbrev (2).
655 MCOS->EmitULEB128IntValue(2);
657 // AT_name, of the label without any leading underbar.
658 MCOS->EmitBytes(Entry->getName(), 0);
659 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
661 // AT_decl_file, index into the file table.
662 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
664 // AT_decl_line, source line number.
665 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
667 // AT_low_pc, start address of the label.
668 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
669 MCSymbolRefExpr::VK_None, context);
670 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
672 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
673 MCOS->EmitIntValue(0, 1);
675 // The DW_TAG_unspecified_parameters DIE abbrev (3).
676 MCOS->EmitULEB128IntValue(3);
678 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
679 MCOS->EmitIntValue(0, 1);
681 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
682 // for the dwarf labels.
683 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
684 Entries.begin(), ie = Entries.end(); it != ie;
686 const MCGenDwarfLabelEntry *Entry = *it;
690 // Add the NULL DIE terminating the Compile Unit DIE's.
691 MCOS->EmitIntValue(0, 1);
693 // Now set the value of the symbol at the end of the info section.
694 MCOS->EmitLabel(InfoEnd);
698 // When generating dwarf for assembly source files this emits the Dwarf
701 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
702 // Create the dwarf sections in this order (.debug_line already created).
703 MCContext &context = MCOS->getContext();
704 const MCAsmInfo &AsmInfo = context.getAsmInfo();
705 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
706 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
707 MCSymbol *AbbrevSectionSymbol;
708 if (AsmInfo.doesDwarfRequireRelocationForSectionOffset()) {
709 AbbrevSectionSymbol = context.CreateTempSymbol();
710 MCOS->EmitLabel(AbbrevSectionSymbol);
712 AbbrevSectionSymbol = NULL;
713 LineSectionSymbol = NULL;
715 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
717 // If there are no line table entries then do not emit any section contents.
718 if (context.getMCLineSections().empty())
721 // Output the data for .debug_aranges section.
722 EmitGenDwarfAranges(MCOS);
724 // Output the data for .debug_abbrev section.
725 EmitGenDwarfAbbrev(MCOS);
727 // Output the data for .debug_info section.
728 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
732 // When generating dwarf for assembly source files this is called when symbol
733 // for a label is created. If this symbol is not a temporary and is in the
734 // section that dwarf is being generated for, save the needed info to create
737 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
738 SourceMgr &SrcMgr, SMLoc &Loc) {
739 // We won't create dwarf labels for temporary symbols or symbols not in
741 if (Symbol->isTemporary())
743 MCContext &context = MCOS->getContext();
744 if (context.getGenDwarfSection() != MCOS->getCurrentSection())
747 // The dwarf label's name does not have the symbol name's leading
749 StringRef Name = Symbol->getName();
750 if (Name.startswith("_"))
751 Name = Name.substr(1, Name.size()-1);
753 // Get the dwarf file number to be used for the dwarf label.
754 unsigned FileNumber = context.getGenDwarfFileNumber();
756 // Finding the line number is the expensive part which is why we just don't
757 // pass it in as for some symbols we won't create a dwarf label.
758 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
759 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
761 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
762 // values so that they don't have things like an ARM thumb bit from the
763 // original symbol. So when used they won't get a low bit set after
765 MCSymbol *Label = context.CreateTempSymbol();
766 MCOS->EmitLabel(Label);
768 // Create and entry for the info and add it to the other entries.
769 MCGenDwarfLabelEntry *Entry =
770 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
771 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
774 static int getDataAlignmentFactor(MCStreamer &streamer) {
775 MCContext &context = streamer.getContext();
776 const MCAsmInfo &asmInfo = context.getAsmInfo();
777 int size = asmInfo.getPointerSize();
778 if (asmInfo.isStackGrowthDirectionUp())
784 static unsigned getSizeForEncoding(MCStreamer &streamer,
785 unsigned symbolEncoding) {
786 MCContext &context = streamer.getContext();
787 unsigned format = symbolEncoding & 0x0f;
789 default: llvm_unreachable("Unknown Encoding");
790 case dwarf::DW_EH_PE_absptr:
791 case dwarf::DW_EH_PE_signed:
792 return context.getAsmInfo().getPointerSize();
793 case dwarf::DW_EH_PE_udata2:
794 case dwarf::DW_EH_PE_sdata2:
796 case dwarf::DW_EH_PE_udata4:
797 case dwarf::DW_EH_PE_sdata4:
799 case dwarf::DW_EH_PE_udata8:
800 case dwarf::DW_EH_PE_sdata8:
805 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
806 unsigned symbolEncoding, const char *comment = 0) {
807 MCContext &context = streamer.getContext();
808 const MCAsmInfo &asmInfo = context.getAsmInfo();
809 const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
812 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
813 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
814 streamer.EmitAbsValue(v, size);
817 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
818 unsigned symbolEncoding) {
819 MCContext &context = streamer.getContext();
820 const MCAsmInfo &asmInfo = context.getAsmInfo();
821 const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
824 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
825 streamer.EmitValue(v, size);
828 static const MachineLocation TranslateMachineLocation(
829 const MCRegisterInfo &MRI,
830 const MachineLocation &Loc) {
831 unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
832 MachineLocation::VirtualFP :
833 unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
834 const MachineLocation &NewLoc = Loc.isReg() ?
835 MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
840 class FrameEmitterImpl {
845 const MCSymbol *SectionStart;
847 FrameEmitterImpl(bool usingCFI, bool isEH)
848 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
851 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
853 /// EmitCompactUnwind - Emit the unwind information in a compact way. If
854 /// we're successful, return 'true'. Otherwise, return 'false' and it will
855 /// emit the normal CIE and FDE.
856 bool EmitCompactUnwind(MCStreamer &streamer,
857 const MCDwarfFrameInfo &frame);
859 const MCSymbol &EmitCIE(MCStreamer &streamer,
860 const MCSymbol *personality,
861 unsigned personalityEncoding,
862 const MCSymbol *lsda,
864 unsigned lsdaEncoding);
865 MCSymbol *EmitFDE(MCStreamer &streamer,
866 const MCSymbol &cieStart,
867 const MCDwarfFrameInfo &frame);
868 void EmitCFIInstructions(MCStreamer &streamer,
869 const std::vector<MCCFIInstruction> &Instrs,
870 MCSymbol *BaseLabel);
871 void EmitCFIInstruction(MCStreamer &Streamer,
872 const MCCFIInstruction &Instr);
875 } // end anonymous namespace
877 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
879 if (Streamer.isVerboseAsm()) {
882 default: EncStr = "<unknown encoding>"; break;
883 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
884 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
885 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
886 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
887 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
888 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
889 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
890 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
891 EncStr = "pcrel udata4";
893 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
894 EncStr = "pcrel sdata4";
896 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
897 EncStr = "pcrel udata8";
899 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
900 EncStr = "screl sdata8";
902 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
903 EncStr = "indirect pcrel udata4";
905 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
906 EncStr = "indirect pcrel sdata4";
908 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
909 EncStr = "indirect pcrel udata8";
911 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
912 EncStr = "indirect pcrel sdata8";
916 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
919 Streamer.EmitIntValue(Encoding, 1);
922 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
923 const MCCFIInstruction &Instr) {
924 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
925 bool VerboseAsm = Streamer.isVerboseAsm();
927 switch (Instr.getOperation()) {
928 case MCCFIInstruction::Move:
929 case MCCFIInstruction::RelMove: {
930 const MachineLocation &Dst = Instr.getDestination();
931 const MachineLocation &Src = Instr.getSource();
932 const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
935 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
936 if (Src.getReg() == MachineLocation::VirtualFP) {
937 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
938 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
940 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
941 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
942 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
943 Twine(Src.getReg()));
944 Streamer.EmitULEB128IntValue(Src.getReg());
948 CFAOffset += Src.getOffset();
950 CFAOffset = -Src.getOffset();
952 if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
953 Streamer.EmitULEB128IntValue(CFAOffset);
957 if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
958 assert(Dst.isReg() && "Machine move not supported yet.");
959 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
960 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
961 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
962 Streamer.EmitULEB128IntValue(Dst.getReg());
966 unsigned Reg = Src.getReg();
967 int Offset = Dst.getOffset();
970 Offset = Offset / dataAlignmentFactor;
973 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
974 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
975 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
976 Streamer.EmitULEB128IntValue(Reg);
977 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
978 Streamer.EmitSLEB128IntValue(Offset);
979 } else if (Reg < 64) {
980 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
982 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
983 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
984 Streamer.EmitULEB128IntValue(Offset);
986 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
987 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
988 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
989 Streamer.EmitULEB128IntValue(Reg);
990 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
991 Streamer.EmitULEB128IntValue(Offset);
995 case MCCFIInstruction::RememberState:
996 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
997 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
999 case MCCFIInstruction::RestoreState:
1000 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1001 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1003 case MCCFIInstruction::SameValue: {
1004 unsigned Reg = Instr.getDestination().getReg();
1005 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1006 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1007 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1008 Streamer.EmitULEB128IntValue(Reg);
1011 case MCCFIInstruction::Restore: {
1012 unsigned Reg = Instr.getDestination().getReg();
1014 Streamer.AddComment("DW_CFA_restore");
1015 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1017 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1020 case MCCFIInstruction::Escape:
1021 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1022 Streamer.EmitBytes(Instr.getValues(), 0);
1025 llvm_unreachable("Unhandled case in switch");
1028 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1030 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1031 const std::vector<MCCFIInstruction> &Instrs,
1032 MCSymbol *BaseLabel) {
1033 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1034 const MCCFIInstruction &Instr = Instrs[i];
1035 MCSymbol *Label = Instr.getLabel();
1036 // Throw out move if the label is invalid.
1037 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1039 // Advance row if new location.
1040 if (BaseLabel && Label) {
1041 MCSymbol *ThisSym = Label;
1042 if (ThisSym != BaseLabel) {
1043 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1044 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1045 BaseLabel = ThisSym;
1049 EmitCFIInstruction(streamer, Instr);
1053 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
1054 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
1055 /// normal CIE and FDE.
1056 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1057 const MCDwarfFrameInfo &Frame) {
1058 MCContext &Context = Streamer.getContext();
1059 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1060 bool VerboseAsm = Streamer.isVerboseAsm();
1062 // range-start range-length compact-unwind-enc personality-func lsda
1063 // _foo LfooEnd-_foo 0x00000023 0 0
1064 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1066 // .section __LD,__compact_unwind,regular,debug
1068 // # compact unwind for _foo
1070 // .set L1,LfooEnd-_foo
1076 // # compact unwind for _bar
1078 // .set L2,LbarEnd-_bar
1081 // .quad __gxx_personality
1082 // .quad except_tab1
1084 uint32_t Encoding = Frame.CompactUnwindEncoding;
1085 if (!Encoding) return false;
1087 // The encoding needs to know we have an LSDA.
1089 Encoding |= 0x40000000;
1091 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1094 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1095 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1096 if (VerboseAsm) Streamer.AddComment("Range Start");
1097 Streamer.EmitSymbolValue(Frame.Function, Size);
1100 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1102 if (VerboseAsm) Streamer.AddComment("Range Length");
1103 Streamer.EmitAbsValue(Range, 4);
1106 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1107 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1108 Twine::utohexstr(Encoding));
1109 Streamer.EmitIntValue(Encoding, Size);
1112 // Personality Function
1113 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1114 if (VerboseAsm) Streamer.AddComment("Personality Function");
1115 if (Frame.Personality)
1116 Streamer.EmitSymbolValue(Frame.Personality, Size);
1118 Streamer.EmitIntValue(0, Size); // No personality fn
1121 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1122 if (VerboseAsm) Streamer.AddComment("LSDA");
1124 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1126 Streamer.EmitIntValue(0, Size); // No LSDA
1131 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1132 const MCSymbol *personality,
1133 unsigned personalityEncoding,
1134 const MCSymbol *lsda,
1136 unsigned lsdaEncoding) {
1137 MCContext &context = streamer.getContext();
1138 const MCRegisterInfo &MRI = context.getRegisterInfo();
1139 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1140 bool verboseAsm = streamer.isVerboseAsm();
1142 MCSymbol *sectionStart;
1143 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1144 sectionStart = context.CreateTempSymbol();
1146 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1148 streamer.EmitLabel(sectionStart);
1151 MCSymbol *sectionEnd = context.CreateTempSymbol();
1154 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1156 if (verboseAsm) streamer.AddComment("CIE Length");
1157 streamer.EmitAbsValue(Length, 4);
1160 unsigned CIE_ID = IsEH ? 0 : -1;
1161 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1162 streamer.EmitIntValue(CIE_ID, 4);
1165 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1166 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1168 // Augmentation String
1169 SmallString<8> Augmentation;
1171 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1172 Augmentation += "z";
1174 Augmentation += "P";
1176 Augmentation += "L";
1177 Augmentation += "R";
1179 Augmentation += "S";
1180 streamer.EmitBytes(Augmentation.str(), 0);
1182 streamer.EmitIntValue(0, 1);
1184 // Code Alignment Factor
1185 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1186 streamer.EmitULEB128IntValue(1);
1188 // Data Alignment Factor
1189 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1190 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1192 // Return Address Register
1193 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1194 streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
1196 // Augmentation Data Length (optional)
1198 unsigned augmentationLength = 0;
1201 // Personality Encoding
1202 augmentationLength += 1;
1204 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1207 augmentationLength += 1;
1208 // Encoding of the FDE pointers
1209 augmentationLength += 1;
1211 if (verboseAsm) streamer.AddComment("Augmentation Size");
1212 streamer.EmitULEB128IntValue(augmentationLength);
1214 // Augmentation Data (optional)
1216 // Personality Encoding
1217 EmitEncodingByte(streamer, personalityEncoding,
1218 "Personality Encoding");
1220 if (verboseAsm) streamer.AddComment("Personality");
1221 EmitPersonality(streamer, *personality, personalityEncoding);
1225 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1227 // Encoding of the FDE pointers
1228 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1232 // Initial Instructions
1234 const MCAsmInfo &MAI = context.getAsmInfo();
1235 const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
1236 std::vector<MCCFIInstruction> Instructions;
1238 for (int i = 0, n = Moves.size(); i != n; ++i) {
1239 MCSymbol *Label = Moves[i].getLabel();
1240 const MachineLocation &Dst =
1241 TranslateMachineLocation(MRI, Moves[i].getDestination());
1242 const MachineLocation &Src =
1243 TranslateMachineLocation(MRI, Moves[i].getSource());
1244 MCCFIInstruction Inst(Label, Dst, Src);
1245 Instructions.push_back(Inst);
1248 EmitCFIInstructions(streamer, Instructions, NULL);
1251 streamer.EmitValueToAlignment(IsEH
1252 ? 4 : context.getAsmInfo().getPointerSize());
1254 streamer.EmitLabel(sectionEnd);
1255 return *sectionStart;
1258 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1259 const MCSymbol &cieStart,
1260 const MCDwarfFrameInfo &frame) {
1261 MCContext &context = streamer.getContext();
1262 MCSymbol *fdeStart = context.CreateTempSymbol();
1263 MCSymbol *fdeEnd = context.CreateTempSymbol();
1264 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1265 bool verboseAsm = streamer.isVerboseAsm();
1267 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1269 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1270 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1271 streamer.EmitLabel(EHSym);
1275 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1276 if (verboseAsm) streamer.AddComment("FDE Length");
1277 streamer.EmitAbsValue(Length, 4);
1279 streamer.EmitLabel(fdeStart);
1282 const MCAsmInfo &asmInfo = context.getAsmInfo();
1284 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1286 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1287 streamer.EmitAbsValue(offset, 4);
1288 } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
1289 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1291 streamer.EmitAbsValue(offset, 4);
1293 streamer.EmitSymbolValue(&cieStart, 4);
1296 unsigned fdeEncoding = MOFI->getFDEEncoding(UsingCFI);
1297 unsigned size = getSizeForEncoding(streamer, fdeEncoding);
1300 unsigned PCBeginEncoding = IsEH ? fdeEncoding :
1301 (unsigned)dwarf::DW_EH_PE_absptr;
1302 unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
1303 EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
1306 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1308 if (verboseAsm) streamer.AddComment("FDE address range");
1309 streamer.EmitAbsValue(Range, size);
1312 // Augmentation Data Length
1313 unsigned augmentationLength = 0;
1316 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1318 if (verboseAsm) streamer.AddComment("Augmentation size");
1319 streamer.EmitULEB128IntValue(augmentationLength);
1321 // Augmentation Data
1323 EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
1324 "Language Specific Data Area");
1327 // Call Frame Instructions
1329 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1332 streamer.EmitValueToAlignment(PCBeginSize);
1339 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false); }
1340 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false); }
1342 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1343 unsigned LsdaEncoding_, bool IsSignalFrame_) :
1344 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1345 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_) {
1347 const MCSymbol* Personality;
1348 unsigned PersonalityEncoding;
1349 unsigned LsdaEncoding;
1356 struct DenseMapInfo<CIEKey> {
1357 static CIEKey getEmptyKey() {
1358 return CIEKey::getEmptyKey();
1360 static CIEKey getTombstoneKey() {
1361 return CIEKey::getTombstoneKey();
1363 static unsigned getHashValue(const CIEKey &Key) {
1364 FoldingSetNodeID ID;
1365 ID.AddPointer(Key.Personality);
1366 ID.AddInteger(Key.PersonalityEncoding);
1367 ID.AddInteger(Key.LsdaEncoding);
1368 ID.AddBoolean(Key.IsSignalFrame);
1369 return ID.ComputeHash();
1371 static bool isEqual(const CIEKey &LHS,
1372 const CIEKey &RHS) {
1373 return LHS.Personality == RHS.Personality &&
1374 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1375 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1376 LHS.IsSignalFrame == RHS.IsSignalFrame;
1381 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
1384 MCContext &Context = Streamer.getContext();
1385 MCObjectFileInfo *MOFI =
1386 const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
1387 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1388 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1390 // Emit the compact unwind info if available.
1391 if (IsEH && MOFI->getCompactUnwindSection())
1392 for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
1393 const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
1394 if (Frame.CompactUnwindEncoding)
1395 Emitter.EmitCompactUnwind(Streamer, Frame);
1398 const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
1399 *MOFI->getDwarfFrameSection();
1400 Streamer.SwitchSection(&Section);
1401 MCSymbol *SectionStart = Context.CreateTempSymbol();
1402 Streamer.EmitLabel(SectionStart);
1403 Emitter.setSectionStart(SectionStart);
1405 MCSymbol *FDEEnd = NULL;
1406 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1408 const MCSymbol *DummyDebugKey = NULL;
1409 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1410 const MCDwarfFrameInfo &Frame = FrameArray[i];
1411 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1412 Frame.LsdaEncoding, Frame.IsSignalFrame);
1413 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1415 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1416 Frame.PersonalityEncoding, Frame.Lsda,
1417 Frame.IsSignalFrame,
1418 Frame.LsdaEncoding);
1420 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1423 Streamer.EmitLabel(FDEEnd);
1426 Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
1428 Streamer.EmitLabel(FDEEnd);
1431 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1432 uint64_t AddrDelta) {
1433 SmallString<256> Tmp;
1434 raw_svector_ostream OS(Tmp);
1435 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
1436 Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
1439 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
1441 // FIXME: Assumes the code alignment factor is 1.
1442 if (AddrDelta == 0) {
1443 } else if (isUIntN(6, AddrDelta)) {
1444 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1446 } else if (isUInt<8>(AddrDelta)) {
1447 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1448 OS << uint8_t(AddrDelta);
1449 } else if (isUInt<16>(AddrDelta)) {
1450 // FIXME: check what is the correct behavior on a big endian machine.
1451 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1452 OS << uint8_t( AddrDelta & 0xff);
1453 OS << uint8_t((AddrDelta >> 8) & 0xff);
1455 // FIXME: check what is the correct behavior on a big endian machine.
1456 assert(isUInt<32>(AddrDelta));
1457 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1458 OS << uint8_t( AddrDelta & 0xff);
1459 OS << uint8_t((AddrDelta >> 8) & 0xff);
1460 OS << uint8_t((AddrDelta >> 16) & 0xff);
1461 OS << uint8_t((AddrDelta >> 24) & 0xff);