1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCDwarf.h"
11 #include "llvm/ADT/Hashing.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/Config/config.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectFileInfo.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.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 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
50 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
51 if (MinInsnLength == 1)
53 if (AddrDelta % MinInsnLength != 0) {
54 // TODO: report this error, but really only once.
57 return AddrDelta / MinInsnLength;
61 // This is called when an instruction is assembled into the specified section
62 // and if there is information from the last .loc directive that has yet to have
63 // a line entry made for it is made.
65 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
66 if (!MCOS->getContext().getDwarfLocSeen())
69 // Create a symbol at in the current section for use in the line entry.
70 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
71 // Set the value of the symbol to use for the MCLineEntry.
72 MCOS->EmitLabel(LineSym);
74 // Get the current .loc info saved in the context.
75 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
77 // Create a (local) line entry with the symbol and the current .loc info.
78 MCLineEntry LineEntry(LineSym, DwarfLoc);
80 // clear DwarfLocSeen saying the current .loc info is now used.
81 MCOS->getContext().ClearDwarfLocSeen();
83 // Add the line entry to this section's entries.
85 .getMCDwarfFileTable(MCOS->getContext().getDwarfCompileUnitID())
87 .addLineEntry(LineEntry, Section);
91 // This helper routine returns an expression of End - Start + IntVal .
93 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
94 const MCSymbol &Start,
97 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
99 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
101 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
103 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
105 MCConstantExpr::Create(IntVal, MCOS.getContext());
107 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
112 // This emits the Dwarf line table for the specified section from the entries
113 // in the LineSection.
116 EmitDwarfLineTable(MCStreamer *MCOS, const MCSection *Section,
117 const MCLineSection::MCLineEntryCollection &LineEntries) {
118 unsigned FileNum = 1;
119 unsigned LastLine = 1;
121 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
123 unsigned Discriminator = 0;
124 MCSymbol *LastLabel = NULL;
126 // Loop through each MCLineEntry and encode the dwarf line number table.
127 for (auto it = LineEntries.begin(),
128 ie = LineEntries.end();
131 if (FileNum != it->getFileNum()) {
132 FileNum = it->getFileNum();
133 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
134 MCOS->EmitULEB128IntValue(FileNum);
136 if (Column != it->getColumn()) {
137 Column = it->getColumn();
138 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
139 MCOS->EmitULEB128IntValue(Column);
141 if (Discriminator != it->getDiscriminator()) {
142 Discriminator = it->getDiscriminator();
143 unsigned Size = getULEB128Size(Discriminator);
144 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
145 MCOS->EmitULEB128IntValue(Size + 1);
146 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
147 MCOS->EmitULEB128IntValue(Discriminator);
149 if (Isa != it->getIsa()) {
151 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
152 MCOS->EmitULEB128IntValue(Isa);
154 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
155 Flags = it->getFlags();
156 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
158 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
159 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
160 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
161 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
162 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
165 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
166 MCSymbol *Label = it->getLabel();
168 // At this point we want to emit/create the sequence to encode the delta in
169 // line numbers and the increment of the address from the previous Label
170 // and the current Label.
171 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
172 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
173 asmInfo->getPointerSize());
175 LastLine = it->getLine();
179 // Emit a DW_LNE_end_sequence for the end of the section.
180 // Using the pointer Section create a temporary label at the end of the
181 // section and use that and the LastLabel to compute the address delta
182 // and use INT64_MAX as the line delta which is the signal that this is
183 // actually a DW_LNE_end_sequence.
185 // Switch to the section to be able to create a symbol at its end.
186 // TODO: keep track of the last subsection so that this symbol appears in the
188 MCOS->SwitchSection(Section);
190 MCContext &context = MCOS->getContext();
191 // Create a symbol at the end of the section.
192 MCSymbol *SectionEnd = context.CreateTempSymbol();
193 // Set the value of the symbol, as we are at the end of the section.
194 MCOS->EmitLabel(SectionEnd);
196 // Switch back the dwarf line section.
197 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
199 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
200 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
201 asmInfo->getPointerSize());
205 // This emits the Dwarf file and the line tables.
207 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
208 MCContext &context = MCOS->getContext();
210 // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does
211 // not exist, CUID will be 0 and MCLineTableSymbols will be empty.
212 // Handle Compile Unit 0, the line table start symbol is the section symbol.
213 auto I = MCOS->getContext().getMCDwarfFileTables().begin(),
214 E = MCOS->getContext().getMCDwarfFileTables().end();
216 // Switch to the section where the table will be emitted into.
217 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
219 const MCSymbol *LineStartSym = I->second.EmitCU(MCOS);
220 // Handle the rest of the Compile Units.
221 for (++I; I != E; ++I)
222 I->second.EmitCU(MCOS);
227 const MCSymbol *MCDwarfFileTable::EmitCU(MCStreamer *MCOS) const {
228 MCContext &context = MCOS->getContext();
232 // Create a symbol at the beginning of the line table.
233 MCSymbol *LineStartSym = Label;
235 LineStartSym = context.CreateTempSymbol();
236 // Set the value of the symbol, as we are at the start of the line table.
237 MCOS->EmitLabel(LineStartSym);
239 // Create a symbol for the end of the section (to be set when we get there).
240 MCSymbol *LineEndSym = context.CreateTempSymbol();
242 // The first 4 bytes is the total length of the information for this
243 // compilation unit (not including these 4 bytes for the length).
244 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
247 // Next 2 bytes is the Version, which is Dwarf 2.
248 MCOS->EmitIntValue(2, 2);
250 // Create a symbol for the end of the prologue (to be set when we get there).
251 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
253 // Length of the prologue, is the next 4 bytes. Which is the start of the
254 // section to the end of the prologue. Not including the 4 bytes for the
255 // total length, the 2 bytes for the version, and these 4 bytes for the
256 // length of the prologue.
257 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
260 // Parameters of the state machine, are next.
261 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
262 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
263 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
264 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
265 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
267 // Standard opcode lengths
268 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
269 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
270 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
271 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
272 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
273 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
274 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
275 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
276 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
277 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
278 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
279 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
281 // Put out the directory and file tables.
283 // First the directory table.
284 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
285 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
286 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
288 MCOS->EmitIntValue(0, 1); // Terminate the directory list
290 // Second the file table.
291 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
292 MCOS->EmitBytes(MCDwarfFiles[i]->Name); // FileName
293 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
295 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->DirIndex);
296 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
297 MCOS->EmitIntValue(0, 1); // filesize (always 0)
299 MCOS->EmitIntValue(0, 1); // Terminate the file list
301 // This is the end of the prologue, so set the value of the symbol at the
302 // end of the prologue (that was used in a previous expression).
303 MCOS->EmitLabel(ProEndSym);
305 // Put out the line tables.
306 for (const auto &LineSec : MCLineSections.getMCLineEntries())
307 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
309 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
310 MCLineSections.getMCLineEntries().empty()) {
311 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
313 // total_length >= prologue_length + 10
314 // We are 4 bytes short, since we have total_length = 51 and
315 // prologue_length = 45
317 // The regular end_sequence should be sufficient.
318 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
321 // This is the end of the section, so set the value of the symbol at the end
322 // of this section (that was used in a previous expression).
323 MCOS->EmitLabel(LineEndSym);
328 /// Utility function to emit the encoding to a streamer.
329 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
330 uint64_t AddrDelta) {
331 MCContext &Context = MCOS->getContext();
332 SmallString<256> Tmp;
333 raw_svector_ostream OS(Tmp);
334 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
335 MCOS->EmitBytes(OS.str());
338 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
339 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
340 uint64_t AddrDelta, raw_ostream &OS) {
341 uint64_t Temp, Opcode;
342 bool NeedCopy = false;
344 // Scale the address delta by the minimum instruction length.
345 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
347 // A LineDelta of INT64_MAX is a signal that this is actually a
348 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
349 // end_sequence to emit the matrix entry.
350 if (LineDelta == INT64_MAX) {
351 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
352 OS << char(dwarf::DW_LNS_const_add_pc);
354 OS << char(dwarf::DW_LNS_advance_pc);
355 encodeULEB128(AddrDelta, OS);
357 OS << char(dwarf::DW_LNS_extended_op);
359 OS << char(dwarf::DW_LNE_end_sequence);
363 // Bias the line delta by the base.
364 Temp = LineDelta - DWARF2_LINE_BASE;
366 // If the line increment is out of range of a special opcode, we must encode
367 // it with DW_LNS_advance_line.
368 if (Temp >= DWARF2_LINE_RANGE) {
369 OS << char(dwarf::DW_LNS_advance_line);
370 encodeSLEB128(LineDelta, OS);
373 Temp = 0 - DWARF2_LINE_BASE;
377 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
378 if (LineDelta == 0 && AddrDelta == 0) {
379 OS << char(dwarf::DW_LNS_copy);
383 // Bias the opcode by the special opcode base.
384 Temp += DWARF2_LINE_OPCODE_BASE;
386 // Avoid overflow when addr_delta is large.
387 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
388 // Try using a special opcode.
389 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
395 // Try using DW_LNS_const_add_pc followed by special op.
396 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
398 OS << char(dwarf::DW_LNS_const_add_pc);
404 // Otherwise use DW_LNS_advance_pc.
405 OS << char(dwarf::DW_LNS_advance_pc);
406 encodeULEB128(AddrDelta, OS);
409 OS << char(dwarf::DW_LNS_copy);
414 // Utility function to write a tuple for .debug_abbrev.
415 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
416 MCOS->EmitULEB128IntValue(Name);
417 MCOS->EmitULEB128IntValue(Form);
420 // When generating dwarf for assembly source files this emits
421 // the data for .debug_abbrev section which contains three DIEs.
422 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
423 MCContext &context = MCOS->getContext();
424 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
426 // DW_TAG_compile_unit DIE abbrev (1).
427 MCOS->EmitULEB128IntValue(1);
428 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
429 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
430 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
431 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
432 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
433 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
434 if (!context.getCompilationDir().empty())
435 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
436 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
437 if (!DwarfDebugFlags.empty())
438 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
439 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
440 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
441 EmitAbbrev(MCOS, 0, 0);
443 // DW_TAG_label DIE abbrev (2).
444 MCOS->EmitULEB128IntValue(2);
445 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
446 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
447 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
448 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
449 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
450 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
451 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
452 EmitAbbrev(MCOS, 0, 0);
454 // DW_TAG_unspecified_parameters DIE abbrev (3).
455 MCOS->EmitULEB128IntValue(3);
456 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
457 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
458 EmitAbbrev(MCOS, 0, 0);
460 // Terminate the abbreviations for this compilation unit.
461 MCOS->EmitIntValue(0, 1);
464 // When generating dwarf for assembly source files this emits the data for
465 // .debug_aranges section. Which contains a header and a table of pairs of
466 // PointerSize'ed values for the address and size of section(s) with line table
467 // entries (just the default .text in our case) and a terminating pair of zeros.
468 static void EmitGenDwarfAranges(MCStreamer *MCOS,
469 const MCSymbol *InfoSectionSymbol) {
470 MCContext &context = MCOS->getContext();
472 // Create a symbol at the end of the section that we are creating the dwarf
473 // debugging info to use later in here as part of the expression to calculate
474 // the size of the section for the table.
475 MCOS->SwitchSection(context.getGenDwarfSection());
476 MCSymbol *SectionEndSym = context.CreateTempSymbol();
477 MCOS->EmitLabel(SectionEndSym);
478 context.setGenDwarfSectionEndSym(SectionEndSym);
480 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
482 // This will be the length of the .debug_aranges section, first account for
483 // the size of each item in the header (see below where we emit these items).
484 int Length = 4 + 2 + 4 + 1 + 1;
486 // Figure the padding after the header before the table of address and size
487 // pairs who's values are PointerSize'ed.
488 const MCAsmInfo *asmInfo = context.getAsmInfo();
489 int AddrSize = asmInfo->getPointerSize();
490 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
491 if (Pad == 2 * AddrSize)
495 // Add the size of the pair of PointerSize'ed values for the address and size
496 // of the one default .text section we have in the table.
497 Length += 2 * AddrSize;
498 // And the pair of terminating zeros.
499 Length += 2 * AddrSize;
502 // Emit the header for this section.
503 // The 4 byte length not including the 4 byte value for the length.
504 MCOS->EmitIntValue(Length - 4, 4);
505 // The 2 byte version, which is 2.
506 MCOS->EmitIntValue(2, 2);
507 // The 4 byte offset to the compile unit in the .debug_info from the start
508 // of the .debug_info.
509 if (InfoSectionSymbol)
510 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
512 MCOS->EmitIntValue(0, 4);
513 // The 1 byte size of an address.
514 MCOS->EmitIntValue(AddrSize, 1);
515 // The 1 byte size of a segment descriptor, we use a value of zero.
516 MCOS->EmitIntValue(0, 1);
517 // Align the header with the padding if needed, before we put out the table.
518 for(int i = 0; i < Pad; i++)
519 MCOS->EmitIntValue(0, 1);
521 // Now emit the table of pairs of PointerSize'ed values for the section(s)
522 // address and size, in our case just the one default .text section.
523 const MCExpr *Addr = MCSymbolRefExpr::Create(
524 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
525 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
526 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
527 MCOS->EmitAbsValue(Addr, AddrSize);
528 MCOS->EmitAbsValue(Size, AddrSize);
530 // And finally the pair of terminating zeros.
531 MCOS->EmitIntValue(0, AddrSize);
532 MCOS->EmitIntValue(0, AddrSize);
535 // When generating dwarf for assembly source files this emits the data for
536 // .debug_info section which contains three parts. The header, the compile_unit
537 // DIE and a list of label DIEs.
538 static void EmitGenDwarfInfo(MCStreamer *MCOS,
539 const MCSymbol *AbbrevSectionSymbol,
540 const MCSymbol *LineSectionSymbol) {
541 MCContext &context = MCOS->getContext();
543 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
545 // Create a symbol at the start and end of this section used in here for the
546 // expression to calculate the length in the header.
547 MCSymbol *InfoStart = context.CreateTempSymbol();
548 MCOS->EmitLabel(InfoStart);
549 MCSymbol *InfoEnd = context.CreateTempSymbol();
551 // First part: the header.
553 // The 4 byte total length of the information for this compilation unit, not
554 // including these 4 bytes.
555 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
556 MCOS->EmitAbsValue(Length, 4);
558 // The 2 byte DWARF version, which is 2.
559 MCOS->EmitIntValue(2, 2);
561 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
562 // it is at the start of that section so this is zero.
563 if (AbbrevSectionSymbol) {
564 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
566 MCOS->EmitIntValue(0, 4);
569 const MCAsmInfo *asmInfo = context.getAsmInfo();
570 int AddrSize = asmInfo->getPointerSize();
571 // The 1 byte size of an address.
572 MCOS->EmitIntValue(AddrSize, 1);
574 // Second part: the compile_unit DIE.
576 // The DW_TAG_compile_unit DIE abbrev (1).
577 MCOS->EmitULEB128IntValue(1);
579 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
580 // which is at the start of that section so this is zero.
581 if (LineSectionSymbol) {
582 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
584 MCOS->EmitIntValue(0, 4);
587 // AT_low_pc, the first address of the default .text section.
588 const MCExpr *Start = MCSymbolRefExpr::Create(
589 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
590 MCOS->EmitAbsValue(Start, AddrSize);
592 // AT_high_pc, the last address of the default .text section.
593 const MCExpr *End = MCSymbolRefExpr::Create(
594 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
595 MCOS->EmitAbsValue(End, AddrSize);
597 // AT_name, the name of the source file. Reconstruct from the first directory
598 // and file table entries.
599 const SmallVectorImpl<StringRef> &MCDwarfDirs =
600 context.getMCDwarfDirs();
601 if (MCDwarfDirs.size() > 0) {
602 MCOS->EmitBytes(MCDwarfDirs[0]);
603 MCOS->EmitBytes("/");
605 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
606 MCOS->getContext().getMCDwarfFiles();
607 MCOS->EmitBytes(MCDwarfFiles[1]->Name);
608 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
610 // AT_comp_dir, the working directory the assembly was done in.
611 if (!context.getCompilationDir().empty()) {
612 MCOS->EmitBytes(context.getCompilationDir());
613 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
616 // AT_APPLE_flags, the command line arguments of the assembler tool.
617 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
618 if (!DwarfDebugFlags.empty()){
619 MCOS->EmitBytes(DwarfDebugFlags);
620 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
623 // AT_producer, the version of the assembler tool.
624 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
625 if (!DwarfDebugProducer.empty()){
626 MCOS->EmitBytes(DwarfDebugProducer);
629 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
630 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
631 MCOS->EmitBytes(StringRef(")"));
633 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
635 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
636 // draft has no standard code for assembler.
637 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
639 // Third part: the list of label DIEs.
641 // Loop on saved info for dwarf labels and create the DIEs for them.
642 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
643 MCOS->getContext().getMCGenDwarfLabelEntries();
644 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
645 Entries.begin(), ie = Entries.end(); it != ie;
647 const MCGenDwarfLabelEntry *Entry = *it;
649 // The DW_TAG_label DIE abbrev (2).
650 MCOS->EmitULEB128IntValue(2);
652 // AT_name, of the label without any leading underbar.
653 MCOS->EmitBytes(Entry->getName());
654 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
656 // AT_decl_file, index into the file table.
657 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
659 // AT_decl_line, source line number.
660 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
662 // AT_low_pc, start address of the label.
663 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
664 MCSymbolRefExpr::VK_None, context);
665 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
667 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
668 MCOS->EmitIntValue(0, 1);
670 // The DW_TAG_unspecified_parameters DIE abbrev (3).
671 MCOS->EmitULEB128IntValue(3);
673 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
674 MCOS->EmitIntValue(0, 1);
676 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
677 // for the dwarf labels.
678 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
679 Entries.begin(), ie = Entries.end(); it != ie;
681 const MCGenDwarfLabelEntry *Entry = *it;
685 // Add the NULL DIE terminating the Compile Unit DIE's.
686 MCOS->EmitIntValue(0, 1);
688 // Now set the value of the symbol at the end of the info section.
689 MCOS->EmitLabel(InfoEnd);
693 // When generating dwarf for assembly source files this emits the Dwarf
696 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
697 // Create the dwarf sections in this order (.debug_line already created).
698 MCContext &context = MCOS->getContext();
699 const MCAsmInfo *AsmInfo = context.getAsmInfo();
700 bool CreateDwarfSectionSymbols =
701 AsmInfo->doesDwarfUseRelocationsAcrossSections();
702 if (!CreateDwarfSectionSymbols)
703 LineSectionSymbol = NULL;
704 MCSymbol *AbbrevSectionSymbol = NULL;
705 MCSymbol *InfoSectionSymbol = NULL;
706 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
707 if (CreateDwarfSectionSymbols) {
708 InfoSectionSymbol = context.CreateTempSymbol();
709 MCOS->EmitLabel(InfoSectionSymbol);
711 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
712 if (CreateDwarfSectionSymbols) {
713 AbbrevSectionSymbol = context.CreateTempSymbol();
714 MCOS->EmitLabel(AbbrevSectionSymbol);
716 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
718 // If there are no line table entries then do not emit any section contents.
719 if (!context.hasMCLineSections())
722 // Output the data for .debug_aranges section.
723 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
725 // Output the data for .debug_abbrev section.
726 EmitGenDwarfAbbrev(MCOS);
728 // Output the data for .debug_info section.
729 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
733 // When generating dwarf for assembly source files this is called when symbol
734 // for a label is created. If this symbol is not a temporary and is in the
735 // section that dwarf is being generated for, save the needed info to create
738 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
739 SourceMgr &SrcMgr, SMLoc &Loc) {
740 // We won't create dwarf labels for temporary symbols or symbols not in
742 if (Symbol->isTemporary())
744 MCContext &context = MCOS->getContext();
745 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
748 // The dwarf label's name does not have the symbol name's leading
750 StringRef Name = Symbol->getName();
751 if (Name.startswith("_"))
752 Name = Name.substr(1, Name.size()-1);
754 // Get the dwarf file number to be used for the dwarf label.
755 unsigned FileNumber = context.getGenDwarfFileNumber();
757 // Finding the line number is the expensive part which is why we just don't
758 // pass it in as for some symbols we won't create a dwarf label.
759 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
760 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
762 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
763 // values so that they don't have things like an ARM thumb bit from the
764 // original symbol. So when used they won't get a low bit set after
766 MCSymbol *Label = context.CreateTempSymbol();
767 MCOS->EmitLabel(Label);
769 // Create and entry for the info and add it to the other entries.
770 MCGenDwarfLabelEntry *Entry =
771 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
772 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
775 static int getDataAlignmentFactor(MCStreamer &streamer) {
776 MCContext &context = streamer.getContext();
777 const MCAsmInfo *asmInfo = context.getAsmInfo();
778 int size = asmInfo->getCalleeSaveStackSlotSize();
779 if (asmInfo->isStackGrowthDirectionUp())
785 static unsigned getSizeForEncoding(MCStreamer &streamer,
786 unsigned symbolEncoding) {
787 MCContext &context = streamer.getContext();
788 unsigned format = symbolEncoding & 0x0f;
790 default: llvm_unreachable("Unknown Encoding");
791 case dwarf::DW_EH_PE_absptr:
792 case dwarf::DW_EH_PE_signed:
793 return context.getAsmInfo()->getPointerSize();
794 case dwarf::DW_EH_PE_udata2:
795 case dwarf::DW_EH_PE_sdata2:
797 case dwarf::DW_EH_PE_udata4:
798 case dwarf::DW_EH_PE_sdata4:
800 case dwarf::DW_EH_PE_udata8:
801 case dwarf::DW_EH_PE_sdata8:
806 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
807 unsigned symbolEncoding, bool isEH,
808 const char *comment = 0) {
809 MCContext &context = streamer.getContext();
810 const MCAsmInfo *asmInfo = context.getAsmInfo();
811 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
814 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
815 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
816 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
817 streamer.EmitAbsValue(v, size);
819 streamer.EmitValue(v, size);
822 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
823 unsigned symbolEncoding) {
824 MCContext &context = streamer.getContext();
825 const MCAsmInfo *asmInfo = context.getAsmInfo();
826 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
829 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
830 streamer.EmitValue(v, size);
834 class FrameEmitterImpl {
839 const MCSymbol *SectionStart;
841 FrameEmitterImpl(bool usingCFI, bool isEH)
842 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
845 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
847 /// EmitCompactUnwind - Emit the unwind information in a compact way.
848 void EmitCompactUnwind(MCStreamer &streamer,
849 const MCDwarfFrameInfo &frame);
851 const MCSymbol &EmitCIE(MCStreamer &streamer,
852 const MCSymbol *personality,
853 unsigned personalityEncoding,
854 const MCSymbol *lsda,
856 unsigned lsdaEncoding,
858 MCSymbol *EmitFDE(MCStreamer &streamer,
859 const MCSymbol &cieStart,
860 const MCDwarfFrameInfo &frame);
861 void EmitCFIInstructions(MCStreamer &streamer,
862 ArrayRef<MCCFIInstruction> Instrs,
863 MCSymbol *BaseLabel);
864 void EmitCFIInstruction(MCStreamer &Streamer,
865 const MCCFIInstruction &Instr);
868 } // end anonymous namespace
870 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
872 if (Streamer.isVerboseAsm()) {
875 default: EncStr = "<unknown encoding>"; break;
876 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
877 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
878 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
879 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
880 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
881 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
882 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
883 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
884 EncStr = "pcrel udata4";
886 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
887 EncStr = "pcrel sdata4";
889 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
890 EncStr = "pcrel udata8";
892 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
893 EncStr = "screl sdata8";
895 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
896 EncStr = "indirect pcrel udata4";
898 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
899 EncStr = "indirect pcrel sdata4";
901 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
902 EncStr = "indirect pcrel udata8";
904 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
905 EncStr = "indirect pcrel sdata8";
909 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
912 Streamer.EmitIntValue(Encoding, 1);
915 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
916 const MCCFIInstruction &Instr) {
917 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
918 bool VerboseAsm = Streamer.isVerboseAsm();
920 switch (Instr.getOperation()) {
921 case MCCFIInstruction::OpRegister: {
922 unsigned Reg1 = Instr.getRegister();
923 unsigned Reg2 = Instr.getRegister2();
925 Streamer.AddComment("DW_CFA_register");
926 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
927 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
929 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
930 Streamer.EmitULEB128IntValue(Reg1);
931 Streamer.EmitULEB128IntValue(Reg2);
934 case MCCFIInstruction::OpWindowSave: {
935 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
938 case MCCFIInstruction::OpUndefined: {
939 unsigned Reg = Instr.getRegister();
941 Streamer.AddComment("DW_CFA_undefined");
942 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
944 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
945 Streamer.EmitULEB128IntValue(Reg);
948 case MCCFIInstruction::OpAdjustCfaOffset:
949 case MCCFIInstruction::OpDefCfaOffset: {
950 const bool IsRelative =
951 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
954 Streamer.AddComment("DW_CFA_def_cfa_offset");
955 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
958 CFAOffset += Instr.getOffset();
960 CFAOffset = -Instr.getOffset();
963 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
964 Streamer.EmitULEB128IntValue(CFAOffset);
968 case MCCFIInstruction::OpDefCfa: {
970 Streamer.AddComment("DW_CFA_def_cfa");
971 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
974 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
975 Streamer.EmitULEB128IntValue(Instr.getRegister());
977 CFAOffset = -Instr.getOffset();
980 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
981 Streamer.EmitULEB128IntValue(CFAOffset);
986 case MCCFIInstruction::OpDefCfaRegister: {
988 Streamer.AddComment("DW_CFA_def_cfa_register");
989 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
992 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
993 Streamer.EmitULEB128IntValue(Instr.getRegister());
998 case MCCFIInstruction::OpOffset:
999 case MCCFIInstruction::OpRelOffset: {
1000 const bool IsRelative =
1001 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1003 unsigned Reg = Instr.getRegister();
1004 int Offset = Instr.getOffset();
1006 Offset -= CFAOffset;
1007 Offset = Offset / dataAlignmentFactor;
1010 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1011 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1012 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1013 Streamer.EmitULEB128IntValue(Reg);
1014 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1015 Streamer.EmitSLEB128IntValue(Offset);
1016 } else if (Reg < 64) {
1017 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1019 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1020 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1021 Streamer.EmitULEB128IntValue(Offset);
1023 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1024 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1025 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1026 Streamer.EmitULEB128IntValue(Reg);
1027 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1028 Streamer.EmitULEB128IntValue(Offset);
1032 case MCCFIInstruction::OpRememberState:
1033 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1034 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1036 case MCCFIInstruction::OpRestoreState:
1037 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1038 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1040 case MCCFIInstruction::OpSameValue: {
1041 unsigned Reg = Instr.getRegister();
1042 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1043 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1044 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1045 Streamer.EmitULEB128IntValue(Reg);
1048 case MCCFIInstruction::OpRestore: {
1049 unsigned Reg = Instr.getRegister();
1051 Streamer.AddComment("DW_CFA_restore");
1052 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1054 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1057 case MCCFIInstruction::OpEscape:
1058 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1059 Streamer.EmitBytes(Instr.getValues());
1062 llvm_unreachable("Unhandled case in switch");
1065 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1067 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1068 ArrayRef<MCCFIInstruction> Instrs,
1069 MCSymbol *BaseLabel) {
1070 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1071 const MCCFIInstruction &Instr = Instrs[i];
1072 MCSymbol *Label = Instr.getLabel();
1073 // Throw out move if the label is invalid.
1074 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1076 // Advance row if new location.
1077 if (BaseLabel && Label) {
1078 MCSymbol *ThisSym = Label;
1079 if (ThisSym != BaseLabel) {
1080 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1081 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1082 BaseLabel = ThisSym;
1086 EmitCFIInstruction(streamer, Instr);
1090 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1091 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1092 const MCDwarfFrameInfo &Frame) {
1093 MCContext &Context = Streamer.getContext();
1094 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1095 bool VerboseAsm = Streamer.isVerboseAsm();
1097 // range-start range-length compact-unwind-enc personality-func lsda
1098 // _foo LfooEnd-_foo 0x00000023 0 0
1099 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1101 // .section __LD,__compact_unwind,regular,debug
1103 // # compact unwind for _foo
1105 // .set L1,LfooEnd-_foo
1111 // # compact unwind for _bar
1113 // .set L2,LbarEnd-_bar
1116 // .quad __gxx_personality
1117 // .quad except_tab1
1119 uint32_t Encoding = Frame.CompactUnwindEncoding;
1120 if (!Encoding) return;
1121 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1123 // The encoding needs to know we have an LSDA.
1124 if (!DwarfEHFrameOnly && Frame.Lsda)
1125 Encoding |= 0x40000000;
1128 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1129 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1130 if (VerboseAsm) Streamer.AddComment("Range Start");
1131 Streamer.EmitSymbolValue(Frame.Function, Size);
1134 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1136 if (VerboseAsm) Streamer.AddComment("Range Length");
1137 Streamer.EmitAbsValue(Range, 4);
1140 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1141 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1142 Twine::utohexstr(Encoding));
1143 Streamer.EmitIntValue(Encoding, Size);
1145 // Personality Function
1146 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1147 if (VerboseAsm) Streamer.AddComment("Personality Function");
1148 if (!DwarfEHFrameOnly && Frame.Personality)
1149 Streamer.EmitSymbolValue(Frame.Personality, Size);
1151 Streamer.EmitIntValue(0, Size); // No personality fn
1154 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1155 if (VerboseAsm) Streamer.AddComment("LSDA");
1156 if (!DwarfEHFrameOnly && Frame.Lsda)
1157 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1159 Streamer.EmitIntValue(0, Size); // No LSDA
1162 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1163 const MCSymbol *personality,
1164 unsigned personalityEncoding,
1165 const MCSymbol *lsda,
1167 unsigned lsdaEncoding,
1169 MCContext &context = streamer.getContext();
1170 const MCRegisterInfo *MRI = context.getRegisterInfo();
1171 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1172 bool verboseAsm = streamer.isVerboseAsm();
1174 MCSymbol *sectionStart;
1175 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1176 sectionStart = context.CreateTempSymbol();
1178 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1180 streamer.EmitLabel(sectionStart);
1183 MCSymbol *sectionEnd = context.CreateTempSymbol();
1186 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1188 if (verboseAsm) streamer.AddComment("CIE Length");
1189 streamer.EmitAbsValue(Length, 4);
1192 unsigned CIE_ID = IsEH ? 0 : -1;
1193 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1194 streamer.EmitIntValue(CIE_ID, 4);
1197 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1198 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1200 // Augmentation String
1201 SmallString<8> Augmentation;
1203 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1204 Augmentation += "z";
1206 Augmentation += "P";
1208 Augmentation += "L";
1209 Augmentation += "R";
1211 Augmentation += "S";
1212 streamer.EmitBytes(Augmentation.str());
1214 streamer.EmitIntValue(0, 1);
1216 // Code Alignment Factor
1217 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1218 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1220 // Data Alignment Factor
1221 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1222 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1224 // Return Address Register
1225 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1226 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1228 // Augmentation Data Length (optional)
1230 unsigned augmentationLength = 0;
1233 // Personality Encoding
1234 augmentationLength += 1;
1236 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1239 augmentationLength += 1;
1240 // Encoding of the FDE pointers
1241 augmentationLength += 1;
1243 if (verboseAsm) streamer.AddComment("Augmentation Size");
1244 streamer.EmitULEB128IntValue(augmentationLength);
1246 // Augmentation Data (optional)
1248 // Personality Encoding
1249 EmitEncodingByte(streamer, personalityEncoding,
1250 "Personality Encoding");
1252 if (verboseAsm) streamer.AddComment("Personality");
1253 EmitPersonality(streamer, *personality, personalityEncoding);
1257 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1259 // Encoding of the FDE pointers
1260 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1264 // Initial Instructions
1266 const MCAsmInfo *MAI = context.getAsmInfo();
1268 const std::vector<MCCFIInstruction> &Instructions =
1269 MAI->getInitialFrameState();
1270 EmitCFIInstructions(streamer, Instructions, NULL);
1274 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1276 streamer.EmitLabel(sectionEnd);
1277 return *sectionStart;
1280 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1281 const MCSymbol &cieStart,
1282 const MCDwarfFrameInfo &frame) {
1283 MCContext &context = streamer.getContext();
1284 MCSymbol *fdeStart = context.CreateTempSymbol();
1285 MCSymbol *fdeEnd = context.CreateTempSymbol();
1286 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1287 bool verboseAsm = streamer.isVerboseAsm();
1289 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1291 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1292 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1293 streamer.EmitLabel(EHSym);
1297 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1298 if (verboseAsm) streamer.AddComment("FDE Length");
1299 streamer.EmitAbsValue(Length, 4);
1301 streamer.EmitLabel(fdeStart);
1304 const MCAsmInfo *asmInfo = context.getAsmInfo();
1306 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1308 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1309 streamer.EmitAbsValue(offset, 4);
1310 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1311 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1313 streamer.EmitAbsValue(offset, 4);
1315 streamer.EmitSymbolValue(&cieStart, 4);
1319 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1320 : (unsigned)dwarf::DW_EH_PE_absptr;
1321 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1322 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1325 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1327 if (verboseAsm) streamer.AddComment("FDE address range");
1328 streamer.EmitAbsValue(Range, PCSize);
1331 // Augmentation Data Length
1332 unsigned augmentationLength = 0;
1335 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1337 if (verboseAsm) streamer.AddComment("Augmentation size");
1338 streamer.EmitULEB128IntValue(augmentationLength);
1340 // Augmentation Data
1342 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1343 "Language Specific Data Area");
1346 // Call Frame Instructions
1347 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1350 streamer.EmitValueToAlignment(PCSize);
1357 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1358 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1360 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1361 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1362 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1363 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1364 IsSimple(IsSimple_) {
1366 const MCSymbol* Personality;
1367 unsigned PersonalityEncoding;
1368 unsigned LsdaEncoding;
1376 struct DenseMapInfo<CIEKey> {
1377 static CIEKey getEmptyKey() {
1378 return CIEKey::getEmptyKey();
1380 static CIEKey getTombstoneKey() {
1381 return CIEKey::getTombstoneKey();
1383 static unsigned getHashValue(const CIEKey &Key) {
1384 return static_cast<unsigned>(hash_combine(Key.Personality,
1385 Key.PersonalityEncoding,
1390 static bool isEqual(const CIEKey &LHS,
1391 const CIEKey &RHS) {
1392 return LHS.Personality == RHS.Personality &&
1393 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1394 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1395 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1396 LHS.IsSimple == RHS.IsSimple;
1401 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1402 bool UsingCFI, bool IsEH) {
1403 Streamer.generateCompactUnwindEncodings(MAB);
1405 MCContext &Context = Streamer.getContext();
1406 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1407 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1408 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1410 // Emit the compact unwind info if available.
1411 if (IsEH && MOFI->getCompactUnwindSection()) {
1412 bool SectionEmitted = false;
1413 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1414 const MCDwarfFrameInfo &Frame = FrameArray[i];
1415 if (Frame.CompactUnwindEncoding == 0) continue;
1416 if (!SectionEmitted) {
1417 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1418 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1419 SectionEmitted = true;
1421 Emitter.EmitCompactUnwind(Streamer, Frame);
1425 const MCSection &Section =
1426 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1427 *MOFI->getDwarfFrameSection();
1428 Streamer.SwitchSection(&Section);
1429 MCSymbol *SectionStart = Context.CreateTempSymbol();
1430 Streamer.EmitLabel(SectionStart);
1431 Emitter.setSectionStart(SectionStart);
1433 MCSymbol *FDEEnd = NULL;
1434 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1436 const MCSymbol *DummyDebugKey = NULL;
1437 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1438 const MCDwarfFrameInfo &Frame = FrameArray[i];
1439 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1440 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1441 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1443 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1444 Frame.PersonalityEncoding, Frame.Lsda,
1445 Frame.IsSignalFrame,
1449 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1452 Streamer.EmitLabel(FDEEnd);
1455 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1457 Streamer.EmitLabel(FDEEnd);
1460 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1461 uint64_t AddrDelta) {
1462 MCContext &Context = Streamer.getContext();
1463 SmallString<256> Tmp;
1464 raw_svector_ostream OS(Tmp);
1465 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1466 Streamer.EmitBytes(OS.str());
1469 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1472 // Scale the address delta by the minimum instruction length.
1473 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1475 if (AddrDelta == 0) {
1476 } else if (isUIntN(6, AddrDelta)) {
1477 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1479 } else if (isUInt<8>(AddrDelta)) {
1480 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1481 OS << uint8_t(AddrDelta);
1482 } else if (isUInt<16>(AddrDelta)) {
1483 // FIXME: check what is the correct behavior on a big endian machine.
1484 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1485 OS << uint8_t( AddrDelta & 0xff);
1486 OS << uint8_t((AddrDelta >> 8) & 0xff);
1488 // FIXME: check what is the correct behavior on a big endian machine.
1489 assert(isUInt<32>(AddrDelta));
1490 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1491 OS << uint8_t( AddrDelta & 0xff);
1492 OS << uint8_t((AddrDelta >> 8) & 0xff);
1493 OS << uint8_t((AddrDelta >> 16) & 0xff);
1494 OS << uint8_t((AddrDelta >> 24) & 0xff);