1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCDwarf.h"
11 #include "llvm/ADT/Hashing.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectFileInfo.h"
20 #include "llvm/MC/MCRegisterInfo.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
31 // Given a special op, return the address skip amount (in units of
32 // DWARF2_LINE_MIN_INSN_LENGTH.
33 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
35 // The maximum address skip amount that can be encoded with a special op.
36 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
38 // First special line opcode - leave room for the standard opcodes.
39 // Note: If you want to change this, you'll have to update the
40 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
41 #define DWARF2_LINE_OPCODE_BASE 13
43 // Minimum line offset in a special line info. opcode. This value
44 // was chosen to give a reasonable range of values.
45 #define DWARF2_LINE_BASE -5
47 // Range of line offsets in a special line info. opcode.
48 #define DWARF2_LINE_RANGE 14
50 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
51 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
52 if (MinInsnLength == 1)
54 if (AddrDelta % MinInsnLength != 0) {
55 // TODO: report this error, but really only once.
58 return AddrDelta / MinInsnLength;
62 // This is called when an instruction is assembled into the specified section
63 // and if there is information from the last .loc directive that has yet to have
64 // a line entry made for it is made.
66 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
67 if (!MCOS->getContext().getDwarfLocSeen())
70 // Create a symbol at in the current section for use in the line entry.
71 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
72 // Set the value of the symbol to use for the MCLineEntry.
73 MCOS->EmitLabel(LineSym);
75 // Get the current .loc info saved in the context.
76 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
78 // Create a (local) line entry with the symbol and the current .loc info.
79 MCLineEntry LineEntry(LineSym, DwarfLoc);
81 // clear DwarfLocSeen saying the current .loc info is now used.
82 MCOS->getContext().ClearDwarfLocSeen();
84 // Add the line entry to this section's entries.
86 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
88 .addLineEntry(LineEntry, Section);
92 // This helper routine returns an expression of End - Start + IntVal .
94 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
95 const MCSymbol &Start,
98 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
100 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
102 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
104 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
106 MCConstantExpr::Create(IntVal, MCOS.getContext());
108 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
113 // This emits the Dwarf line table for the specified section from the entries
114 // in the LineSection.
117 EmitDwarfLineTable(MCStreamer *MCOS, const MCSection *Section,
118 const MCLineSection::MCLineEntryCollection &LineEntries) {
119 unsigned FileNum = 1;
120 unsigned LastLine = 1;
122 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
124 unsigned Discriminator = 0;
125 MCSymbol *LastLabel = NULL;
127 // Loop through each MCLineEntry and encode the dwarf line number table.
128 for (auto it = LineEntries.begin(),
129 ie = LineEntries.end();
132 if (FileNum != it->getFileNum()) {
133 FileNum = it->getFileNum();
134 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
135 MCOS->EmitULEB128IntValue(FileNum);
137 if (Column != it->getColumn()) {
138 Column = it->getColumn();
139 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
140 MCOS->EmitULEB128IntValue(Column);
142 if (Discriminator != it->getDiscriminator()) {
143 Discriminator = it->getDiscriminator();
144 unsigned Size = getULEB128Size(Discriminator);
145 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
146 MCOS->EmitULEB128IntValue(Size + 1);
147 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
148 MCOS->EmitULEB128IntValue(Discriminator);
150 if (Isa != it->getIsa()) {
152 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
153 MCOS->EmitULEB128IntValue(Isa);
155 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
156 Flags = it->getFlags();
157 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
159 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
160 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
161 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
162 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
163 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
164 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
166 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
167 MCSymbol *Label = it->getLabel();
169 // At this point we want to emit/create the sequence to encode the delta in
170 // line numbers and the increment of the address from the previous Label
171 // and the current Label.
172 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
173 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
174 asmInfo->getPointerSize());
176 LastLine = it->getLine();
180 // Emit a DW_LNE_end_sequence for the end of the section.
181 // Using the pointer Section create a temporary label at the end of the
182 // section and use that and the LastLabel to compute the address delta
183 // and use INT64_MAX as the line delta which is the signal that this is
184 // actually a DW_LNE_end_sequence.
186 // Switch to the section to be able to create a symbol at its end.
187 // TODO: keep track of the last subsection so that this symbol appears in the
189 MCOS->SwitchSection(Section);
191 MCContext &context = MCOS->getContext();
192 // Create a symbol at the end of the section.
193 MCSymbol *SectionEnd = context.CreateTempSymbol();
194 // Set the value of the symbol, as we are at the end of the section.
195 MCOS->EmitLabel(SectionEnd);
197 // Switch back the dwarf line section.
198 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
200 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
201 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
202 asmInfo->getPointerSize());
206 // This emits the Dwarf file and the line tables.
208 void MCDwarfLineTable::Emit(MCStreamer *MCOS) {
209 MCContext &context = MCOS->getContext();
211 auto &LineTables = context.getMCDwarfLineTables();
213 // Bail out early so we don't switch to the debug_line section needlessly and
214 // in doing so create an unnecessary (if empty) section.
215 if (LineTables.empty())
218 // Switch to the section where the table will be emitted into.
219 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
221 // Handle the rest of the Compile Units.
222 for (const auto &CUIDTablePair : LineTables)
223 CUIDTablePair.second.EmitCU(MCOS);
226 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
227 MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
230 std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
231 static const char StandardOpcodeLengths[] = {
232 0, // length of DW_LNS_copy
233 1, // length of DW_LNS_advance_pc
234 1, // length of DW_LNS_advance_line
235 1, // length of DW_LNS_set_file
236 1, // length of DW_LNS_set_column
237 0, // length of DW_LNS_negate_stmt
238 0, // length of DW_LNS_set_basic_block
239 0, // length of DW_LNS_const_add_pc
240 1, // length of DW_LNS_fixed_advance_pc
241 0, // length of DW_LNS_set_prologue_end
242 0, // length of DW_LNS_set_epilogue_begin
245 assert(array_lengthof(StandardOpcodeLengths) == (DWARF2_LINE_OPCODE_BASE - 1));
246 return Emit(MCOS, StandardOpcodeLengths);
249 std::pair<MCSymbol *, MCSymbol *>
250 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
251 ArrayRef<char> StandardOpcodeLengths) const {
253 MCContext &context = MCOS->getContext();
255 // Create a symbol at the beginning of the line table.
256 MCSymbol *LineStartSym = Label;
258 LineStartSym = context.CreateTempSymbol();
259 // Set the value of the symbol, as we are at the start of the line table.
260 MCOS->EmitLabel(LineStartSym);
262 // Create a symbol for the end of the section (to be set when we get there).
263 MCSymbol *LineEndSym = context.CreateTempSymbol();
265 // The first 4 bytes is the total length of the information for this
266 // compilation unit (not including these 4 bytes for the length).
267 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
270 // Next 2 bytes is the Version, which is Dwarf 2.
271 MCOS->EmitIntValue(2, 2);
273 // Create a symbol for the end of the prologue (to be set when we get there).
274 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
276 // Length of the prologue, is the next 4 bytes. Which is the start of the
277 // section to the end of the prologue. Not including the 4 bytes for the
278 // total length, the 2 bytes for the version, and these 4 bytes for the
279 // length of the prologue.
280 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
283 // Parameters of the state machine, are next.
284 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
285 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
286 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
287 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
288 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
290 // Standard opcode lengths
291 for (char Length : StandardOpcodeLengths)
292 MCOS->EmitIntValue(Length, 1);
294 // Put out the directory and file tables.
296 // First the directory table.
297 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
298 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
299 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
301 MCOS->EmitIntValue(0, 1); // Terminate the directory list
303 // Second the file table.
304 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
305 assert(!MCDwarfFiles[i].Name.empty());
306 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
307 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
309 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
310 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
311 MCOS->EmitIntValue(0, 1); // filesize (always 0)
313 MCOS->EmitIntValue(0, 1); // Terminate the file list
315 // This is the end of the prologue, so set the value of the symbol at the
316 // end of the prologue (that was used in a previous expression).
317 MCOS->EmitLabel(ProEndSym);
319 return std::make_pair(LineStartSym, LineEndSym);
322 void MCDwarfLineTable::EmitCU(MCStreamer *MCOS) const {
323 MCSymbol *LineEndSym = Header.Emit(MCOS).second;
325 // Put out the line tables.
326 for (const auto &LineSec : MCLineSections.getMCLineEntries())
327 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
329 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
330 MCLineSections.getMCLineEntries().empty()) {
331 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
333 // total_length >= prologue_length + 10
334 // We are 4 bytes short, since we have total_length = 51 and
335 // prologue_length = 45
337 // The regular end_sequence should be sufficient.
338 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
341 // This is the end of the section, so set the value of the symbol at the end
342 // of this section (that was used in a previous expression).
343 MCOS->EmitLabel(LineEndSym);
346 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
347 unsigned FileNumber) {
348 return Header.getFile(Directory, FileName, FileNumber);
351 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
353 unsigned FileNumber) {
354 if (Directory == CompilationDir)
356 if (FileName.empty()) {
357 FileName = "<stdin>";
360 assert(!FileName.empty());
361 if (FileNumber == 0) {
362 FileNumber = SourceIdMap.size() + 1;
363 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
364 "Don't mix autonumbered and explicit numbered line table usage");
365 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(
366 (Directory + Twine('\0') + FileName).str(), FileNumber);
367 if (Ent.getValue() != FileNumber)
368 return Ent.getValue();
370 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
371 MCDwarfFiles.resize(FileNumber + 1);
373 // Get the new MCDwarfFile slot for this FileNumber.
374 MCDwarfFile &File = MCDwarfFiles[FileNumber];
376 // It is an error to use see the same number more than once.
377 if (!File.Name.empty())
380 if (Directory.empty()) {
381 // Separate the directory part from the basename of the FileName.
382 StringRef tFileName = sys::path::filename(FileName);
383 if (!tFileName.empty()) {
384 Directory = sys::path::parent_path(FileName);
385 if (!Directory.empty())
386 FileName = tFileName;
390 // Find or make an entry in the MCDwarfDirs vector for this Directory.
391 // Capture directory name.
393 if (Directory.empty()) {
394 // For FileNames with no directories a DirIndex of 0 is used.
398 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
399 if (Directory == MCDwarfDirs[DirIndex])
402 if (DirIndex >= MCDwarfDirs.size())
403 MCDwarfDirs.push_back(Directory);
404 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
405 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
406 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
407 // are stored at MCDwarfFiles[FileNumber].Name .
411 File.Name = FileName;
412 File.DirIndex = DirIndex;
414 // return the allocated FileNumber.
418 /// Utility function to emit the encoding to a streamer.
419 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
420 uint64_t AddrDelta) {
421 MCContext &Context = MCOS->getContext();
422 SmallString<256> Tmp;
423 raw_svector_ostream OS(Tmp);
424 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
425 MCOS->EmitBytes(OS.str());
428 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
429 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
430 uint64_t AddrDelta, raw_ostream &OS) {
431 uint64_t Temp, Opcode;
432 bool NeedCopy = false;
434 // Scale the address delta by the minimum instruction length.
435 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
437 // A LineDelta of INT64_MAX is a signal that this is actually a
438 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
439 // end_sequence to emit the matrix entry.
440 if (LineDelta == INT64_MAX) {
441 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
442 OS << char(dwarf::DW_LNS_const_add_pc);
444 OS << char(dwarf::DW_LNS_advance_pc);
445 encodeULEB128(AddrDelta, OS);
447 OS << char(dwarf::DW_LNS_extended_op);
449 OS << char(dwarf::DW_LNE_end_sequence);
453 // Bias the line delta by the base.
454 Temp = LineDelta - DWARF2_LINE_BASE;
456 // If the line increment is out of range of a special opcode, we must encode
457 // it with DW_LNS_advance_line.
458 if (Temp >= DWARF2_LINE_RANGE) {
459 OS << char(dwarf::DW_LNS_advance_line);
460 encodeSLEB128(LineDelta, OS);
463 Temp = 0 - DWARF2_LINE_BASE;
467 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
468 if (LineDelta == 0 && AddrDelta == 0) {
469 OS << char(dwarf::DW_LNS_copy);
473 // Bias the opcode by the special opcode base.
474 Temp += DWARF2_LINE_OPCODE_BASE;
476 // Avoid overflow when addr_delta is large.
477 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
478 // Try using a special opcode.
479 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
485 // Try using DW_LNS_const_add_pc followed by special op.
486 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
488 OS << char(dwarf::DW_LNS_const_add_pc);
494 // Otherwise use DW_LNS_advance_pc.
495 OS << char(dwarf::DW_LNS_advance_pc);
496 encodeULEB128(AddrDelta, OS);
499 OS << char(dwarf::DW_LNS_copy);
504 // Utility function to write a tuple for .debug_abbrev.
505 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
506 MCOS->EmitULEB128IntValue(Name);
507 MCOS->EmitULEB128IntValue(Form);
510 // When generating dwarf for assembly source files this emits
511 // the data for .debug_abbrev section which contains three DIEs.
512 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
513 MCContext &context = MCOS->getContext();
514 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
516 // DW_TAG_compile_unit DIE abbrev (1).
517 MCOS->EmitULEB128IntValue(1);
518 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
519 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
520 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
521 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
522 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
523 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
524 if (!context.getCompilationDir().empty())
525 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
526 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
527 if (!DwarfDebugFlags.empty())
528 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
529 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
530 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
531 EmitAbbrev(MCOS, 0, 0);
533 // DW_TAG_label DIE abbrev (2).
534 MCOS->EmitULEB128IntValue(2);
535 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
536 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
537 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
538 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
539 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
540 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
541 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
542 EmitAbbrev(MCOS, 0, 0);
544 // DW_TAG_unspecified_parameters DIE abbrev (3).
545 MCOS->EmitULEB128IntValue(3);
546 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
547 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
548 EmitAbbrev(MCOS, 0, 0);
550 // Terminate the abbreviations for this compilation unit.
551 MCOS->EmitIntValue(0, 1);
554 // When generating dwarf for assembly source files this emits the data for
555 // .debug_aranges section. Which contains a header and a table of pairs of
556 // PointerSize'ed values for the address and size of section(s) with line table
557 // entries (just the default .text in our case) and a terminating pair of zeros.
558 static void EmitGenDwarfAranges(MCStreamer *MCOS,
559 const MCSymbol *InfoSectionSymbol) {
560 MCContext &context = MCOS->getContext();
562 // Create a symbol at the end of the section that we are creating the dwarf
563 // debugging info to use later in here as part of the expression to calculate
564 // the size of the section for the table.
565 MCOS->SwitchSection(context.getGenDwarfSection());
566 MCSymbol *SectionEndSym = context.CreateTempSymbol();
567 MCOS->EmitLabel(SectionEndSym);
568 context.setGenDwarfSectionEndSym(SectionEndSym);
570 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
572 // This will be the length of the .debug_aranges section, first account for
573 // the size of each item in the header (see below where we emit these items).
574 int Length = 4 + 2 + 4 + 1 + 1;
576 // Figure the padding after the header before the table of address and size
577 // pairs who's values are PointerSize'ed.
578 const MCAsmInfo *asmInfo = context.getAsmInfo();
579 int AddrSize = asmInfo->getPointerSize();
580 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
581 if (Pad == 2 * AddrSize)
585 // Add the size of the pair of PointerSize'ed values for the address and size
586 // of the one default .text section we have in the table.
587 Length += 2 * AddrSize;
588 // And the pair of terminating zeros.
589 Length += 2 * AddrSize;
592 // Emit the header for this section.
593 // The 4 byte length not including the 4 byte value for the length.
594 MCOS->EmitIntValue(Length - 4, 4);
595 // The 2 byte version, which is 2.
596 MCOS->EmitIntValue(2, 2);
597 // The 4 byte offset to the compile unit in the .debug_info from the start
598 // of the .debug_info.
599 if (InfoSectionSymbol)
600 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
602 MCOS->EmitIntValue(0, 4);
603 // The 1 byte size of an address.
604 MCOS->EmitIntValue(AddrSize, 1);
605 // The 1 byte size of a segment descriptor, we use a value of zero.
606 MCOS->EmitIntValue(0, 1);
607 // Align the header with the padding if needed, before we put out the table.
608 for(int i = 0; i < Pad; i++)
609 MCOS->EmitIntValue(0, 1);
611 // Now emit the table of pairs of PointerSize'ed values for the section(s)
612 // address and size, in our case just the one default .text section.
613 const MCExpr *Addr = MCSymbolRefExpr::Create(
614 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
615 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
616 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
617 MCOS->EmitValue(Addr, AddrSize);
618 MCOS->EmitAbsValue(Size, AddrSize);
620 // And finally the pair of terminating zeros.
621 MCOS->EmitIntValue(0, AddrSize);
622 MCOS->EmitIntValue(0, AddrSize);
625 // When generating dwarf for assembly source files this emits the data for
626 // .debug_info section which contains three parts. The header, the compile_unit
627 // DIE and a list of label DIEs.
628 static void EmitGenDwarfInfo(MCStreamer *MCOS,
629 const MCSymbol *AbbrevSectionSymbol,
630 const MCSymbol *LineSectionSymbol) {
631 MCContext &context = MCOS->getContext();
633 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
635 // Create a symbol at the start and end of this section used in here for the
636 // expression to calculate the length in the header.
637 MCSymbol *InfoStart = context.CreateTempSymbol();
638 MCOS->EmitLabel(InfoStart);
639 MCSymbol *InfoEnd = context.CreateTempSymbol();
641 // First part: the header.
643 // The 4 byte total length of the information for this compilation unit, not
644 // including these 4 bytes.
645 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
646 MCOS->EmitAbsValue(Length, 4);
648 // The 2 byte DWARF version, which is 2.
649 MCOS->EmitIntValue(2, 2);
651 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
652 // it is at the start of that section so this is zero.
653 if (AbbrevSectionSymbol) {
654 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
656 MCOS->EmitIntValue(0, 4);
659 const MCAsmInfo *asmInfo = context.getAsmInfo();
660 int AddrSize = asmInfo->getPointerSize();
661 // The 1 byte size of an address.
662 MCOS->EmitIntValue(AddrSize, 1);
664 // Second part: the compile_unit DIE.
666 // The DW_TAG_compile_unit DIE abbrev (1).
667 MCOS->EmitULEB128IntValue(1);
669 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
670 // which is at the start of that section so this is zero.
671 if (LineSectionSymbol) {
672 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
674 MCOS->EmitIntValue(0, 4);
677 // AT_low_pc, the first address of the default .text section.
678 const MCExpr *Start = MCSymbolRefExpr::Create(
679 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
680 MCOS->EmitValue(Start, AddrSize);
682 // AT_high_pc, the last address of the default .text section.
683 const MCExpr *End = MCSymbolRefExpr::Create(
684 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
685 MCOS->EmitValue(End, AddrSize);
687 // AT_name, the name of the source file. Reconstruct from the first directory
688 // and file table entries.
689 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
690 if (MCDwarfDirs.size() > 0) {
691 MCOS->EmitBytes(MCDwarfDirs[0]);
692 MCOS->EmitBytes("/");
694 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
695 MCOS->getContext().getMCDwarfFiles();
696 MCOS->EmitBytes(MCDwarfFiles[1].Name);
697 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
699 // AT_comp_dir, the working directory the assembly was done in.
700 if (!context.getCompilationDir().empty()) {
701 MCOS->EmitBytes(context.getCompilationDir());
702 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
705 // AT_APPLE_flags, the command line arguments of the assembler tool.
706 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
707 if (!DwarfDebugFlags.empty()){
708 MCOS->EmitBytes(DwarfDebugFlags);
709 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
712 // AT_producer, the version of the assembler tool.
713 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
714 if (!DwarfDebugProducer.empty()){
715 MCOS->EmitBytes(DwarfDebugProducer);
718 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
719 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
720 MCOS->EmitBytes(StringRef(")"));
722 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
724 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
725 // draft has no standard code for assembler.
726 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
728 // Third part: the list of label DIEs.
730 // Loop on saved info for dwarf labels and create the DIEs for them.
731 const std::vector<MCGenDwarfLabelEntry> &Entries =
732 MCOS->getContext().getMCGenDwarfLabelEntries();
733 for (const auto &Entry : Entries) {
734 // The DW_TAG_label DIE abbrev (2).
735 MCOS->EmitULEB128IntValue(2);
737 // AT_name, of the label without any leading underbar.
738 MCOS->EmitBytes(Entry.getName());
739 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
741 // AT_decl_file, index into the file table.
742 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
744 // AT_decl_line, source line number.
745 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
747 // AT_low_pc, start address of the label.
748 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry.getLabel(),
749 MCSymbolRefExpr::VK_None, context);
750 MCOS->EmitValue(AT_low_pc, AddrSize);
752 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
753 MCOS->EmitIntValue(0, 1);
755 // The DW_TAG_unspecified_parameters DIE abbrev (3).
756 MCOS->EmitULEB128IntValue(3);
758 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
759 MCOS->EmitIntValue(0, 1);
762 // Add the NULL DIE terminating the Compile Unit DIE's.
763 MCOS->EmitIntValue(0, 1);
765 // Now set the value of the symbol at the end of the info section.
766 MCOS->EmitLabel(InfoEnd);
770 // When generating dwarf for assembly source files this emits the Dwarf
773 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
774 // Create the dwarf sections in this order (.debug_line already created).
775 MCContext &context = MCOS->getContext();
776 const MCAsmInfo *AsmInfo = context.getAsmInfo();
777 bool CreateDwarfSectionSymbols =
778 AsmInfo->doesDwarfUseRelocationsAcrossSections();
779 MCSymbol *LineSectionSymbol = nullptr;
780 if (CreateDwarfSectionSymbols)
781 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
782 MCSymbol *AbbrevSectionSymbol = NULL;
783 MCSymbol *InfoSectionSymbol = NULL;
784 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
785 if (CreateDwarfSectionSymbols) {
786 InfoSectionSymbol = context.CreateTempSymbol();
787 MCOS->EmitLabel(InfoSectionSymbol);
789 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
790 if (CreateDwarfSectionSymbols) {
791 AbbrevSectionSymbol = context.CreateTempSymbol();
792 MCOS->EmitLabel(AbbrevSectionSymbol);
794 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
796 // If there are no line table entries then do not emit any section contents.
797 if (!context.hasMCLineSections())
800 // Output the data for .debug_aranges section.
801 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
803 // Output the data for .debug_abbrev section.
804 EmitGenDwarfAbbrev(MCOS);
806 // Output the data for .debug_info section.
807 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
811 // When generating dwarf for assembly source files this is called when symbol
812 // for a label is created. If this symbol is not a temporary and is in the
813 // section that dwarf is being generated for, save the needed info to create
816 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
817 SourceMgr &SrcMgr, SMLoc &Loc) {
818 // We won't create dwarf labels for temporary symbols or symbols not in
820 if (Symbol->isTemporary())
822 MCContext &context = MCOS->getContext();
823 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
826 // The dwarf label's name does not have the symbol name's leading
828 StringRef Name = Symbol->getName();
829 if (Name.startswith("_"))
830 Name = Name.substr(1, Name.size()-1);
832 // Get the dwarf file number to be used for the dwarf label.
833 unsigned FileNumber = context.getGenDwarfFileNumber();
835 // Finding the line number is the expensive part which is why we just don't
836 // pass it in as for some symbols we won't create a dwarf label.
837 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
838 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
840 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
841 // values so that they don't have things like an ARM thumb bit from the
842 // original symbol. So when used they won't get a low bit set after
844 MCSymbol *Label = context.CreateTempSymbol();
845 MCOS->EmitLabel(Label);
847 // Create and entry for the info and add it to the other entries.
848 MCOS->getContext().addMCGenDwarfLabelEntry(
849 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
852 static int getDataAlignmentFactor(MCStreamer &streamer) {
853 MCContext &context = streamer.getContext();
854 const MCAsmInfo *asmInfo = context.getAsmInfo();
855 int size = asmInfo->getCalleeSaveStackSlotSize();
856 if (asmInfo->isStackGrowthDirectionUp())
862 static unsigned getSizeForEncoding(MCStreamer &streamer,
863 unsigned symbolEncoding) {
864 MCContext &context = streamer.getContext();
865 unsigned format = symbolEncoding & 0x0f;
867 default: llvm_unreachable("Unknown Encoding");
868 case dwarf::DW_EH_PE_absptr:
869 case dwarf::DW_EH_PE_signed:
870 return context.getAsmInfo()->getPointerSize();
871 case dwarf::DW_EH_PE_udata2:
872 case dwarf::DW_EH_PE_sdata2:
874 case dwarf::DW_EH_PE_udata4:
875 case dwarf::DW_EH_PE_sdata4:
877 case dwarf::DW_EH_PE_udata8:
878 case dwarf::DW_EH_PE_sdata8:
883 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
884 unsigned symbolEncoding, bool isEH,
885 const char *comment = 0) {
886 MCContext &context = streamer.getContext();
887 const MCAsmInfo *asmInfo = context.getAsmInfo();
888 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
891 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
892 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
893 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
894 streamer.EmitAbsValue(v, size);
896 streamer.EmitValue(v, size);
899 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
900 unsigned symbolEncoding) {
901 MCContext &context = streamer.getContext();
902 const MCAsmInfo *asmInfo = context.getAsmInfo();
903 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
906 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
907 streamer.EmitValue(v, size);
911 class FrameEmitterImpl {
916 const MCSymbol *SectionStart;
918 FrameEmitterImpl(bool usingCFI, bool isEH)
919 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
922 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
924 /// EmitCompactUnwind - Emit the unwind information in a compact way.
925 void EmitCompactUnwind(MCStreamer &streamer,
926 const MCDwarfFrameInfo &frame);
928 const MCSymbol &EmitCIE(MCStreamer &streamer,
929 const MCSymbol *personality,
930 unsigned personalityEncoding,
931 const MCSymbol *lsda,
933 unsigned lsdaEncoding,
935 MCSymbol *EmitFDE(MCStreamer &streamer,
936 const MCSymbol &cieStart,
937 const MCDwarfFrameInfo &frame);
938 void EmitCFIInstructions(MCStreamer &streamer,
939 ArrayRef<MCCFIInstruction> Instrs,
940 MCSymbol *BaseLabel);
941 void EmitCFIInstruction(MCStreamer &Streamer,
942 const MCCFIInstruction &Instr);
945 } // end anonymous namespace
947 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
949 if (Streamer.isVerboseAsm()) {
952 default: EncStr = "<unknown encoding>"; break;
953 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
954 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
955 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
956 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
957 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
958 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
959 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
960 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
961 EncStr = "pcrel udata4";
963 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
964 EncStr = "pcrel sdata4";
966 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
967 EncStr = "pcrel udata8";
969 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
970 EncStr = "screl sdata8";
972 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
973 EncStr = "indirect pcrel udata4";
975 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
976 EncStr = "indirect pcrel sdata4";
978 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
979 EncStr = "indirect pcrel udata8";
981 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
982 EncStr = "indirect pcrel sdata8";
986 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
989 Streamer.EmitIntValue(Encoding, 1);
992 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
993 const MCCFIInstruction &Instr) {
994 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
995 bool VerboseAsm = Streamer.isVerboseAsm();
997 switch (Instr.getOperation()) {
998 case MCCFIInstruction::OpRegister: {
999 unsigned Reg1 = Instr.getRegister();
1000 unsigned Reg2 = Instr.getRegister2();
1002 Streamer.AddComment("DW_CFA_register");
1003 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
1004 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
1006 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1007 Streamer.EmitULEB128IntValue(Reg1);
1008 Streamer.EmitULEB128IntValue(Reg2);
1011 case MCCFIInstruction::OpWindowSave: {
1012 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1015 case MCCFIInstruction::OpUndefined: {
1016 unsigned Reg = Instr.getRegister();
1018 Streamer.AddComment("DW_CFA_undefined");
1019 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1021 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1022 Streamer.EmitULEB128IntValue(Reg);
1025 case MCCFIInstruction::OpAdjustCfaOffset:
1026 case MCCFIInstruction::OpDefCfaOffset: {
1027 const bool IsRelative =
1028 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1031 Streamer.AddComment("DW_CFA_def_cfa_offset");
1032 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1035 CFAOffset += Instr.getOffset();
1037 CFAOffset = -Instr.getOffset();
1040 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1041 Streamer.EmitULEB128IntValue(CFAOffset);
1045 case MCCFIInstruction::OpDefCfa: {
1047 Streamer.AddComment("DW_CFA_def_cfa");
1048 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1051 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1052 Streamer.EmitULEB128IntValue(Instr.getRegister());
1054 CFAOffset = -Instr.getOffset();
1057 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1058 Streamer.EmitULEB128IntValue(CFAOffset);
1063 case MCCFIInstruction::OpDefCfaRegister: {
1065 Streamer.AddComment("DW_CFA_def_cfa_register");
1066 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1069 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1070 Streamer.EmitULEB128IntValue(Instr.getRegister());
1075 case MCCFIInstruction::OpOffset:
1076 case MCCFIInstruction::OpRelOffset: {
1077 const bool IsRelative =
1078 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1080 unsigned Reg = Instr.getRegister();
1081 int Offset = Instr.getOffset();
1083 Offset -= CFAOffset;
1084 Offset = Offset / dataAlignmentFactor;
1087 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1088 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1089 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1090 Streamer.EmitULEB128IntValue(Reg);
1091 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1092 Streamer.EmitSLEB128IntValue(Offset);
1093 } else if (Reg < 64) {
1094 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1096 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1097 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1098 Streamer.EmitULEB128IntValue(Offset);
1100 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1101 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1102 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1103 Streamer.EmitULEB128IntValue(Reg);
1104 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1105 Streamer.EmitULEB128IntValue(Offset);
1109 case MCCFIInstruction::OpRememberState:
1110 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1111 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1113 case MCCFIInstruction::OpRestoreState:
1114 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1115 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1117 case MCCFIInstruction::OpSameValue: {
1118 unsigned Reg = Instr.getRegister();
1119 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1120 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1121 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1122 Streamer.EmitULEB128IntValue(Reg);
1125 case MCCFIInstruction::OpRestore: {
1126 unsigned Reg = Instr.getRegister();
1128 Streamer.AddComment("DW_CFA_restore");
1129 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1131 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1134 case MCCFIInstruction::OpEscape:
1135 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1136 Streamer.EmitBytes(Instr.getValues());
1139 llvm_unreachable("Unhandled case in switch");
1142 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1144 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1145 ArrayRef<MCCFIInstruction> Instrs,
1146 MCSymbol *BaseLabel) {
1147 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1148 const MCCFIInstruction &Instr = Instrs[i];
1149 MCSymbol *Label = Instr.getLabel();
1150 // Throw out move if the label is invalid.
1151 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1153 // Advance row if new location.
1154 if (BaseLabel && Label) {
1155 MCSymbol *ThisSym = Label;
1156 if (ThisSym != BaseLabel) {
1157 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1158 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1159 BaseLabel = ThisSym;
1163 EmitCFIInstruction(streamer, Instr);
1167 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1168 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1169 const MCDwarfFrameInfo &Frame) {
1170 MCContext &Context = Streamer.getContext();
1171 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1172 bool VerboseAsm = Streamer.isVerboseAsm();
1174 // range-start range-length compact-unwind-enc personality-func lsda
1175 // _foo LfooEnd-_foo 0x00000023 0 0
1176 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1178 // .section __LD,__compact_unwind,regular,debug
1180 // # compact unwind for _foo
1182 // .set L1,LfooEnd-_foo
1188 // # compact unwind for _bar
1190 // .set L2,LbarEnd-_bar
1193 // .quad __gxx_personality
1194 // .quad except_tab1
1196 uint32_t Encoding = Frame.CompactUnwindEncoding;
1197 if (!Encoding) return;
1198 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1200 // The encoding needs to know we have an LSDA.
1201 if (!DwarfEHFrameOnly && Frame.Lsda)
1202 Encoding |= 0x40000000;
1205 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1206 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1207 if (VerboseAsm) Streamer.AddComment("Range Start");
1208 Streamer.EmitSymbolValue(Frame.Function, Size);
1211 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1213 if (VerboseAsm) Streamer.AddComment("Range Length");
1214 Streamer.EmitAbsValue(Range, 4);
1217 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1218 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1219 Twine::utohexstr(Encoding));
1220 Streamer.EmitIntValue(Encoding, Size);
1222 // Personality Function
1223 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1224 if (VerboseAsm) Streamer.AddComment("Personality Function");
1225 if (!DwarfEHFrameOnly && Frame.Personality)
1226 Streamer.EmitSymbolValue(Frame.Personality, Size);
1228 Streamer.EmitIntValue(0, Size); // No personality fn
1231 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1232 if (VerboseAsm) Streamer.AddComment("LSDA");
1233 if (!DwarfEHFrameOnly && Frame.Lsda)
1234 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1236 Streamer.EmitIntValue(0, Size); // No LSDA
1239 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1240 const MCSymbol *personality,
1241 unsigned personalityEncoding,
1242 const MCSymbol *lsda,
1244 unsigned lsdaEncoding,
1246 MCContext &context = streamer.getContext();
1247 const MCRegisterInfo *MRI = context.getRegisterInfo();
1248 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1249 bool verboseAsm = streamer.isVerboseAsm();
1251 MCSymbol *sectionStart;
1252 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1253 sectionStart = context.CreateTempSymbol();
1255 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1257 streamer.EmitLabel(sectionStart);
1260 MCSymbol *sectionEnd = context.CreateTempSymbol();
1263 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1265 if (verboseAsm) streamer.AddComment("CIE Length");
1266 streamer.EmitAbsValue(Length, 4);
1269 unsigned CIE_ID = IsEH ? 0 : -1;
1270 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1271 streamer.EmitIntValue(CIE_ID, 4);
1274 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1275 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1277 // Augmentation String
1278 SmallString<8> Augmentation;
1280 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1281 Augmentation += "z";
1283 Augmentation += "P";
1285 Augmentation += "L";
1286 Augmentation += "R";
1288 Augmentation += "S";
1289 streamer.EmitBytes(Augmentation.str());
1291 streamer.EmitIntValue(0, 1);
1293 // Code Alignment Factor
1294 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1295 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1297 // Data Alignment Factor
1298 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1299 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1301 // Return Address Register
1302 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1303 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1305 // Augmentation Data Length (optional)
1307 unsigned augmentationLength = 0;
1310 // Personality Encoding
1311 augmentationLength += 1;
1313 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1316 augmentationLength += 1;
1317 // Encoding of the FDE pointers
1318 augmentationLength += 1;
1320 if (verboseAsm) streamer.AddComment("Augmentation Size");
1321 streamer.EmitULEB128IntValue(augmentationLength);
1323 // Augmentation Data (optional)
1325 // Personality Encoding
1326 EmitEncodingByte(streamer, personalityEncoding,
1327 "Personality Encoding");
1329 if (verboseAsm) streamer.AddComment("Personality");
1330 EmitPersonality(streamer, *personality, personalityEncoding);
1334 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1336 // Encoding of the FDE pointers
1337 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1341 // Initial Instructions
1343 const MCAsmInfo *MAI = context.getAsmInfo();
1345 const std::vector<MCCFIInstruction> &Instructions =
1346 MAI->getInitialFrameState();
1347 EmitCFIInstructions(streamer, Instructions, NULL);
1351 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1353 streamer.EmitLabel(sectionEnd);
1354 return *sectionStart;
1357 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1358 const MCSymbol &cieStart,
1359 const MCDwarfFrameInfo &frame) {
1360 MCContext &context = streamer.getContext();
1361 MCSymbol *fdeStart = context.CreateTempSymbol();
1362 MCSymbol *fdeEnd = context.CreateTempSymbol();
1363 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1364 bool verboseAsm = streamer.isVerboseAsm();
1366 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1368 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1369 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1370 streamer.EmitLabel(EHSym);
1374 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1375 if (verboseAsm) streamer.AddComment("FDE Length");
1376 streamer.EmitAbsValue(Length, 4);
1378 streamer.EmitLabel(fdeStart);
1381 const MCAsmInfo *asmInfo = context.getAsmInfo();
1383 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1385 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1386 streamer.EmitAbsValue(offset, 4);
1387 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1388 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1390 streamer.EmitAbsValue(offset, 4);
1392 streamer.EmitSymbolValue(&cieStart, 4);
1396 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1397 : (unsigned)dwarf::DW_EH_PE_absptr;
1398 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1399 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1402 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1404 if (verboseAsm) streamer.AddComment("FDE address range");
1405 streamer.EmitAbsValue(Range, PCSize);
1408 // Augmentation Data Length
1409 unsigned augmentationLength = 0;
1412 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1414 if (verboseAsm) streamer.AddComment("Augmentation size");
1415 streamer.EmitULEB128IntValue(augmentationLength);
1417 // Augmentation Data
1419 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1420 "Language Specific Data Area");
1423 // Call Frame Instructions
1424 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1427 streamer.EmitValueToAlignment(PCSize);
1434 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1435 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1437 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1438 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1439 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1440 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1441 IsSimple(IsSimple_) {
1443 const MCSymbol* Personality;
1444 unsigned PersonalityEncoding;
1445 unsigned LsdaEncoding;
1453 struct DenseMapInfo<CIEKey> {
1454 static CIEKey getEmptyKey() {
1455 return CIEKey::getEmptyKey();
1457 static CIEKey getTombstoneKey() {
1458 return CIEKey::getTombstoneKey();
1460 static unsigned getHashValue(const CIEKey &Key) {
1461 return static_cast<unsigned>(hash_combine(Key.Personality,
1462 Key.PersonalityEncoding,
1467 static bool isEqual(const CIEKey &LHS,
1468 const CIEKey &RHS) {
1469 return LHS.Personality == RHS.Personality &&
1470 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1471 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1472 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1473 LHS.IsSimple == RHS.IsSimple;
1478 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1479 bool UsingCFI, bool IsEH) {
1480 Streamer.generateCompactUnwindEncodings(MAB);
1482 MCContext &Context = Streamer.getContext();
1483 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1484 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1485 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1487 // Emit the compact unwind info if available.
1488 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1489 if (IsEH && MOFI->getCompactUnwindSection()) {
1490 bool SectionEmitted = false;
1491 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1492 const MCDwarfFrameInfo &Frame = FrameArray[i];
1493 if (Frame.CompactUnwindEncoding == 0) continue;
1494 if (!SectionEmitted) {
1495 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1496 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1497 SectionEmitted = true;
1499 NeedsEHFrameSection |=
1500 Frame.CompactUnwindEncoding ==
1501 MOFI->getCompactUnwindDwarfEHFrameOnly();
1502 Emitter.EmitCompactUnwind(Streamer, Frame);
1506 if (!NeedsEHFrameSection) return;
1508 const MCSection &Section =
1509 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1510 *MOFI->getDwarfFrameSection();
1512 Streamer.SwitchSection(&Section);
1513 MCSymbol *SectionStart = Context.CreateTempSymbol();
1514 Streamer.EmitLabel(SectionStart);
1515 Emitter.setSectionStart(SectionStart);
1517 MCSymbol *FDEEnd = NULL;
1518 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1520 const MCSymbol *DummyDebugKey = NULL;
1521 NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1522 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1523 const MCDwarfFrameInfo &Frame = FrameArray[i];
1525 // Emit the label from the previous iteration
1527 Streamer.EmitLabel(FDEEnd);
1531 if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1532 MOFI->getCompactUnwindDwarfEHFrameOnly())
1533 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1534 // of by the compact unwind encoding.
1537 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1538 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1539 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1541 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1542 Frame.PersonalityEncoding, Frame.Lsda,
1543 Frame.IsSignalFrame,
1547 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1550 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1552 Streamer.EmitLabel(FDEEnd);
1555 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1556 uint64_t AddrDelta) {
1557 MCContext &Context = Streamer.getContext();
1558 SmallString<256> Tmp;
1559 raw_svector_ostream OS(Tmp);
1560 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1561 Streamer.EmitBytes(OS.str());
1564 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1567 // Scale the address delta by the minimum instruction length.
1568 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1570 if (AddrDelta == 0) {
1571 } else if (isUIntN(6, AddrDelta)) {
1572 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1574 } else if (isUInt<8>(AddrDelta)) {
1575 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1576 OS << uint8_t(AddrDelta);
1577 } else if (isUInt<16>(AddrDelta)) {
1578 // FIXME: check what is the correct behavior on a big endian machine.
1579 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1580 OS << uint8_t( AddrDelta & 0xff);
1581 OS << uint8_t((AddrDelta >> 8) & 0xff);
1583 // FIXME: check what is the correct behavior on a big endian machine.
1584 assert(isUInt<32>(AddrDelta));
1585 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1586 OS << uint8_t( AddrDelta & 0xff);
1587 OS << uint8_t((AddrDelta >> 8) & 0xff);
1588 OS << uint8_t((AddrDelta >> 16) & 0xff);
1589 OS << uint8_t((AddrDelta >> 24) & 0xff);