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 .getMCDwarfLineTable(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 *MCDwarfLineTable::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().getMCDwarfLineTables().begin(),
214 E = MCOS->getContext().getMCDwarfLineTables().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 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
228 MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
231 std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
232 static const char StandardOpcodeLengths[] = {
233 0, // length of DW_LNS_copy
234 1, // length of DW_LNS_advance_pc
235 1, // length of DW_LNS_advance_line
236 1, // length of DW_LNS_set_file
237 1, // length of DW_LNS_set_column
238 0, // length of DW_LNS_negate_stmt
239 0, // length of DW_LNS_set_basic_block
240 0, // length of DW_LNS_const_add_pc
241 1, // length of DW_LNS_fixed_advance_pc
242 0, // length of DW_LNS_set_prologue_end
243 0, // length of DW_LNS_set_epilogue_begin
246 assert(array_lengthof(StandardOpcodeLengths) == (DWARF2_LINE_OPCODE_BASE - 1));
247 return Emit(MCOS, StandardOpcodeLengths);
250 std::pair<MCSymbol *, MCSymbol *>
251 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
252 ArrayRef<char> StandardOpcodeLengths) const {
254 MCContext &context = MCOS->getContext();
256 // Create a symbol at the beginning of the line table.
257 MCSymbol *LineStartSym = Label;
259 LineStartSym = context.CreateTempSymbol();
260 // Set the value of the symbol, as we are at the start of the line table.
261 MCOS->EmitLabel(LineStartSym);
263 // Create a symbol for the end of the section (to be set when we get there).
264 MCSymbol *LineEndSym = context.CreateTempSymbol();
266 // The first 4 bytes is the total length of the information for this
267 // compilation unit (not including these 4 bytes for the length).
268 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
271 // Next 2 bytes is the Version, which is Dwarf 2.
272 MCOS->EmitIntValue(2, 2);
274 // Create a symbol for the end of the prologue (to be set when we get there).
275 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
277 // Length of the prologue, is the next 4 bytes. Which is the start of the
278 // section to the end of the prologue. Not including the 4 bytes for the
279 // total length, the 2 bytes for the version, and these 4 bytes for the
280 // length of the prologue.
281 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
284 // Parameters of the state machine, are next.
285 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
286 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
287 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
288 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
289 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
291 // Standard opcode lengths
292 for (char Length : StandardOpcodeLengths)
293 MCOS->EmitIntValue(Length, 1);
295 // Put out the directory and file tables.
297 // First the directory table.
298 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
299 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
300 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
302 MCOS->EmitIntValue(0, 1); // Terminate the directory list
304 // Second the file table.
305 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
306 assert(!MCDwarfFiles[i].Name.empty());
307 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
308 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
310 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
311 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
312 MCOS->EmitIntValue(0, 1); // filesize (always 0)
314 MCOS->EmitIntValue(0, 1); // Terminate the file list
316 // This is the end of the prologue, so set the value of the symbol at the
317 // end of the prologue (that was used in a previous expression).
318 MCOS->EmitLabel(ProEndSym);
320 return std::make_pair(LineStartSym, LineEndSym);
323 const MCSymbol *MCDwarfLineTable::EmitCU(MCStreamer *MCOS) const {
324 MCSymbol *LineStartSym;
325 MCSymbol *LineEndSym;
326 std::tie(LineStartSym, LineEndSym) = Header.Emit(MCOS);
328 // Put out the line tables.
329 for (const auto &LineSec : MCLineSections.getMCLineEntries())
330 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
332 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
333 MCLineSections.getMCLineEntries().empty()) {
334 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
336 // total_length >= prologue_length + 10
337 // We are 4 bytes short, since we have total_length = 51 and
338 // prologue_length = 45
340 // The regular end_sequence should be sufficient.
341 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
344 // This is the end of the section, so set the value of the symbol at the end
345 // of this section (that was used in a previous expression).
346 MCOS->EmitLabel(LineEndSym);
351 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
352 unsigned FileNumber) {
353 return Header.getFile(Directory, FileName, FileNumber);
356 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
358 unsigned FileNumber) {
359 if (Directory == CompilationDir)
361 if (FileName.empty()) {
362 FileName = "<stdin>";
365 assert(!FileName.empty());
366 if (FileNumber == 0) {
367 FileNumber = SourceIdMap.size() + 1;
368 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
369 "Don't mix autonumbered and explicit numbered line table usage");
370 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(
371 (Directory + Twine('\0') + FileName).str(), FileNumber);
372 if (Ent.getValue() != FileNumber)
373 return Ent.getValue();
375 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
376 MCDwarfFiles.resize(FileNumber + 1);
378 // Get the new MCDwarfFile slot for this FileNumber.
379 MCDwarfFile &File = MCDwarfFiles[FileNumber];
381 // It is an error to use see the same number more than once.
382 if (!File.Name.empty())
385 if (Directory.empty()) {
386 // Separate the directory part from the basename of the FileName.
387 StringRef tFileName = sys::path::filename(FileName);
388 if (!tFileName.empty()) {
389 Directory = sys::path::parent_path(FileName);
390 if (!Directory.empty())
391 FileName = tFileName;
395 // Find or make an entry in the MCDwarfDirs vector for this Directory.
396 // Capture directory name.
398 if (Directory.empty()) {
399 // For FileNames with no directories a DirIndex of 0 is used.
403 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
404 if (Directory == MCDwarfDirs[DirIndex])
407 if (DirIndex >= MCDwarfDirs.size())
408 MCDwarfDirs.push_back(Directory);
409 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
410 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
411 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
412 // are stored at MCDwarfFiles[FileNumber].Name .
416 File.Name = FileName;
417 File.DirIndex = DirIndex;
419 // return the allocated FileNumber.
423 /// Utility function to emit the encoding to a streamer.
424 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
425 uint64_t AddrDelta) {
426 MCContext &Context = MCOS->getContext();
427 SmallString<256> Tmp;
428 raw_svector_ostream OS(Tmp);
429 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
430 MCOS->EmitBytes(OS.str());
433 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
434 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
435 uint64_t AddrDelta, raw_ostream &OS) {
436 uint64_t Temp, Opcode;
437 bool NeedCopy = false;
439 // Scale the address delta by the minimum instruction length.
440 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
442 // A LineDelta of INT64_MAX is a signal that this is actually a
443 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
444 // end_sequence to emit the matrix entry.
445 if (LineDelta == INT64_MAX) {
446 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
447 OS << char(dwarf::DW_LNS_const_add_pc);
449 OS << char(dwarf::DW_LNS_advance_pc);
450 encodeULEB128(AddrDelta, OS);
452 OS << char(dwarf::DW_LNS_extended_op);
454 OS << char(dwarf::DW_LNE_end_sequence);
458 // Bias the line delta by the base.
459 Temp = LineDelta - DWARF2_LINE_BASE;
461 // If the line increment is out of range of a special opcode, we must encode
462 // it with DW_LNS_advance_line.
463 if (Temp >= DWARF2_LINE_RANGE) {
464 OS << char(dwarf::DW_LNS_advance_line);
465 encodeSLEB128(LineDelta, OS);
468 Temp = 0 - DWARF2_LINE_BASE;
472 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
473 if (LineDelta == 0 && AddrDelta == 0) {
474 OS << char(dwarf::DW_LNS_copy);
478 // Bias the opcode by the special opcode base.
479 Temp += DWARF2_LINE_OPCODE_BASE;
481 // Avoid overflow when addr_delta is large.
482 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
483 // Try using a special opcode.
484 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
490 // Try using DW_LNS_const_add_pc followed by special op.
491 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
493 OS << char(dwarf::DW_LNS_const_add_pc);
499 // Otherwise use DW_LNS_advance_pc.
500 OS << char(dwarf::DW_LNS_advance_pc);
501 encodeULEB128(AddrDelta, OS);
504 OS << char(dwarf::DW_LNS_copy);
509 // Utility function to write a tuple for .debug_abbrev.
510 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
511 MCOS->EmitULEB128IntValue(Name);
512 MCOS->EmitULEB128IntValue(Form);
515 // When generating dwarf for assembly source files this emits
516 // the data for .debug_abbrev section which contains three DIEs.
517 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
518 MCContext &context = MCOS->getContext();
519 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
521 // DW_TAG_compile_unit DIE abbrev (1).
522 MCOS->EmitULEB128IntValue(1);
523 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
524 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
525 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
526 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
527 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
528 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
529 if (!context.getCompilationDir().empty())
530 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
531 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
532 if (!DwarfDebugFlags.empty())
533 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
534 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
535 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
536 EmitAbbrev(MCOS, 0, 0);
538 // DW_TAG_label DIE abbrev (2).
539 MCOS->EmitULEB128IntValue(2);
540 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
541 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
542 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
543 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
544 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
545 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
546 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
547 EmitAbbrev(MCOS, 0, 0);
549 // DW_TAG_unspecified_parameters DIE abbrev (3).
550 MCOS->EmitULEB128IntValue(3);
551 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
552 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
553 EmitAbbrev(MCOS, 0, 0);
555 // Terminate the abbreviations for this compilation unit.
556 MCOS->EmitIntValue(0, 1);
559 // When generating dwarf for assembly source files this emits the data for
560 // .debug_aranges section. Which contains a header and a table of pairs of
561 // PointerSize'ed values for the address and size of section(s) with line table
562 // entries (just the default .text in our case) and a terminating pair of zeros.
563 static void EmitGenDwarfAranges(MCStreamer *MCOS,
564 const MCSymbol *InfoSectionSymbol) {
565 MCContext &context = MCOS->getContext();
567 // Create a symbol at the end of the section that we are creating the dwarf
568 // debugging info to use later in here as part of the expression to calculate
569 // the size of the section for the table.
570 MCOS->SwitchSection(context.getGenDwarfSection());
571 MCSymbol *SectionEndSym = context.CreateTempSymbol();
572 MCOS->EmitLabel(SectionEndSym);
573 context.setGenDwarfSectionEndSym(SectionEndSym);
575 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
577 // This will be the length of the .debug_aranges section, first account for
578 // the size of each item in the header (see below where we emit these items).
579 int Length = 4 + 2 + 4 + 1 + 1;
581 // Figure the padding after the header before the table of address and size
582 // pairs who's values are PointerSize'ed.
583 const MCAsmInfo *asmInfo = context.getAsmInfo();
584 int AddrSize = asmInfo->getPointerSize();
585 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
586 if (Pad == 2 * AddrSize)
590 // Add the size of the pair of PointerSize'ed values for the address and size
591 // of the one default .text section we have in the table.
592 Length += 2 * AddrSize;
593 // And the pair of terminating zeros.
594 Length += 2 * AddrSize;
597 // Emit the header for this section.
598 // The 4 byte length not including the 4 byte value for the length.
599 MCOS->EmitIntValue(Length - 4, 4);
600 // The 2 byte version, which is 2.
601 MCOS->EmitIntValue(2, 2);
602 // The 4 byte offset to the compile unit in the .debug_info from the start
603 // of the .debug_info.
604 if (InfoSectionSymbol)
605 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
607 MCOS->EmitIntValue(0, 4);
608 // The 1 byte size of an address.
609 MCOS->EmitIntValue(AddrSize, 1);
610 // The 1 byte size of a segment descriptor, we use a value of zero.
611 MCOS->EmitIntValue(0, 1);
612 // Align the header with the padding if needed, before we put out the table.
613 for(int i = 0; i < Pad; i++)
614 MCOS->EmitIntValue(0, 1);
616 // Now emit the table of pairs of PointerSize'ed values for the section(s)
617 // address and size, in our case just the one default .text section.
618 const MCExpr *Addr = MCSymbolRefExpr::Create(
619 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
620 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
621 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
622 MCOS->EmitAbsValue(Addr, AddrSize);
623 MCOS->EmitAbsValue(Size, AddrSize);
625 // And finally the pair of terminating zeros.
626 MCOS->EmitIntValue(0, AddrSize);
627 MCOS->EmitIntValue(0, AddrSize);
630 // When generating dwarf for assembly source files this emits the data for
631 // .debug_info section which contains three parts. The header, the compile_unit
632 // DIE and a list of label DIEs.
633 static void EmitGenDwarfInfo(MCStreamer *MCOS,
634 const MCSymbol *AbbrevSectionSymbol,
635 const MCSymbol *LineSectionSymbol) {
636 MCContext &context = MCOS->getContext();
638 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
640 // Create a symbol at the start and end of this section used in here for the
641 // expression to calculate the length in the header.
642 MCSymbol *InfoStart = context.CreateTempSymbol();
643 MCOS->EmitLabel(InfoStart);
644 MCSymbol *InfoEnd = context.CreateTempSymbol();
646 // First part: the header.
648 // The 4 byte total length of the information for this compilation unit, not
649 // including these 4 bytes.
650 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
651 MCOS->EmitAbsValue(Length, 4);
653 // The 2 byte DWARF version, which is 2.
654 MCOS->EmitIntValue(2, 2);
656 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
657 // it is at the start of that section so this is zero.
658 if (AbbrevSectionSymbol) {
659 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
661 MCOS->EmitIntValue(0, 4);
664 const MCAsmInfo *asmInfo = context.getAsmInfo();
665 int AddrSize = asmInfo->getPointerSize();
666 // The 1 byte size of an address.
667 MCOS->EmitIntValue(AddrSize, 1);
669 // Second part: the compile_unit DIE.
671 // The DW_TAG_compile_unit DIE abbrev (1).
672 MCOS->EmitULEB128IntValue(1);
674 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
675 // which is at the start of that section so this is zero.
676 if (LineSectionSymbol) {
677 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
679 MCOS->EmitIntValue(0, 4);
682 // AT_low_pc, the first address of the default .text section.
683 const MCExpr *Start = MCSymbolRefExpr::Create(
684 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
685 MCOS->EmitAbsValue(Start, AddrSize);
687 // AT_high_pc, the last address of the default .text section.
688 const MCExpr *End = MCSymbolRefExpr::Create(
689 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
690 MCOS->EmitAbsValue(End, AddrSize);
692 // AT_name, the name of the source file. Reconstruct from the first directory
693 // and file table entries.
694 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
695 if (MCDwarfDirs.size() > 0) {
696 MCOS->EmitBytes(MCDwarfDirs[0]);
697 MCOS->EmitBytes("/");
699 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
700 MCOS->getContext().getMCDwarfFiles();
701 MCOS->EmitBytes(MCDwarfFiles[1].Name);
702 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
704 // AT_comp_dir, the working directory the assembly was done in.
705 if (!context.getCompilationDir().empty()) {
706 MCOS->EmitBytes(context.getCompilationDir());
707 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
710 // AT_APPLE_flags, the command line arguments of the assembler tool.
711 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
712 if (!DwarfDebugFlags.empty()){
713 MCOS->EmitBytes(DwarfDebugFlags);
714 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
717 // AT_producer, the version of the assembler tool.
718 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
719 if (!DwarfDebugProducer.empty()){
720 MCOS->EmitBytes(DwarfDebugProducer);
723 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
724 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
725 MCOS->EmitBytes(StringRef(")"));
727 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
729 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
730 // draft has no standard code for assembler.
731 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
733 // Third part: the list of label DIEs.
735 // Loop on saved info for dwarf labels and create the DIEs for them.
736 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
737 MCOS->getContext().getMCGenDwarfLabelEntries();
738 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
739 Entries.begin(), ie = Entries.end(); it != ie;
741 const MCGenDwarfLabelEntry *Entry = *it;
743 // The DW_TAG_label DIE abbrev (2).
744 MCOS->EmitULEB128IntValue(2);
746 // AT_name, of the label without any leading underbar.
747 MCOS->EmitBytes(Entry->getName());
748 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
750 // AT_decl_file, index into the file table.
751 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
753 // AT_decl_line, source line number.
754 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
756 // AT_low_pc, start address of the label.
757 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
758 MCSymbolRefExpr::VK_None, context);
759 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
761 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
762 MCOS->EmitIntValue(0, 1);
764 // The DW_TAG_unspecified_parameters DIE abbrev (3).
765 MCOS->EmitULEB128IntValue(3);
767 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
768 MCOS->EmitIntValue(0, 1);
770 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
771 // for the dwarf labels.
772 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
773 Entries.begin(), ie = Entries.end(); it != ie;
775 const MCGenDwarfLabelEntry *Entry = *it;
779 // Add the NULL DIE terminating the Compile Unit DIE's.
780 MCOS->EmitIntValue(0, 1);
782 // Now set the value of the symbol at the end of the info section.
783 MCOS->EmitLabel(InfoEnd);
787 // When generating dwarf for assembly source files this emits the Dwarf
790 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
791 // Create the dwarf sections in this order (.debug_line already created).
792 MCContext &context = MCOS->getContext();
793 const MCAsmInfo *AsmInfo = context.getAsmInfo();
794 bool CreateDwarfSectionSymbols =
795 AsmInfo->doesDwarfUseRelocationsAcrossSections();
796 if (!CreateDwarfSectionSymbols)
797 LineSectionSymbol = NULL;
798 MCSymbol *AbbrevSectionSymbol = NULL;
799 MCSymbol *InfoSectionSymbol = NULL;
800 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
801 if (CreateDwarfSectionSymbols) {
802 InfoSectionSymbol = context.CreateTempSymbol();
803 MCOS->EmitLabel(InfoSectionSymbol);
805 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
806 if (CreateDwarfSectionSymbols) {
807 AbbrevSectionSymbol = context.CreateTempSymbol();
808 MCOS->EmitLabel(AbbrevSectionSymbol);
810 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
812 // If there are no line table entries then do not emit any section contents.
813 if (!context.hasMCLineSections())
816 // Output the data for .debug_aranges section.
817 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
819 // Output the data for .debug_abbrev section.
820 EmitGenDwarfAbbrev(MCOS);
822 // Output the data for .debug_info section.
823 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
827 // When generating dwarf for assembly source files this is called when symbol
828 // for a label is created. If this symbol is not a temporary and is in the
829 // section that dwarf is being generated for, save the needed info to create
832 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
833 SourceMgr &SrcMgr, SMLoc &Loc) {
834 // We won't create dwarf labels for temporary symbols or symbols not in
836 if (Symbol->isTemporary())
838 MCContext &context = MCOS->getContext();
839 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
842 // The dwarf label's name does not have the symbol name's leading
844 StringRef Name = Symbol->getName();
845 if (Name.startswith("_"))
846 Name = Name.substr(1, Name.size()-1);
848 // Get the dwarf file number to be used for the dwarf label.
849 unsigned FileNumber = context.getGenDwarfFileNumber();
851 // Finding the line number is the expensive part which is why we just don't
852 // pass it in as for some symbols we won't create a dwarf label.
853 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
854 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
856 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
857 // values so that they don't have things like an ARM thumb bit from the
858 // original symbol. So when used they won't get a low bit set after
860 MCSymbol *Label = context.CreateTempSymbol();
861 MCOS->EmitLabel(Label);
863 // Create and entry for the info and add it to the other entries.
864 MCGenDwarfLabelEntry *Entry =
865 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
866 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
869 static int getDataAlignmentFactor(MCStreamer &streamer) {
870 MCContext &context = streamer.getContext();
871 const MCAsmInfo *asmInfo = context.getAsmInfo();
872 int size = asmInfo->getCalleeSaveStackSlotSize();
873 if (asmInfo->isStackGrowthDirectionUp())
879 static unsigned getSizeForEncoding(MCStreamer &streamer,
880 unsigned symbolEncoding) {
881 MCContext &context = streamer.getContext();
882 unsigned format = symbolEncoding & 0x0f;
884 default: llvm_unreachable("Unknown Encoding");
885 case dwarf::DW_EH_PE_absptr:
886 case dwarf::DW_EH_PE_signed:
887 return context.getAsmInfo()->getPointerSize();
888 case dwarf::DW_EH_PE_udata2:
889 case dwarf::DW_EH_PE_sdata2:
891 case dwarf::DW_EH_PE_udata4:
892 case dwarf::DW_EH_PE_sdata4:
894 case dwarf::DW_EH_PE_udata8:
895 case dwarf::DW_EH_PE_sdata8:
900 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
901 unsigned symbolEncoding, bool isEH,
902 const char *comment = 0) {
903 MCContext &context = streamer.getContext();
904 const MCAsmInfo *asmInfo = context.getAsmInfo();
905 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
908 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
909 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
910 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
911 streamer.EmitAbsValue(v, size);
913 streamer.EmitValue(v, size);
916 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
917 unsigned symbolEncoding) {
918 MCContext &context = streamer.getContext();
919 const MCAsmInfo *asmInfo = context.getAsmInfo();
920 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
923 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
924 streamer.EmitValue(v, size);
928 class FrameEmitterImpl {
933 const MCSymbol *SectionStart;
935 FrameEmitterImpl(bool usingCFI, bool isEH)
936 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
939 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
941 /// EmitCompactUnwind - Emit the unwind information in a compact way.
942 void EmitCompactUnwind(MCStreamer &streamer,
943 const MCDwarfFrameInfo &frame);
945 const MCSymbol &EmitCIE(MCStreamer &streamer,
946 const MCSymbol *personality,
947 unsigned personalityEncoding,
948 const MCSymbol *lsda,
950 unsigned lsdaEncoding,
952 MCSymbol *EmitFDE(MCStreamer &streamer,
953 const MCSymbol &cieStart,
954 const MCDwarfFrameInfo &frame);
955 void EmitCFIInstructions(MCStreamer &streamer,
956 ArrayRef<MCCFIInstruction> Instrs,
957 MCSymbol *BaseLabel);
958 void EmitCFIInstruction(MCStreamer &Streamer,
959 const MCCFIInstruction &Instr);
962 } // end anonymous namespace
964 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
966 if (Streamer.isVerboseAsm()) {
969 default: EncStr = "<unknown encoding>"; break;
970 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
971 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
972 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
973 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
974 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
975 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
976 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
977 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
978 EncStr = "pcrel udata4";
980 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
981 EncStr = "pcrel sdata4";
983 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
984 EncStr = "pcrel udata8";
986 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
987 EncStr = "screl sdata8";
989 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
990 EncStr = "indirect pcrel udata4";
992 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
993 EncStr = "indirect pcrel sdata4";
995 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
996 EncStr = "indirect pcrel udata8";
998 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
999 EncStr = "indirect pcrel sdata8";
1003 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
1006 Streamer.EmitIntValue(Encoding, 1);
1009 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
1010 const MCCFIInstruction &Instr) {
1011 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1012 bool VerboseAsm = Streamer.isVerboseAsm();
1014 switch (Instr.getOperation()) {
1015 case MCCFIInstruction::OpRegister: {
1016 unsigned Reg1 = Instr.getRegister();
1017 unsigned Reg2 = Instr.getRegister2();
1019 Streamer.AddComment("DW_CFA_register");
1020 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
1021 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
1023 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1024 Streamer.EmitULEB128IntValue(Reg1);
1025 Streamer.EmitULEB128IntValue(Reg2);
1028 case MCCFIInstruction::OpWindowSave: {
1029 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1032 case MCCFIInstruction::OpUndefined: {
1033 unsigned Reg = Instr.getRegister();
1035 Streamer.AddComment("DW_CFA_undefined");
1036 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1038 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1039 Streamer.EmitULEB128IntValue(Reg);
1042 case MCCFIInstruction::OpAdjustCfaOffset:
1043 case MCCFIInstruction::OpDefCfaOffset: {
1044 const bool IsRelative =
1045 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1048 Streamer.AddComment("DW_CFA_def_cfa_offset");
1049 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1052 CFAOffset += Instr.getOffset();
1054 CFAOffset = -Instr.getOffset();
1057 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1058 Streamer.EmitULEB128IntValue(CFAOffset);
1062 case MCCFIInstruction::OpDefCfa: {
1064 Streamer.AddComment("DW_CFA_def_cfa");
1065 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1068 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1069 Streamer.EmitULEB128IntValue(Instr.getRegister());
1071 CFAOffset = -Instr.getOffset();
1074 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1075 Streamer.EmitULEB128IntValue(CFAOffset);
1080 case MCCFIInstruction::OpDefCfaRegister: {
1082 Streamer.AddComment("DW_CFA_def_cfa_register");
1083 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1086 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1087 Streamer.EmitULEB128IntValue(Instr.getRegister());
1092 case MCCFIInstruction::OpOffset:
1093 case MCCFIInstruction::OpRelOffset: {
1094 const bool IsRelative =
1095 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1097 unsigned Reg = Instr.getRegister();
1098 int Offset = Instr.getOffset();
1100 Offset -= CFAOffset;
1101 Offset = Offset / dataAlignmentFactor;
1104 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1105 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1106 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1107 Streamer.EmitULEB128IntValue(Reg);
1108 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1109 Streamer.EmitSLEB128IntValue(Offset);
1110 } else if (Reg < 64) {
1111 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1113 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1114 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1115 Streamer.EmitULEB128IntValue(Offset);
1117 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1118 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1119 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1120 Streamer.EmitULEB128IntValue(Reg);
1121 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1122 Streamer.EmitULEB128IntValue(Offset);
1126 case MCCFIInstruction::OpRememberState:
1127 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1128 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1130 case MCCFIInstruction::OpRestoreState:
1131 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1132 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1134 case MCCFIInstruction::OpSameValue: {
1135 unsigned Reg = Instr.getRegister();
1136 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1137 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1138 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1139 Streamer.EmitULEB128IntValue(Reg);
1142 case MCCFIInstruction::OpRestore: {
1143 unsigned Reg = Instr.getRegister();
1145 Streamer.AddComment("DW_CFA_restore");
1146 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1148 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1151 case MCCFIInstruction::OpEscape:
1152 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1153 Streamer.EmitBytes(Instr.getValues());
1156 llvm_unreachable("Unhandled case in switch");
1159 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1161 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1162 ArrayRef<MCCFIInstruction> Instrs,
1163 MCSymbol *BaseLabel) {
1164 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1165 const MCCFIInstruction &Instr = Instrs[i];
1166 MCSymbol *Label = Instr.getLabel();
1167 // Throw out move if the label is invalid.
1168 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1170 // Advance row if new location.
1171 if (BaseLabel && Label) {
1172 MCSymbol *ThisSym = Label;
1173 if (ThisSym != BaseLabel) {
1174 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1175 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1176 BaseLabel = ThisSym;
1180 EmitCFIInstruction(streamer, Instr);
1184 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1185 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1186 const MCDwarfFrameInfo &Frame) {
1187 MCContext &Context = Streamer.getContext();
1188 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1189 bool VerboseAsm = Streamer.isVerboseAsm();
1191 // range-start range-length compact-unwind-enc personality-func lsda
1192 // _foo LfooEnd-_foo 0x00000023 0 0
1193 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1195 // .section __LD,__compact_unwind,regular,debug
1197 // # compact unwind for _foo
1199 // .set L1,LfooEnd-_foo
1205 // # compact unwind for _bar
1207 // .set L2,LbarEnd-_bar
1210 // .quad __gxx_personality
1211 // .quad except_tab1
1213 uint32_t Encoding = Frame.CompactUnwindEncoding;
1214 if (!Encoding) return;
1215 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1217 // The encoding needs to know we have an LSDA.
1218 if (!DwarfEHFrameOnly && Frame.Lsda)
1219 Encoding |= 0x40000000;
1222 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1223 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1224 if (VerboseAsm) Streamer.AddComment("Range Start");
1225 Streamer.EmitSymbolValue(Frame.Function, Size);
1228 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1230 if (VerboseAsm) Streamer.AddComment("Range Length");
1231 Streamer.EmitAbsValue(Range, 4);
1234 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1235 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1236 Twine::utohexstr(Encoding));
1237 Streamer.EmitIntValue(Encoding, Size);
1239 // Personality Function
1240 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1241 if (VerboseAsm) Streamer.AddComment("Personality Function");
1242 if (!DwarfEHFrameOnly && Frame.Personality)
1243 Streamer.EmitSymbolValue(Frame.Personality, Size);
1245 Streamer.EmitIntValue(0, Size); // No personality fn
1248 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1249 if (VerboseAsm) Streamer.AddComment("LSDA");
1250 if (!DwarfEHFrameOnly && Frame.Lsda)
1251 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1253 Streamer.EmitIntValue(0, Size); // No LSDA
1256 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1257 const MCSymbol *personality,
1258 unsigned personalityEncoding,
1259 const MCSymbol *lsda,
1261 unsigned lsdaEncoding,
1263 MCContext &context = streamer.getContext();
1264 const MCRegisterInfo *MRI = context.getRegisterInfo();
1265 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1266 bool verboseAsm = streamer.isVerboseAsm();
1268 MCSymbol *sectionStart;
1269 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1270 sectionStart = context.CreateTempSymbol();
1272 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1274 streamer.EmitLabel(sectionStart);
1277 MCSymbol *sectionEnd = context.CreateTempSymbol();
1280 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1282 if (verboseAsm) streamer.AddComment("CIE Length");
1283 streamer.EmitAbsValue(Length, 4);
1286 unsigned CIE_ID = IsEH ? 0 : -1;
1287 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1288 streamer.EmitIntValue(CIE_ID, 4);
1291 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1292 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1294 // Augmentation String
1295 SmallString<8> Augmentation;
1297 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1298 Augmentation += "z";
1300 Augmentation += "P";
1302 Augmentation += "L";
1303 Augmentation += "R";
1305 Augmentation += "S";
1306 streamer.EmitBytes(Augmentation.str());
1308 streamer.EmitIntValue(0, 1);
1310 // Code Alignment Factor
1311 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1312 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1314 // Data Alignment Factor
1315 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1316 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1318 // Return Address Register
1319 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1320 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1322 // Augmentation Data Length (optional)
1324 unsigned augmentationLength = 0;
1327 // Personality Encoding
1328 augmentationLength += 1;
1330 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1333 augmentationLength += 1;
1334 // Encoding of the FDE pointers
1335 augmentationLength += 1;
1337 if (verboseAsm) streamer.AddComment("Augmentation Size");
1338 streamer.EmitULEB128IntValue(augmentationLength);
1340 // Augmentation Data (optional)
1342 // Personality Encoding
1343 EmitEncodingByte(streamer, personalityEncoding,
1344 "Personality Encoding");
1346 if (verboseAsm) streamer.AddComment("Personality");
1347 EmitPersonality(streamer, *personality, personalityEncoding);
1351 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1353 // Encoding of the FDE pointers
1354 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1358 // Initial Instructions
1360 const MCAsmInfo *MAI = context.getAsmInfo();
1362 const std::vector<MCCFIInstruction> &Instructions =
1363 MAI->getInitialFrameState();
1364 EmitCFIInstructions(streamer, Instructions, NULL);
1368 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1370 streamer.EmitLabel(sectionEnd);
1371 return *sectionStart;
1374 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1375 const MCSymbol &cieStart,
1376 const MCDwarfFrameInfo &frame) {
1377 MCContext &context = streamer.getContext();
1378 MCSymbol *fdeStart = context.CreateTempSymbol();
1379 MCSymbol *fdeEnd = context.CreateTempSymbol();
1380 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1381 bool verboseAsm = streamer.isVerboseAsm();
1383 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1385 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1386 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1387 streamer.EmitLabel(EHSym);
1391 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1392 if (verboseAsm) streamer.AddComment("FDE Length");
1393 streamer.EmitAbsValue(Length, 4);
1395 streamer.EmitLabel(fdeStart);
1398 const MCAsmInfo *asmInfo = context.getAsmInfo();
1400 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1402 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1403 streamer.EmitAbsValue(offset, 4);
1404 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1405 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1407 streamer.EmitAbsValue(offset, 4);
1409 streamer.EmitSymbolValue(&cieStart, 4);
1413 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1414 : (unsigned)dwarf::DW_EH_PE_absptr;
1415 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1416 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1419 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1421 if (verboseAsm) streamer.AddComment("FDE address range");
1422 streamer.EmitAbsValue(Range, PCSize);
1425 // Augmentation Data Length
1426 unsigned augmentationLength = 0;
1429 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1431 if (verboseAsm) streamer.AddComment("Augmentation size");
1432 streamer.EmitULEB128IntValue(augmentationLength);
1434 // Augmentation Data
1436 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1437 "Language Specific Data Area");
1440 // Call Frame Instructions
1441 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1444 streamer.EmitValueToAlignment(PCSize);
1451 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1452 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1454 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1455 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1456 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1457 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1458 IsSimple(IsSimple_) {
1460 const MCSymbol* Personality;
1461 unsigned PersonalityEncoding;
1462 unsigned LsdaEncoding;
1470 struct DenseMapInfo<CIEKey> {
1471 static CIEKey getEmptyKey() {
1472 return CIEKey::getEmptyKey();
1474 static CIEKey getTombstoneKey() {
1475 return CIEKey::getTombstoneKey();
1477 static unsigned getHashValue(const CIEKey &Key) {
1478 return static_cast<unsigned>(hash_combine(Key.Personality,
1479 Key.PersonalityEncoding,
1484 static bool isEqual(const CIEKey &LHS,
1485 const CIEKey &RHS) {
1486 return LHS.Personality == RHS.Personality &&
1487 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1488 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1489 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1490 LHS.IsSimple == RHS.IsSimple;
1495 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1496 bool UsingCFI, bool IsEH) {
1497 Streamer.generateCompactUnwindEncodings(MAB);
1499 MCContext &Context = Streamer.getContext();
1500 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1501 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1502 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1504 // Emit the compact unwind info if available.
1505 if (IsEH && MOFI->getCompactUnwindSection()) {
1506 bool SectionEmitted = false;
1507 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1508 const MCDwarfFrameInfo &Frame = FrameArray[i];
1509 if (Frame.CompactUnwindEncoding == 0) continue;
1510 if (!SectionEmitted) {
1511 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1512 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1513 SectionEmitted = true;
1515 Emitter.EmitCompactUnwind(Streamer, Frame);
1519 const MCSection &Section =
1520 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1521 *MOFI->getDwarfFrameSection();
1522 Streamer.SwitchSection(&Section);
1523 MCSymbol *SectionStart = Context.CreateTempSymbol();
1524 Streamer.EmitLabel(SectionStart);
1525 Emitter.setSectionStart(SectionStart);
1527 MCSymbol *FDEEnd = NULL;
1528 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1530 const MCSymbol *DummyDebugKey = NULL;
1531 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1532 const MCDwarfFrameInfo &Frame = FrameArray[i];
1533 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1534 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1535 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1537 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1538 Frame.PersonalityEncoding, Frame.Lsda,
1539 Frame.IsSignalFrame,
1543 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1546 Streamer.EmitLabel(FDEEnd);
1549 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1551 Streamer.EmitLabel(FDEEnd);
1554 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1555 uint64_t AddrDelta) {
1556 MCContext &Context = Streamer.getContext();
1557 SmallString<256> Tmp;
1558 raw_svector_ostream OS(Tmp);
1559 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1560 Streamer.EmitBytes(OS.str());
1563 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1566 // Scale the address delta by the minimum instruction length.
1567 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1569 if (AddrDelta == 0) {
1570 } else if (isUIntN(6, AddrDelta)) {
1571 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1573 } else if (isUInt<8>(AddrDelta)) {
1574 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1575 OS << uint8_t(AddrDelta);
1576 } else if (isUInt<16>(AddrDelta)) {
1577 // FIXME: check what is the correct behavior on a big endian machine.
1578 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1579 OS << uint8_t( AddrDelta & 0xff);
1580 OS << uint8_t((AddrDelta >> 8) & 0xff);
1582 // FIXME: check what is the correct behavior on a big endian machine.
1583 assert(isUInt<32>(AddrDelta));
1584 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1585 OS << uint8_t( AddrDelta & 0xff);
1586 OS << uint8_t((AddrDelta >> 8) & 0xff);
1587 OS << uint8_t((AddrDelta >> 16) & 0xff);
1588 OS << uint8_t((AddrDelta >> 24) & 0xff);