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/LEB128.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/ADT/Hashing.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Config/config.h"
31 // Given a special op, return the address skip amount (in units of
32 // DWARF2_LINE_MIN_INSN_LENGTH.
33 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
35 // The maximum address skip amount that can be encoded with a special op.
36 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
38 // First special line opcode - leave room for the standard opcodes.
39 // Note: If you want to change this, you'll have to update the
40 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
41 #define DWARF2_LINE_OPCODE_BASE 13
43 // Minimum line offset in a special line info. opcode. This value
44 // was chosen to give a reasonable range of values.
45 #define DWARF2_LINE_BASE -5
47 // Range of line offsets in a special line info. opcode.
48 #define DWARF2_LINE_RANGE 14
50 // Define the architecture-dependent minimum instruction length (in bytes).
51 // This value should be rather too small than too big.
52 #define DWARF2_LINE_MIN_INSN_LENGTH 1
54 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
55 // this routine is a nop and will be optimized away.
56 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
57 if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
59 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
60 // TODO: report this error, but really only once.
63 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
67 // This is called when an instruction is assembled into the specified section
68 // and if there is information from the last .loc directive that has yet to have
69 // a line entry made for it is made.
71 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
72 if (!MCOS->getContext().getDwarfLocSeen())
75 // Create a symbol at in the current section for use in the line entry.
76 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
77 // Set the value of the symbol to use for the MCLineEntry.
78 MCOS->EmitLabel(LineSym);
80 // Get the current .loc info saved in the context.
81 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
83 // Create a (local) line entry with the symbol and the current .loc info.
84 MCLineEntry LineEntry(LineSym, DwarfLoc);
86 // clear DwarfLocSeen saying the current .loc info is now used.
87 MCOS->getContext().ClearDwarfLocSeen();
89 // Get the MCLineSection for this section, if one does not exist for this
91 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
92 MCOS->getContext().getMCLineSections();
93 MCLineSection *LineSection = MCLineSections.lookup(Section);
95 // Create a new MCLineSection. This will be deleted after the dwarf line
96 // table is created using it by iterating through the MCLineSections
98 LineSection = new MCLineSection;
99 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
100 MCOS->getContext().addMCLineSection(Section, LineSection);
103 // Add the line entry to this section's entries.
104 LineSection->addLineEntry(LineEntry);
108 // This helper routine returns an expression of End - Start + IntVal .
110 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
111 const MCSymbol &Start,
114 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
116 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
118 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
120 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
122 MCConstantExpr::Create(IntVal, MCOS.getContext());
124 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
129 // This emits the Dwarf line table for the specified section from the entries
130 // in the LineSection.
132 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
133 const MCSection *Section,
134 const MCLineSection *LineSection) {
135 unsigned FileNum = 1;
136 unsigned LastLine = 1;
138 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
140 MCSymbol *LastLabel = NULL;
142 // Loop through each MCLineEntry and encode the dwarf line number table.
143 for (MCLineSection::const_iterator
144 it = LineSection->getMCLineEntries()->begin(),
145 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
147 if (FileNum != it->getFileNum()) {
148 FileNum = it->getFileNum();
149 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
150 MCOS->EmitULEB128IntValue(FileNum);
152 if (Column != it->getColumn()) {
153 Column = it->getColumn();
154 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
155 MCOS->EmitULEB128IntValue(Column);
157 if (Isa != it->getIsa()) {
159 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
160 MCOS->EmitULEB128IntValue(Isa);
162 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
163 Flags = it->getFlags();
164 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
166 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
167 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
168 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
169 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
170 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
171 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
173 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
174 MCSymbol *Label = it->getLabel();
176 // At this point we want to emit/create the sequence to encode the delta in
177 // line numbers and the increment of the address from the previous Label
178 // and the current Label.
179 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
180 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
181 asmInfo.getPointerSize());
183 LastLine = it->getLine();
187 // Emit a DW_LNE_end_sequence for the end of the section.
188 // Using the pointer Section create a temporary label at the end of the
189 // section and use that and the LastLabel to compute the address delta
190 // and use INT64_MAX as the line delta which is the signal that this is
191 // actually a DW_LNE_end_sequence.
193 // Switch to the section to be able to create a symbol at its end.
194 MCOS->SwitchSection(Section);
196 MCContext &context = MCOS->getContext();
197 // Create a symbol at the end of the section.
198 MCSymbol *SectionEnd = context.CreateTempSymbol();
199 // Set the value of the symbol, as we are at the end of the section.
200 MCOS->EmitLabel(SectionEnd);
202 // Switch back the dwarf line section.
203 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
205 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
206 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
207 asmInfo.getPointerSize());
211 // This emits the Dwarf file and the line tables.
213 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
214 MCContext &context = MCOS->getContext();
215 // Switch to the section where the table will be emitted into.
216 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
218 // Create a symbol at the beginning of this section.
219 MCSymbol *LineStartSym = context.CreateTempSymbol();
220 // Set the value of the symbol, as we are at the start of the section.
221 MCOS->EmitLabel(LineStartSym);
223 // Create a symbol for the end of the section (to be set when we get there).
224 MCSymbol *LineEndSym = context.CreateTempSymbol();
226 // The first 4 bytes is the total length of the information for this
227 // compilation unit (not including these 4 bytes for the length).
228 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
231 // Next 2 bytes is the Version, which is Dwarf 2.
232 MCOS->EmitIntValue(2, 2);
234 // Create a symbol for the end of the prologue (to be set when we get there).
235 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
237 // Length of the prologue, is the next 4 bytes. Which is the start of the
238 // section to the end of the prologue. Not including the 4 bytes for the
239 // total length, the 2 bytes for the version, and these 4 bytes for the
240 // length of the prologue.
241 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
245 // Parameters of the state machine, are next.
246 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
247 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
248 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
249 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
250 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
252 // Standard opcode lengths
253 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
254 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
255 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
256 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
257 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
258 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
259 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
260 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
261 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
262 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
263 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
264 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
266 // Put out the directory and file tables.
268 // First the directory table.
269 const std::vector<StringRef> &MCDwarfDirs =
270 context.getMCDwarfDirs();
271 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
272 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
273 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
275 MCOS->EmitIntValue(0, 1); // Terminate the directory list
277 // Second the file table.
278 const std::vector<MCDwarfFile *> &MCDwarfFiles =
279 MCOS->getContext().getMCDwarfFiles();
280 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
281 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
282 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
284 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
285 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
286 MCOS->EmitIntValue(0, 1); // filesize (always 0)
288 MCOS->EmitIntValue(0, 1); // Terminate the file list
290 // This is the end of the prologue, so set the value of the symbol at the
291 // end of the prologue (that was used in a previous expression).
292 MCOS->EmitLabel(ProEndSym);
294 // Put out the line tables.
295 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
296 MCOS->getContext().getMCLineSections();
297 const std::vector<const MCSection *> &MCLineSectionOrder =
298 MCOS->getContext().getMCLineSectionOrder();
299 for (std::vector<const MCSection*>::const_iterator it =
300 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
302 const MCSection *Sec = *it;
303 const MCLineSection *Line = MCLineSections.lookup(Sec);
304 EmitDwarfLineTable(MCOS, Sec, Line);
306 // Now delete the MCLineSections that were created in MCLineEntry::Make()
307 // and used to emit the line table.
311 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
312 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
313 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
315 // total_length >= prologue_length + 10
316 // We are 4 bytes short, since we have total_length = 51 and
317 // prologue_length = 45
319 // The regular end_sequence should be sufficient.
320 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
323 // This is the end of the section, so set the value of the symbol at the end
324 // of this section (that was used in a previous expression).
325 MCOS->EmitLabel(LineEndSym);
330 /// Utility function to write the encoding to an object writer.
331 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
332 uint64_t AddrDelta) {
333 SmallString<256> Tmp;
334 raw_svector_ostream OS(Tmp);
335 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
336 OW->WriteBytes(OS.str());
339 /// Utility function to emit the encoding to a streamer.
340 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
341 uint64_t AddrDelta) {
342 SmallString<256> Tmp;
343 raw_svector_ostream OS(Tmp);
344 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
345 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
348 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
349 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
351 uint64_t Temp, Opcode;
352 bool NeedCopy = false;
354 // Scale the address delta by the minimum instruction length.
355 AddrDelta = ScaleAddrDelta(AddrDelta);
357 // A LineDelta of INT64_MAX is a signal that this is actually a
358 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
359 // end_sequence to emit the matrix entry.
360 if (LineDelta == INT64_MAX) {
361 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
362 OS << char(dwarf::DW_LNS_const_add_pc);
364 OS << char(dwarf::DW_LNS_advance_pc);
365 encodeULEB128(AddrDelta, OS);
367 OS << char(dwarf::DW_LNS_extended_op);
369 OS << char(dwarf::DW_LNE_end_sequence);
373 // Bias the line delta by the base.
374 Temp = LineDelta - DWARF2_LINE_BASE;
376 // If the line increment is out of range of a special opcode, we must encode
377 // it with DW_LNS_advance_line.
378 if (Temp >= DWARF2_LINE_RANGE) {
379 OS << char(dwarf::DW_LNS_advance_line);
380 encodeSLEB128(LineDelta, OS);
383 Temp = 0 - DWARF2_LINE_BASE;
387 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
388 if (LineDelta == 0 && AddrDelta == 0) {
389 OS << char(dwarf::DW_LNS_copy);
393 // Bias the opcode by the special opcode base.
394 Temp += DWARF2_LINE_OPCODE_BASE;
396 // Avoid overflow when addr_delta is large.
397 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
398 // Try using a special opcode.
399 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
405 // Try using DW_LNS_const_add_pc followed by special op.
406 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
408 OS << char(dwarf::DW_LNS_const_add_pc);
414 // Otherwise use DW_LNS_advance_pc.
415 OS << char(dwarf::DW_LNS_advance_pc);
416 encodeULEB128(AddrDelta, OS);
419 OS << char(dwarf::DW_LNS_copy);
424 void MCDwarfFile::print(raw_ostream &OS) const {
425 OS << '"' << getName() << '"';
428 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
429 void MCDwarfFile::dump() const {
434 // Utility function to write a tuple for .debug_abbrev.
435 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
436 MCOS->EmitULEB128IntValue(Name);
437 MCOS->EmitULEB128IntValue(Form);
440 // When generating dwarf for assembly source files this emits
441 // the data for .debug_abbrev section which contains three DIEs.
442 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
443 MCContext &context = MCOS->getContext();
444 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
446 // DW_TAG_compile_unit DIE abbrev (1).
447 MCOS->EmitULEB128IntValue(1);
448 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
449 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
450 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
451 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
452 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
453 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
454 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
455 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
456 if (!DwarfDebugFlags.empty())
457 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
458 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
459 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
460 EmitAbbrev(MCOS, 0, 0);
462 // DW_TAG_label DIE abbrev (2).
463 MCOS->EmitULEB128IntValue(2);
464 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
465 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
466 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
467 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
468 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
469 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
470 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
471 EmitAbbrev(MCOS, 0, 0);
473 // DW_TAG_unspecified_parameters DIE abbrev (3).
474 MCOS->EmitULEB128IntValue(3);
475 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
476 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
477 EmitAbbrev(MCOS, 0, 0);
479 // Terminate the abbreviations for this compilation unit.
480 MCOS->EmitIntValue(0, 1);
483 // When generating dwarf for assembly source files this emits the data for
484 // .debug_aranges section. Which contains a header and a table of pairs of
485 // PointerSize'ed values for the address and size of section(s) with line table
486 // entries (just the default .text in our case) and a terminating pair of zeros.
487 static void EmitGenDwarfAranges(MCStreamer *MCOS) {
488 MCContext &context = MCOS->getContext();
490 // Create a symbol at the end of the section that we are creating the dwarf
491 // debugging info to use later in here as part of the expression to calculate
492 // the size of the section for the table.
493 MCOS->SwitchSection(context.getGenDwarfSection());
494 MCSymbol *SectionEndSym = context.CreateTempSymbol();
495 MCOS->EmitLabel(SectionEndSym);
496 context.setGenDwarfSectionEndSym(SectionEndSym);
498 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
500 // This will be the length of the .debug_aranges section, first account for
501 // the size of each item in the header (see below where we emit these items).
502 int Length = 4 + 2 + 4 + 1 + 1;
504 // Figure the padding after the header before the table of address and size
505 // pairs who's values are PointerSize'ed.
506 const MCAsmInfo &asmInfo = context.getAsmInfo();
507 int AddrSize = asmInfo.getPointerSize();
508 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
509 if (Pad == 2 * AddrSize)
513 // Add the size of the pair of PointerSize'ed values for the address and size
514 // of the one default .text section we have in the table.
515 Length += 2 * AddrSize;
516 // And the pair of terminating zeros.
517 Length += 2 * AddrSize;
520 // Emit the header for this section.
521 // The 4 byte length not including the 4 byte value for the length.
522 MCOS->EmitIntValue(Length - 4, 4);
523 // The 2 byte version, which is 2.
524 MCOS->EmitIntValue(2, 2);
525 // The 4 byte offset to the compile unit in the .debug_info from the start
526 // of the .debug_info, it is at the start of that section so this is zero.
527 MCOS->EmitIntValue(0, 4);
528 // The 1 byte size of an address.
529 MCOS->EmitIntValue(AddrSize, 1);
530 // The 1 byte size of a segment descriptor, we use a value of zero.
531 MCOS->EmitIntValue(0, 1);
532 // Align the header with the padding if needed, before we put out the table.
533 for(int i = 0; i < Pad; i++)
534 MCOS->EmitIntValue(0, 1);
536 // Now emit the table of pairs of PointerSize'ed values for the section(s)
537 // address and size, in our case just the one default .text section.
538 const MCExpr *Addr = MCSymbolRefExpr::Create(
539 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
540 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
541 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
542 MCOS->EmitAbsValue(Addr, AddrSize);
543 MCOS->EmitAbsValue(Size, AddrSize);
545 // And finally the pair of terminating zeros.
546 MCOS->EmitIntValue(0, AddrSize);
547 MCOS->EmitIntValue(0, AddrSize);
550 // When generating dwarf for assembly source files this emits the data for
551 // .debug_info section which contains three parts. The header, the compile_unit
552 // DIE and a list of label DIEs.
553 static void EmitGenDwarfInfo(MCStreamer *MCOS,
554 const MCSymbol *AbbrevSectionSymbol,
555 const MCSymbol *LineSectionSymbol) {
556 MCContext &context = MCOS->getContext();
558 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
560 // Create a symbol at the start and end of this section used in here for the
561 // expression to calculate the length in the header.
562 MCSymbol *InfoStart = context.CreateTempSymbol();
563 MCOS->EmitLabel(InfoStart);
564 MCSymbol *InfoEnd = context.CreateTempSymbol();
566 // First part: the header.
568 // The 4 byte total length of the information for this compilation unit, not
569 // including these 4 bytes.
570 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
571 MCOS->EmitAbsValue(Length, 4);
573 // The 2 byte DWARF version, which is 2.
574 MCOS->EmitIntValue(2, 2);
576 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
577 // it is at the start of that section so this is zero.
578 if (AbbrevSectionSymbol) {
579 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
581 MCOS->EmitIntValue(0, 4);
584 const MCAsmInfo &asmInfo = context.getAsmInfo();
585 int AddrSize = asmInfo.getPointerSize();
586 // The 1 byte size of an address.
587 MCOS->EmitIntValue(AddrSize, 1);
589 // Second part: the compile_unit DIE.
591 // The DW_TAG_compile_unit DIE abbrev (1).
592 MCOS->EmitULEB128IntValue(1);
594 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
595 // which is at the start of that section so this is zero.
596 if (LineSectionSymbol) {
597 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
599 MCOS->EmitIntValue(0, 4);
602 // AT_low_pc, the first address of the default .text section.
603 const MCExpr *Start = MCSymbolRefExpr::Create(
604 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
605 MCOS->EmitAbsValue(Start, AddrSize);
607 // AT_high_pc, the last address of the default .text section.
608 const MCExpr *End = MCSymbolRefExpr::Create(
609 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
610 MCOS->EmitAbsValue(End, AddrSize);
612 // AT_name, the name of the source file. Reconstruct from the first directory
613 // and file table entries.
614 const std::vector<StringRef> &MCDwarfDirs =
615 context.getMCDwarfDirs();
616 if (MCDwarfDirs.size() > 0) {
617 MCOS->EmitBytes(MCDwarfDirs[0], 0);
618 MCOS->EmitBytes("/", 0);
620 const std::vector<MCDwarfFile *> &MCDwarfFiles =
621 MCOS->getContext().getMCDwarfFiles();
622 MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0);
623 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
625 // AT_comp_dir, the working directory the assembly was done in.
626 llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
627 MCOS->EmitBytes(StringRef(CWD.c_str()), 0);
628 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
630 // AT_APPLE_flags, the command line arguments of the assembler tool.
631 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
632 if (!DwarfDebugFlags.empty()){
633 MCOS->EmitBytes(DwarfDebugFlags, 0);
634 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
637 // AT_producer, the version of the assembler tool.
638 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0);
639 MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0);
640 MCOS->EmitBytes(StringRef(")"), 0);
641 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
643 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
644 // draft has no standard code for assembler.
645 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
647 // Third part: the list of label DIEs.
649 // Loop on saved info for dwarf labels and create the DIEs for them.
650 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
651 MCOS->getContext().getMCGenDwarfLabelEntries();
652 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
653 Entries.begin(), ie = Entries.end(); it != ie;
655 const MCGenDwarfLabelEntry *Entry = *it;
657 // The DW_TAG_label DIE abbrev (2).
658 MCOS->EmitULEB128IntValue(2);
660 // AT_name, of the label without any leading underbar.
661 MCOS->EmitBytes(Entry->getName(), 0);
662 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
664 // AT_decl_file, index into the file table.
665 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
667 // AT_decl_line, source line number.
668 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
670 // AT_low_pc, start address of the label.
671 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
672 MCSymbolRefExpr::VK_None, context);
673 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
675 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
676 MCOS->EmitIntValue(0, 1);
678 // The DW_TAG_unspecified_parameters DIE abbrev (3).
679 MCOS->EmitULEB128IntValue(3);
681 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
682 MCOS->EmitIntValue(0, 1);
684 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
685 // for the dwarf labels.
686 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
687 Entries.begin(), ie = Entries.end(); it != ie;
689 const MCGenDwarfLabelEntry *Entry = *it;
693 // Add the NULL DIE terminating the Compile Unit DIE's.
694 MCOS->EmitIntValue(0, 1);
696 // Now set the value of the symbol at the end of the info section.
697 MCOS->EmitLabel(InfoEnd);
701 // When generating dwarf for assembly source files this emits the Dwarf
704 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
705 // Create the dwarf sections in this order (.debug_line already created).
706 MCContext &context = MCOS->getContext();
707 const MCAsmInfo &AsmInfo = context.getAsmInfo();
708 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
709 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
710 MCSymbol *AbbrevSectionSymbol;
711 if (AsmInfo.doesDwarfUseRelocationsAcrossSections()) {
712 AbbrevSectionSymbol = context.CreateTempSymbol();
713 MCOS->EmitLabel(AbbrevSectionSymbol);
715 AbbrevSectionSymbol = NULL;
716 LineSectionSymbol = NULL;
718 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
720 // If there are no line table entries then do not emit any section contents.
721 if (context.getMCLineSections().empty())
724 // Output the data for .debug_aranges section.
725 EmitGenDwarfAranges(MCOS);
727 // Output the data for .debug_abbrev section.
728 EmitGenDwarfAbbrev(MCOS);
730 // Output the data for .debug_info section.
731 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
735 // When generating dwarf for assembly source files this is called when symbol
736 // for a label is created. If this symbol is not a temporary and is in the
737 // section that dwarf is being generated for, save the needed info to create
740 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
741 SourceMgr &SrcMgr, SMLoc &Loc) {
742 // We won't create dwarf labels for temporary symbols or symbols not in
744 if (Symbol->isTemporary())
746 MCContext &context = MCOS->getContext();
747 if (context.getGenDwarfSection() != MCOS->getCurrentSection())
750 // The dwarf label's name does not have the symbol name's leading
752 StringRef Name = Symbol->getName();
753 if (Name.startswith("_"))
754 Name = Name.substr(1, Name.size()-1);
756 // Get the dwarf file number to be used for the dwarf label.
757 unsigned FileNumber = context.getGenDwarfFileNumber();
759 // Finding the line number is the expensive part which is why we just don't
760 // pass it in as for some symbols we won't create a dwarf label.
761 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
762 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
764 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
765 // values so that they don't have things like an ARM thumb bit from the
766 // original symbol. So when used they won't get a low bit set after
768 MCSymbol *Label = context.CreateTempSymbol();
769 MCOS->EmitLabel(Label);
771 // Create and entry for the info and add it to the other entries.
772 MCGenDwarfLabelEntry *Entry =
773 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
774 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
777 static int getDataAlignmentFactor(MCStreamer &streamer) {
778 MCContext &context = streamer.getContext();
779 const MCAsmInfo &asmInfo = context.getAsmInfo();
780 int size = asmInfo.getPointerSize();
781 if (asmInfo.isStackGrowthDirectionUp())
787 static unsigned getSizeForEncoding(MCStreamer &streamer,
788 unsigned symbolEncoding) {
789 MCContext &context = streamer.getContext();
790 unsigned format = symbolEncoding & 0x0f;
792 default: llvm_unreachable("Unknown Encoding");
793 case dwarf::DW_EH_PE_absptr:
794 case dwarf::DW_EH_PE_signed:
795 return context.getAsmInfo().getPointerSize();
796 case dwarf::DW_EH_PE_udata2:
797 case dwarf::DW_EH_PE_sdata2:
799 case dwarf::DW_EH_PE_udata4:
800 case dwarf::DW_EH_PE_sdata4:
802 case dwarf::DW_EH_PE_udata8:
803 case dwarf::DW_EH_PE_sdata8:
808 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
809 unsigned symbolEncoding, const char *comment = 0) {
810 MCContext &context = streamer.getContext();
811 const MCAsmInfo &asmInfo = context.getAsmInfo();
812 const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
815 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
816 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
817 streamer.EmitAbsValue(v, size);
820 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
821 unsigned symbolEncoding) {
822 MCContext &context = streamer.getContext();
823 const MCAsmInfo &asmInfo = context.getAsmInfo();
824 const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
827 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
828 streamer.EmitValue(v, size);
831 static const MachineLocation TranslateMachineLocation(
832 const MCRegisterInfo &MRI,
833 const MachineLocation &Loc) {
834 unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
835 MachineLocation::VirtualFP :
836 unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
837 const MachineLocation &NewLoc = Loc.isReg() ?
838 MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
843 class FrameEmitterImpl {
848 const MCSymbol *SectionStart;
850 FrameEmitterImpl(bool usingCFI, bool isEH)
851 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
854 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
856 /// EmitCompactUnwind - Emit the unwind information in a compact way. If
857 /// we're successful, return 'true'. Otherwise, return 'false' and it will
858 /// emit the normal CIE and FDE.
859 bool EmitCompactUnwind(MCStreamer &streamer,
860 const MCDwarfFrameInfo &frame);
862 const MCSymbol &EmitCIE(MCStreamer &streamer,
863 const MCSymbol *personality,
864 unsigned personalityEncoding,
865 const MCSymbol *lsda,
867 unsigned lsdaEncoding);
868 MCSymbol *EmitFDE(MCStreamer &streamer,
869 const MCSymbol &cieStart,
870 const MCDwarfFrameInfo &frame);
871 void EmitCFIInstructions(MCStreamer &streamer,
872 const std::vector<MCCFIInstruction> &Instrs,
873 MCSymbol *BaseLabel);
874 void EmitCFIInstruction(MCStreamer &Streamer,
875 const MCCFIInstruction &Instr);
878 } // end anonymous namespace
880 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
882 if (Streamer.isVerboseAsm()) {
885 default: EncStr = "<unknown encoding>"; break;
886 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
887 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
888 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
889 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
890 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
891 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
892 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
893 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
894 EncStr = "pcrel udata4";
896 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
897 EncStr = "pcrel sdata4";
899 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
900 EncStr = "pcrel udata8";
902 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
903 EncStr = "screl sdata8";
905 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
906 EncStr = "indirect pcrel udata4";
908 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
909 EncStr = "indirect pcrel sdata4";
911 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
912 EncStr = "indirect pcrel udata8";
914 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
915 EncStr = "indirect pcrel sdata8";
919 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
922 Streamer.EmitIntValue(Encoding, 1);
925 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
926 const MCCFIInstruction &Instr) {
927 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
928 bool VerboseAsm = Streamer.isVerboseAsm();
930 switch (Instr.getOperation()) {
931 case MCCFIInstruction::Move:
932 case MCCFIInstruction::RelMove: {
933 const MachineLocation &Dst = Instr.getDestination();
934 const MachineLocation &Src = Instr.getSource();
935 const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
938 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
939 if (Src.getReg() == MachineLocation::VirtualFP) {
940 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
941 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
943 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
944 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
945 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
946 Twine(Src.getReg()));
947 Streamer.EmitULEB128IntValue(Src.getReg());
951 CFAOffset += Src.getOffset();
953 CFAOffset = -Src.getOffset();
955 if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
956 Streamer.EmitULEB128IntValue(CFAOffset);
960 if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
961 assert(Dst.isReg() && "Machine move not supported yet.");
962 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
963 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
964 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
965 Streamer.EmitULEB128IntValue(Dst.getReg());
969 unsigned Reg = Src.getReg();
970 int Offset = Dst.getOffset();
973 Offset = Offset / dataAlignmentFactor;
976 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
977 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
978 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
979 Streamer.EmitULEB128IntValue(Reg);
980 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
981 Streamer.EmitSLEB128IntValue(Offset);
982 } else if (Reg < 64) {
983 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
985 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
986 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
987 Streamer.EmitULEB128IntValue(Offset);
989 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
990 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
991 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
992 Streamer.EmitULEB128IntValue(Reg);
993 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
994 Streamer.EmitULEB128IntValue(Offset);
998 case MCCFIInstruction::RememberState:
999 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1000 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1002 case MCCFIInstruction::RestoreState:
1003 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1004 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1006 case MCCFIInstruction::SameValue: {
1007 unsigned Reg = Instr.getDestination().getReg();
1008 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1009 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1010 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1011 Streamer.EmitULEB128IntValue(Reg);
1014 case MCCFIInstruction::Restore: {
1015 unsigned Reg = Instr.getDestination().getReg();
1017 Streamer.AddComment("DW_CFA_restore");
1018 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1020 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1023 case MCCFIInstruction::Escape:
1024 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1025 Streamer.EmitBytes(Instr.getValues(), 0);
1028 llvm_unreachable("Unhandled case in switch");
1031 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1033 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1034 const std::vector<MCCFIInstruction> &Instrs,
1035 MCSymbol *BaseLabel) {
1036 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1037 const MCCFIInstruction &Instr = Instrs[i];
1038 MCSymbol *Label = Instr.getLabel();
1039 // Throw out move if the label is invalid.
1040 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1042 // Advance row if new location.
1043 if (BaseLabel && Label) {
1044 MCSymbol *ThisSym = Label;
1045 if (ThisSym != BaseLabel) {
1046 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1047 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1048 BaseLabel = ThisSym;
1052 EmitCFIInstruction(streamer, Instr);
1056 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
1057 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
1058 /// normal CIE and FDE.
1059 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1060 const MCDwarfFrameInfo &Frame) {
1061 MCContext &Context = Streamer.getContext();
1062 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1063 bool VerboseAsm = Streamer.isVerboseAsm();
1065 // range-start range-length compact-unwind-enc personality-func lsda
1066 // _foo LfooEnd-_foo 0x00000023 0 0
1067 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1069 // .section __LD,__compact_unwind,regular,debug
1071 // # compact unwind for _foo
1073 // .set L1,LfooEnd-_foo
1079 // # compact unwind for _bar
1081 // .set L2,LbarEnd-_bar
1084 // .quad __gxx_personality
1085 // .quad except_tab1
1087 uint32_t Encoding = Frame.CompactUnwindEncoding;
1088 if (!Encoding) return false;
1090 // The encoding needs to know we have an LSDA.
1092 Encoding |= 0x40000000;
1094 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1097 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1098 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1099 if (VerboseAsm) Streamer.AddComment("Range Start");
1100 Streamer.EmitSymbolValue(Frame.Function, Size);
1103 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1105 if (VerboseAsm) Streamer.AddComment("Range Length");
1106 Streamer.EmitAbsValue(Range, 4);
1109 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1110 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1111 Twine::utohexstr(Encoding));
1112 Streamer.EmitIntValue(Encoding, Size);
1115 // Personality Function
1116 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1117 if (VerboseAsm) Streamer.AddComment("Personality Function");
1118 if (Frame.Personality)
1119 Streamer.EmitSymbolValue(Frame.Personality, Size);
1121 Streamer.EmitIntValue(0, Size); // No personality fn
1124 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1125 if (VerboseAsm) Streamer.AddComment("LSDA");
1127 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1129 Streamer.EmitIntValue(0, Size); // No LSDA
1134 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1135 const MCSymbol *personality,
1136 unsigned personalityEncoding,
1137 const MCSymbol *lsda,
1139 unsigned lsdaEncoding) {
1140 MCContext &context = streamer.getContext();
1141 const MCRegisterInfo &MRI = context.getRegisterInfo();
1142 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1143 bool verboseAsm = streamer.isVerboseAsm();
1145 MCSymbol *sectionStart;
1146 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1147 sectionStart = context.CreateTempSymbol();
1149 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1151 streamer.EmitLabel(sectionStart);
1154 MCSymbol *sectionEnd = context.CreateTempSymbol();
1157 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1159 if (verboseAsm) streamer.AddComment("CIE Length");
1160 streamer.EmitAbsValue(Length, 4);
1163 unsigned CIE_ID = IsEH ? 0 : -1;
1164 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1165 streamer.EmitIntValue(CIE_ID, 4);
1168 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1169 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1171 // Augmentation String
1172 SmallString<8> Augmentation;
1174 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1175 Augmentation += "z";
1177 Augmentation += "P";
1179 Augmentation += "L";
1180 Augmentation += "R";
1182 Augmentation += "S";
1183 streamer.EmitBytes(Augmentation.str(), 0);
1185 streamer.EmitIntValue(0, 1);
1187 // Code Alignment Factor
1188 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1189 streamer.EmitULEB128IntValue(1);
1191 // Data Alignment Factor
1192 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1193 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1195 // Return Address Register
1196 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1197 streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
1199 // Augmentation Data Length (optional)
1201 unsigned augmentationLength = 0;
1204 // Personality Encoding
1205 augmentationLength += 1;
1207 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1210 augmentationLength += 1;
1211 // Encoding of the FDE pointers
1212 augmentationLength += 1;
1214 if (verboseAsm) streamer.AddComment("Augmentation Size");
1215 streamer.EmitULEB128IntValue(augmentationLength);
1217 // Augmentation Data (optional)
1219 // Personality Encoding
1220 EmitEncodingByte(streamer, personalityEncoding,
1221 "Personality Encoding");
1223 if (verboseAsm) streamer.AddComment("Personality");
1224 EmitPersonality(streamer, *personality, personalityEncoding);
1228 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1230 // Encoding of the FDE pointers
1231 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1235 // Initial Instructions
1237 const MCAsmInfo &MAI = context.getAsmInfo();
1238 const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
1239 std::vector<MCCFIInstruction> Instructions;
1241 for (int i = 0, n = Moves.size(); i != n; ++i) {
1242 MCSymbol *Label = Moves[i].getLabel();
1243 const MachineLocation &Dst =
1244 TranslateMachineLocation(MRI, Moves[i].getDestination());
1245 const MachineLocation &Src =
1246 TranslateMachineLocation(MRI, Moves[i].getSource());
1247 MCCFIInstruction Inst(Label, Dst, Src);
1248 Instructions.push_back(Inst);
1251 EmitCFIInstructions(streamer, Instructions, NULL);
1254 streamer.EmitValueToAlignment(IsEH
1255 ? 4 : context.getAsmInfo().getPointerSize());
1257 streamer.EmitLabel(sectionEnd);
1258 return *sectionStart;
1261 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1262 const MCSymbol &cieStart,
1263 const MCDwarfFrameInfo &frame) {
1264 MCContext &context = streamer.getContext();
1265 MCSymbol *fdeStart = context.CreateTempSymbol();
1266 MCSymbol *fdeEnd = context.CreateTempSymbol();
1267 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1268 bool verboseAsm = streamer.isVerboseAsm();
1270 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1272 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1273 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1274 streamer.EmitLabel(EHSym);
1278 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1279 if (verboseAsm) streamer.AddComment("FDE Length");
1280 streamer.EmitAbsValue(Length, 4);
1282 streamer.EmitLabel(fdeStart);
1285 const MCAsmInfo &asmInfo = context.getAsmInfo();
1287 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1289 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1290 streamer.EmitAbsValue(offset, 4);
1291 } else if (!asmInfo.doesDwarfUseRelocationsAcrossSections()) {
1292 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1294 streamer.EmitAbsValue(offset, 4);
1296 streamer.EmitSymbolValue(&cieStart, 4);
1300 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1301 : (unsigned)dwarf::DW_EH_PE_absptr;
1302 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1303 EmitSymbol(streamer, *frame.Begin, PCEncoding, "FDE initial location");
1306 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1308 if (verboseAsm) streamer.AddComment("FDE address range");
1309 streamer.EmitAbsValue(Range, PCSize);
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(PCSize);
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 return static_cast<unsigned>(hash_combine(Key.Personality,
1365 Key.PersonalityEncoding,
1367 Key.IsSignalFrame));
1369 static bool isEqual(const CIEKey &LHS,
1370 const CIEKey &RHS) {
1371 return LHS.Personality == RHS.Personality &&
1372 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1373 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1374 LHS.IsSignalFrame == RHS.IsSignalFrame;
1379 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
1382 MCContext &Context = Streamer.getContext();
1383 MCObjectFileInfo *MOFI =
1384 const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
1385 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1386 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1388 // Emit the compact unwind info if available.
1389 if (IsEH && MOFI->getCompactUnwindSection())
1390 for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
1391 const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
1392 if (Frame.CompactUnwindEncoding)
1393 Emitter.EmitCompactUnwind(Streamer, Frame);
1396 const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
1397 *MOFI->getDwarfFrameSection();
1398 Streamer.SwitchSection(&Section);
1399 MCSymbol *SectionStart = Context.CreateTempSymbol();
1400 Streamer.EmitLabel(SectionStart);
1401 Emitter.setSectionStart(SectionStart);
1403 MCSymbol *FDEEnd = NULL;
1404 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1406 const MCSymbol *DummyDebugKey = NULL;
1407 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1408 const MCDwarfFrameInfo &Frame = FrameArray[i];
1409 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1410 Frame.LsdaEncoding, Frame.IsSignalFrame);
1411 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1413 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1414 Frame.PersonalityEncoding, Frame.Lsda,
1415 Frame.IsSignalFrame,
1416 Frame.LsdaEncoding);
1418 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1421 Streamer.EmitLabel(FDEEnd);
1424 Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
1426 Streamer.EmitLabel(FDEEnd);
1429 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1430 uint64_t AddrDelta) {
1431 SmallString<256> Tmp;
1432 raw_svector_ostream OS(Tmp);
1433 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
1434 Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
1437 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
1439 // FIXME: Assumes the code alignment factor is 1.
1440 if (AddrDelta == 0) {
1441 } else if (isUIntN(6, AddrDelta)) {
1442 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1444 } else if (isUInt<8>(AddrDelta)) {
1445 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1446 OS << uint8_t(AddrDelta);
1447 } else if (isUInt<16>(AddrDelta)) {
1448 // FIXME: check what is the correct behavior on a big endian machine.
1449 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1450 OS << uint8_t( AddrDelta & 0xff);
1451 OS << uint8_t((AddrDelta >> 8) & 0xff);
1453 // FIXME: check what is the correct behavior on a big endian machine.
1454 assert(isUInt<32>(AddrDelta));
1455 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1456 OS << uint8_t( AddrDelta & 0xff);
1457 OS << uint8_t((AddrDelta >> 8) & 0xff);
1458 OS << uint8_t((AddrDelta >> 16) & 0xff);
1459 OS << uint8_t((AddrDelta >> 24) & 0xff);