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/MCObjectStreamer.h"
21 #include "llvm/MC/MCRegisterInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/LEB128.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/raw_ostream.h"
32 // Given a special op, return the address skip amount (in units of
33 // DWARF2_LINE_MIN_INSN_LENGTH.
34 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
36 // The maximum address skip amount that can be encoded with a special op.
37 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
39 // First special line opcode - leave room for the standard opcodes.
40 // Note: If you want to change this, you'll have to update the
41 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
42 #define DWARF2_LINE_OPCODE_BASE 13
44 // Minimum line offset in a special line info. opcode. This value
45 // was chosen to give a reasonable range of values.
46 #define DWARF2_LINE_BASE -5
48 // Range of line offsets in a special line info. opcode.
49 #define DWARF2_LINE_RANGE 14
51 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
52 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
53 if (MinInsnLength == 1)
55 if (AddrDelta % MinInsnLength != 0) {
56 // TODO: report this error, but really only once.
59 return AddrDelta / MinInsnLength;
63 // This is called when an instruction is assembled into the specified section
64 // and if there is information from the last .loc directive that has yet to have
65 // a line entry made for it is made.
67 void MCLineEntry::Make(MCObjectStreamer *MCOS, const MCSection *Section) {
68 if (!MCOS->getContext().getDwarfLocSeen())
71 // Create a symbol at in the current section for use in the line entry.
72 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
73 // Set the value of the symbol to use for the MCLineEntry.
74 MCOS->EmitLabel(LineSym);
76 // Get the current .loc info saved in the context.
77 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
79 // Create a (local) line entry with the symbol and the current .loc info.
80 MCLineEntry LineEntry(LineSym, DwarfLoc);
82 // clear DwarfLocSeen saying the current .loc info is now used.
83 MCOS->getContext().ClearDwarfLocSeen();
85 // Add the line entry to this section's entries.
87 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
89 .addLineEntry(LineEntry, Section);
93 // This helper routine returns an expression of End - Start + IntVal .
95 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
96 const MCSymbol &Start,
99 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
101 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
103 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
105 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
107 MCConstantExpr::Create(IntVal, MCOS.getContext());
109 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
114 // This emits the Dwarf line table for the specified section from the entries
115 // in the LineSection.
118 EmitDwarfLineTable(MCObjectStreamer *MCOS, const MCSection *Section,
119 const MCLineSection::MCLineEntryCollection &LineEntries) {
120 unsigned FileNum = 1;
121 unsigned LastLine = 1;
123 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
125 unsigned Discriminator = 0;
126 MCSymbol *LastLabel = nullptr;
128 // Loop through each MCLineEntry and encode the dwarf line number table.
129 for (auto it = LineEntries.begin(),
130 ie = LineEntries.end();
133 if (FileNum != it->getFileNum()) {
134 FileNum = it->getFileNum();
135 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
136 MCOS->EmitULEB128IntValue(FileNum);
138 if (Column != it->getColumn()) {
139 Column = it->getColumn();
140 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
141 MCOS->EmitULEB128IntValue(Column);
143 if (Discriminator != it->getDiscriminator()) {
144 Discriminator = it->getDiscriminator();
145 unsigned Size = getULEB128Size(Discriminator);
146 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
147 MCOS->EmitULEB128IntValue(Size + 1);
148 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
149 MCOS->EmitULEB128IntValue(Discriminator);
151 if (Isa != it->getIsa()) {
153 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
154 MCOS->EmitULEB128IntValue(Isa);
156 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
157 Flags = it->getFlags();
158 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
160 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
161 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
162 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
164 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
165 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
167 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
168 MCSymbol *Label = it->getLabel();
170 // At this point we want to emit/create the sequence to encode the delta in
171 // line numbers and the increment of the address from the previous Label
172 // and the current Label.
173 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
174 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
175 asmInfo->getPointerSize());
177 LastLine = it->getLine();
181 // Emit a DW_LNE_end_sequence for the end of the section.
182 // Using the pointer Section create a temporary label at the end of the
183 // section and use that and the LastLabel to compute the address delta
184 // and use INT64_MAX as the line delta which is the signal that this is
185 // actually a DW_LNE_end_sequence.
187 // Switch to the section to be able to create a symbol at its end.
188 // TODO: keep track of the last subsection so that this symbol appears in the
190 MCOS->SwitchSection(Section);
192 MCContext &context = MCOS->getContext();
193 // Create a symbol at the end of the section.
194 MCSymbol *SectionEnd = context.CreateTempSymbol();
195 // Set the value of the symbol, as we are at the end of the section.
196 MCOS->EmitLabel(SectionEnd);
198 // Switch back the dwarf line section.
199 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
201 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
202 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
203 asmInfo->getPointerSize());
207 // This emits the Dwarf file and the line tables.
209 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS) {
210 MCContext &context = MCOS->getContext();
212 auto &LineTables = context.getMCDwarfLineTables();
214 // Bail out early so we don't switch to the debug_line section needlessly and
215 // in doing so create an unnecessary (if empty) section.
216 if (LineTables.empty())
219 // Switch to the section where the table will be emitted into.
220 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
222 // Handle the rest of the Compile Units.
223 for (const auto &CUIDTablePair : LineTables)
224 CUIDTablePair.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 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS) const {
324 MCSymbol *LineEndSym = Header.Emit(MCOS).second;
326 // Put out the line tables.
327 for (const auto &LineSec : MCLineSections.getMCLineEntries())
328 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
330 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
331 MCLineSections.getMCLineEntries().empty()) {
332 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
334 // total_length >= prologue_length + 10
335 // We are 4 bytes short, since we have total_length = 51 and
336 // prologue_length = 45
338 // The regular end_sequence should be sufficient.
339 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
342 // This is the end of the section, so set the value of the symbol at the end
343 // of this section (that was used in a previous expression).
344 MCOS->EmitLabel(LineEndSym);
347 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
348 unsigned FileNumber) {
349 return Header.getFile(Directory, FileName, FileNumber);
352 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
354 unsigned FileNumber) {
355 if (Directory == CompilationDir)
357 if (FileName.empty()) {
358 FileName = "<stdin>";
361 assert(!FileName.empty());
362 if (FileNumber == 0) {
363 FileNumber = SourceIdMap.size() + 1;
364 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
365 "Don't mix autonumbered and explicit numbered line table usage");
366 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(
367 (Directory + Twine('\0') + FileName).str(), FileNumber);
368 if (Ent.getValue() != FileNumber)
369 return Ent.getValue();
371 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
372 MCDwarfFiles.resize(FileNumber + 1);
374 // Get the new MCDwarfFile slot for this FileNumber.
375 MCDwarfFile &File = MCDwarfFiles[FileNumber];
377 // It is an error to use see the same number more than once.
378 if (!File.Name.empty())
381 if (Directory.empty()) {
382 // Separate the directory part from the basename of the FileName.
383 StringRef tFileName = sys::path::filename(FileName);
384 if (!tFileName.empty()) {
385 Directory = sys::path::parent_path(FileName);
386 if (!Directory.empty())
387 FileName = tFileName;
391 // Find or make an entry in the MCDwarfDirs vector for this Directory.
392 // Capture directory name.
394 if (Directory.empty()) {
395 // For FileNames with no directories a DirIndex of 0 is used.
399 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
400 if (Directory == MCDwarfDirs[DirIndex])
403 if (DirIndex >= MCDwarfDirs.size())
404 MCDwarfDirs.push_back(Directory);
405 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
406 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
407 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
408 // are stored at MCDwarfFiles[FileNumber].Name .
412 File.Name = FileName;
413 File.DirIndex = DirIndex;
415 // return the allocated FileNumber.
419 /// Utility function to emit the encoding to a streamer.
420 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
421 uint64_t AddrDelta) {
422 MCContext &Context = MCOS->getContext();
423 small_string_ostream<256> OS;
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 if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1) {
522 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
524 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
525 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
527 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
528 if (!context.getCompilationDir().empty())
529 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
530 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
531 if (!DwarfDebugFlags.empty())
532 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
533 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
534 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
535 EmitAbbrev(MCOS, 0, 0);
537 // DW_TAG_label DIE abbrev (2).
538 MCOS->EmitULEB128IntValue(2);
539 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
540 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
541 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
542 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
543 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
544 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
545 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
546 EmitAbbrev(MCOS, 0, 0);
548 // DW_TAG_unspecified_parameters DIE abbrev (3).
549 MCOS->EmitULEB128IntValue(3);
550 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
551 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
552 EmitAbbrev(MCOS, 0, 0);
554 // Terminate the abbreviations for this compilation unit.
555 MCOS->EmitIntValue(0, 1);
558 // When generating dwarf for assembly source files this emits the data for
559 // .debug_aranges section. This section contains a header and a table of pairs
560 // of PointerSize'ed values for the address and size of section(s) with line
562 static void EmitGenDwarfAranges(MCStreamer *MCOS,
563 const MCSymbol *InfoSectionSymbol) {
564 MCContext &context = MCOS->getContext();
566 auto &Sections = context.getGenDwarfSectionSyms();
568 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
570 // This will be the length of the .debug_aranges section, first account for
571 // the size of each item in the header (see below where we emit these items).
572 int Length = 4 + 2 + 4 + 1 + 1;
574 // Figure the padding after the header before the table of address and size
575 // pairs who's values are PointerSize'ed.
576 const MCAsmInfo *asmInfo = context.getAsmInfo();
577 int AddrSize = asmInfo->getPointerSize();
578 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
579 if (Pad == 2 * AddrSize)
583 // Add the size of the pair of PointerSize'ed values for the address and size
584 // of each section we have in the table.
585 Length += 2 * AddrSize * Sections.size();
586 // And the pair of terminating zeros.
587 Length += 2 * AddrSize;
590 // Emit the header for this section.
591 // The 4 byte length not including the 4 byte value for the length.
592 MCOS->EmitIntValue(Length - 4, 4);
593 // The 2 byte version, which is 2.
594 MCOS->EmitIntValue(2, 2);
595 // The 4 byte offset to the compile unit in the .debug_info from the start
596 // of the .debug_info.
597 if (InfoSectionSymbol)
598 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
600 MCOS->EmitIntValue(0, 4);
601 // The 1 byte size of an address.
602 MCOS->EmitIntValue(AddrSize, 1);
603 // The 1 byte size of a segment descriptor, we use a value of zero.
604 MCOS->EmitIntValue(0, 1);
605 // Align the header with the padding if needed, before we put out the table.
606 for(int i = 0; i < Pad; i++)
607 MCOS->EmitIntValue(0, 1);
609 // Now emit the table of pairs of PointerSize'ed values for the section
610 // addresses and sizes.
611 for (const auto &sec : Sections) {
612 MCSymbol *StartSymbol = sec.second.first;
613 MCSymbol *EndSymbol = sec.second.second;
614 assert(StartSymbol && "StartSymbol must not be NULL");
615 assert(EndSymbol && "EndSymbol must not be NULL");
617 const MCExpr *Addr = MCSymbolRefExpr::Create(
618 StartSymbol, MCSymbolRefExpr::VK_None, context);
619 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
620 *StartSymbol, *EndSymbol, 0);
621 MCOS->EmitValue(Addr, AddrSize);
622 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 const MCSymbol *RangesSectionSymbol) {
637 MCContext &context = MCOS->getContext();
639 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
641 // Create a symbol at the start and end of this section used in here for the
642 // expression to calculate the length in the header.
643 MCSymbol *InfoStart = context.CreateTempSymbol();
644 MCOS->EmitLabel(InfoStart);
645 MCSymbol *InfoEnd = context.CreateTempSymbol();
647 // First part: the header.
649 // The 4 byte total length of the information for this compilation unit, not
650 // including these 4 bytes.
651 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
652 MCOS->EmitAbsValue(Length, 4);
654 // The 2 byte DWARF version.
655 MCOS->EmitIntValue(context.getDwarfVersion(), 2);
657 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
658 // it is at the start of that section so this is zero.
659 if (AbbrevSectionSymbol) {
660 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
662 MCOS->EmitIntValue(0, 4);
665 const MCAsmInfo *asmInfo = context.getAsmInfo();
666 int AddrSize = asmInfo->getPointerSize();
667 // The 1 byte size of an address.
668 MCOS->EmitIntValue(AddrSize, 1);
670 // Second part: the compile_unit DIE.
672 // The DW_TAG_compile_unit DIE abbrev (1).
673 MCOS->EmitULEB128IntValue(1);
675 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
676 // which is at the start of that section so this is zero.
677 if (LineSectionSymbol) {
678 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
680 MCOS->EmitIntValue(0, 4);
683 if (RangesSectionSymbol) {
684 // There are multiple sections containing code, so we must use the
685 // .debug_ranges sections.
687 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
688 // to the address range list for this compilation unit.
689 MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
691 // If we only have one non-empty code section, we can use the simpler
692 // AT_low_pc and AT_high_pc attributes.
694 // Find the first (and only) non-empty text section
695 auto &Sections = context.getGenDwarfSectionSyms();
696 const auto TextSection = Sections.begin();
697 assert(TextSection != Sections.end() && "No text section found");
699 MCSymbol *StartSymbol = TextSection->second.first;
700 MCSymbol *EndSymbol = TextSection->second.second;
701 assert(StartSymbol && "StartSymbol must not be NULL");
702 assert(EndSymbol && "EndSymbol must not be NULL");
704 // AT_low_pc, the first address of the default .text section.
705 const MCExpr *Start = MCSymbolRefExpr::Create(
706 StartSymbol, MCSymbolRefExpr::VK_None, context);
707 MCOS->EmitValue(Start, AddrSize);
709 // AT_high_pc, the last address of the default .text section.
710 const MCExpr *End = MCSymbolRefExpr::Create(
711 EndSymbol, MCSymbolRefExpr::VK_None, context);
712 MCOS->EmitValue(End, AddrSize);
715 // AT_name, the name of the source file. Reconstruct from the first directory
716 // and file table entries.
717 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
718 if (MCDwarfDirs.size() > 0) {
719 MCOS->EmitBytes(MCDwarfDirs[0]);
720 MCOS->EmitBytes(sys::path::get_separator());
722 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
723 MCOS->getContext().getMCDwarfFiles();
724 MCOS->EmitBytes(MCDwarfFiles[1].Name);
725 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
727 // AT_comp_dir, the working directory the assembly was done in.
728 if (!context.getCompilationDir().empty()) {
729 MCOS->EmitBytes(context.getCompilationDir());
730 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
733 // AT_APPLE_flags, the command line arguments of the assembler tool.
734 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
735 if (!DwarfDebugFlags.empty()){
736 MCOS->EmitBytes(DwarfDebugFlags);
737 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
740 // AT_producer, the version of the assembler tool.
741 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
742 if (!DwarfDebugProducer.empty()){
743 MCOS->EmitBytes(DwarfDebugProducer);
746 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
747 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
748 MCOS->EmitBytes(StringRef(")"));
750 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
752 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
753 // draft has no standard code for assembler.
754 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
756 // Third part: the list of label DIEs.
758 // Loop on saved info for dwarf labels and create the DIEs for them.
759 const std::vector<MCGenDwarfLabelEntry> &Entries =
760 MCOS->getContext().getMCGenDwarfLabelEntries();
761 for (const auto &Entry : Entries) {
762 // The DW_TAG_label DIE abbrev (2).
763 MCOS->EmitULEB128IntValue(2);
765 // AT_name, of the label without any leading underbar.
766 MCOS->EmitBytes(Entry.getName());
767 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
769 // AT_decl_file, index into the file table.
770 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
772 // AT_decl_line, source line number.
773 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
775 // AT_low_pc, start address of the label.
776 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry.getLabel(),
777 MCSymbolRefExpr::VK_None, context);
778 MCOS->EmitValue(AT_low_pc, AddrSize);
780 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
781 MCOS->EmitIntValue(0, 1);
783 // The DW_TAG_unspecified_parameters DIE abbrev (3).
784 MCOS->EmitULEB128IntValue(3);
786 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
787 MCOS->EmitIntValue(0, 1);
790 // Add the NULL DIE terminating the Compile Unit DIE's.
791 MCOS->EmitIntValue(0, 1);
793 // Now set the value of the symbol at the end of the info section.
794 MCOS->EmitLabel(InfoEnd);
797 // When generating dwarf for assembly source files this emits the data for
798 // .debug_ranges section. We only emit one range list, which spans all of the
799 // executable sections of this file.
800 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
801 MCContext &context = MCOS->getContext();
802 auto &Sections = context.getGenDwarfSectionSyms();
804 const MCAsmInfo *AsmInfo = context.getAsmInfo();
805 int AddrSize = AsmInfo->getPointerSize();
807 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
809 for (const auto sec : Sections) {
811 MCSymbol *StartSymbol = sec.second.first;
812 MCSymbol *EndSymbol = sec.second.second;
813 assert(StartSymbol && "StartSymbol must not be NULL");
814 assert(EndSymbol && "EndSymbol must not be NULL");
816 // Emit a base address selection entry for the start of this section
817 const MCExpr *SectionStartAddr = MCSymbolRefExpr::Create(
818 StartSymbol, MCSymbolRefExpr::VK_None, context);
819 MCOS->EmitFill(AddrSize, 0xFF);
820 MCOS->EmitValue(SectionStartAddr, AddrSize);
822 // Emit a range list entry spanning this section
823 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
824 *StartSymbol, *EndSymbol, 0);
825 MCOS->EmitIntValue(0, AddrSize);
826 MCOS->EmitAbsValue(SectionSize, AddrSize);
829 // Emit end of list entry
830 MCOS->EmitIntValue(0, AddrSize);
831 MCOS->EmitIntValue(0, AddrSize);
835 // When generating dwarf for assembly source files this emits the Dwarf
838 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
839 MCContext &context = MCOS->getContext();
841 // Create the dwarf sections in this order (.debug_line already created).
842 const MCAsmInfo *AsmInfo = context.getAsmInfo();
843 bool CreateDwarfSectionSymbols =
844 AsmInfo->doesDwarfUseRelocationsAcrossSections();
845 MCSymbol *LineSectionSymbol = nullptr;
846 if (CreateDwarfSectionSymbols)
847 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
848 MCSymbol *AbbrevSectionSymbol = nullptr;
849 MCSymbol *InfoSectionSymbol = nullptr;
850 MCSymbol *RangesSectionSymbol = NULL;
852 // Create end symbols for each section, and remove empty sections
853 MCOS->getContext().finalizeDwarfSections(*MCOS);
855 // If there are no sections to generate debug info for, we don't need
857 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
860 // We only need to use the .debug_ranges section if we have multiple
862 const bool UseRangesSection =
863 MCOS->getContext().getGenDwarfSectionSyms().size() > 1;
864 CreateDwarfSectionSymbols |= UseRangesSection;
866 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
867 if (CreateDwarfSectionSymbols) {
868 InfoSectionSymbol = context.CreateTempSymbol();
869 MCOS->EmitLabel(InfoSectionSymbol);
871 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
872 if (CreateDwarfSectionSymbols) {
873 AbbrevSectionSymbol = context.CreateTempSymbol();
874 MCOS->EmitLabel(AbbrevSectionSymbol);
876 if (UseRangesSection) {
877 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
878 if (CreateDwarfSectionSymbols) {
879 RangesSectionSymbol = context.CreateTempSymbol();
880 MCOS->EmitLabel(RangesSectionSymbol);
884 assert((RangesSectionSymbol != NULL) || !UseRangesSection);
886 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
888 // Output the data for .debug_aranges section.
889 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
891 if (UseRangesSection)
892 EmitGenDwarfRanges(MCOS);
894 // Output the data for .debug_abbrev section.
895 EmitGenDwarfAbbrev(MCOS);
897 // Output the data for .debug_info section.
898 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
899 RangesSectionSymbol);
903 // When generating dwarf for assembly source files this is called when symbol
904 // for a label is created. If this symbol is not a temporary and is in the
905 // section that dwarf is being generated for, save the needed info to create
908 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
909 SourceMgr &SrcMgr, SMLoc &Loc) {
910 // We won't create dwarf labels for temporary symbols.
911 if (Symbol->isTemporary())
913 MCContext &context = MCOS->getContext();
914 // We won't create dwarf labels for symbols in sections that we are not
915 // generating debug info for.
916 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
919 // The dwarf label's name does not have the symbol name's leading
921 StringRef Name = Symbol->getName();
922 if (Name.startswith("_"))
923 Name = Name.substr(1, Name.size()-1);
925 // Get the dwarf file number to be used for the dwarf label.
926 unsigned FileNumber = context.getGenDwarfFileNumber();
928 // Finding the line number is the expensive part which is why we just don't
929 // pass it in as for some symbols we won't create a dwarf label.
930 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
931 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
933 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
934 // values so that they don't have things like an ARM thumb bit from the
935 // original symbol. So when used they won't get a low bit set after
937 MCSymbol *Label = context.CreateTempSymbol();
938 MCOS->EmitLabel(Label);
940 // Create and entry for the info and add it to the other entries.
941 MCOS->getContext().addMCGenDwarfLabelEntry(
942 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
945 static int getDataAlignmentFactor(MCStreamer &streamer) {
946 MCContext &context = streamer.getContext();
947 const MCAsmInfo *asmInfo = context.getAsmInfo();
948 int size = asmInfo->getCalleeSaveStackSlotSize();
949 if (asmInfo->isStackGrowthDirectionUp())
955 static unsigned getSizeForEncoding(MCStreamer &streamer,
956 unsigned symbolEncoding) {
957 MCContext &context = streamer.getContext();
958 unsigned format = symbolEncoding & 0x0f;
960 default: llvm_unreachable("Unknown Encoding");
961 case dwarf::DW_EH_PE_absptr:
962 case dwarf::DW_EH_PE_signed:
963 return context.getAsmInfo()->getPointerSize();
964 case dwarf::DW_EH_PE_udata2:
965 case dwarf::DW_EH_PE_sdata2:
967 case dwarf::DW_EH_PE_udata4:
968 case dwarf::DW_EH_PE_sdata4:
970 case dwarf::DW_EH_PE_udata8:
971 case dwarf::DW_EH_PE_sdata8:
976 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
977 unsigned symbolEncoding, bool isEH,
978 const char *comment = nullptr) {
979 MCContext &context = streamer.getContext();
980 const MCAsmInfo *asmInfo = context.getAsmInfo();
981 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
984 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
985 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
986 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
987 streamer.EmitAbsValue(v, size);
989 streamer.EmitValue(v, size);
992 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
993 unsigned symbolEncoding) {
994 MCContext &context = streamer.getContext();
995 const MCAsmInfo *asmInfo = context.getAsmInfo();
996 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
999 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1000 streamer.EmitValue(v, size);
1004 class FrameEmitterImpl {
1008 const MCSymbol *SectionStart;
1010 FrameEmitterImpl(bool isEH)
1011 : CFAOffset(0), CIENum(0), IsEH(isEH), SectionStart(nullptr) {}
1013 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
1015 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1016 void EmitCompactUnwind(MCStreamer &streamer,
1017 const MCDwarfFrameInfo &frame);
1019 const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
1020 const MCSymbol *personality,
1021 unsigned personalityEncoding,
1022 const MCSymbol *lsda,
1024 unsigned lsdaEncoding,
1026 MCSymbol *EmitFDE(MCObjectStreamer &streamer,
1027 const MCSymbol &cieStart,
1028 const MCDwarfFrameInfo &frame);
1029 void EmitCFIInstructions(MCObjectStreamer &streamer,
1030 ArrayRef<MCCFIInstruction> Instrs,
1031 MCSymbol *BaseLabel);
1032 void EmitCFIInstruction(MCObjectStreamer &Streamer,
1033 const MCCFIInstruction &Instr);
1036 } // end anonymous namespace
1038 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
1040 if (Streamer.isVerboseAsm()) {
1043 default: EncStr = "<unknown encoding>"; break;
1044 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
1045 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
1046 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
1047 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
1048 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
1049 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
1050 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
1051 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
1052 EncStr = "pcrel udata4";
1054 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
1055 EncStr = "pcrel sdata4";
1057 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
1058 EncStr = "pcrel udata8";
1060 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
1061 EncStr = "screl sdata8";
1063 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
1064 EncStr = "indirect pcrel udata4";
1066 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
1067 EncStr = "indirect pcrel sdata4";
1069 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
1070 EncStr = "indirect pcrel udata8";
1072 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
1073 EncStr = "indirect pcrel sdata8";
1077 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
1080 Streamer.EmitIntValue(Encoding, 1);
1083 void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
1084 const MCCFIInstruction &Instr) {
1085 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1086 bool VerboseAsm = Streamer.isVerboseAsm();
1088 switch (Instr.getOperation()) {
1089 case MCCFIInstruction::OpRegister: {
1090 unsigned Reg1 = Instr.getRegister();
1091 unsigned Reg2 = Instr.getRegister2();
1093 Streamer.AddComment("DW_CFA_register");
1094 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
1095 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
1097 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1098 Streamer.EmitULEB128IntValue(Reg1);
1099 Streamer.EmitULEB128IntValue(Reg2);
1102 case MCCFIInstruction::OpWindowSave: {
1103 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1106 case MCCFIInstruction::OpUndefined: {
1107 unsigned Reg = Instr.getRegister();
1109 Streamer.AddComment("DW_CFA_undefined");
1110 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1112 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1113 Streamer.EmitULEB128IntValue(Reg);
1116 case MCCFIInstruction::OpAdjustCfaOffset:
1117 case MCCFIInstruction::OpDefCfaOffset: {
1118 const bool IsRelative =
1119 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1122 Streamer.AddComment("DW_CFA_def_cfa_offset");
1123 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1126 CFAOffset += Instr.getOffset();
1128 CFAOffset = -Instr.getOffset();
1131 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1132 Streamer.EmitULEB128IntValue(CFAOffset);
1136 case MCCFIInstruction::OpDefCfa: {
1138 Streamer.AddComment("DW_CFA_def_cfa");
1139 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1142 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1143 Streamer.EmitULEB128IntValue(Instr.getRegister());
1145 CFAOffset = -Instr.getOffset();
1148 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1149 Streamer.EmitULEB128IntValue(CFAOffset);
1154 case MCCFIInstruction::OpDefCfaRegister: {
1156 Streamer.AddComment("DW_CFA_def_cfa_register");
1157 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1160 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1161 Streamer.EmitULEB128IntValue(Instr.getRegister());
1166 case MCCFIInstruction::OpOffset:
1167 case MCCFIInstruction::OpRelOffset: {
1168 const bool IsRelative =
1169 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1171 unsigned Reg = Instr.getRegister();
1172 int Offset = Instr.getOffset();
1174 Offset -= CFAOffset;
1175 Offset = Offset / dataAlignmentFactor;
1178 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1179 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1180 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1181 Streamer.EmitULEB128IntValue(Reg);
1182 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1183 Streamer.EmitSLEB128IntValue(Offset);
1184 } else if (Reg < 64) {
1185 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1187 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1188 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1189 Streamer.EmitULEB128IntValue(Offset);
1191 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1192 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1193 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1194 Streamer.EmitULEB128IntValue(Reg);
1195 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1196 Streamer.EmitULEB128IntValue(Offset);
1200 case MCCFIInstruction::OpRememberState:
1201 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1202 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1204 case MCCFIInstruction::OpRestoreState:
1205 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1206 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1208 case MCCFIInstruction::OpSameValue: {
1209 unsigned Reg = Instr.getRegister();
1210 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1211 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1212 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1213 Streamer.EmitULEB128IntValue(Reg);
1216 case MCCFIInstruction::OpRestore: {
1217 unsigned Reg = Instr.getRegister();
1219 Streamer.AddComment("DW_CFA_restore");
1220 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1222 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1225 case MCCFIInstruction::OpEscape:
1226 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1227 Streamer.EmitBytes(Instr.getValues());
1230 llvm_unreachable("Unhandled case in switch");
1233 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1235 void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
1236 ArrayRef<MCCFIInstruction> Instrs,
1237 MCSymbol *BaseLabel) {
1238 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1239 const MCCFIInstruction &Instr = Instrs[i];
1240 MCSymbol *Label = Instr.getLabel();
1241 // Throw out move if the label is invalid.
1242 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1244 // Advance row if new location.
1245 if (BaseLabel && Label) {
1246 MCSymbol *ThisSym = Label;
1247 if (ThisSym != BaseLabel) {
1248 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1249 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1250 BaseLabel = ThisSym;
1254 EmitCFIInstruction(streamer, Instr);
1258 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1259 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1260 const MCDwarfFrameInfo &Frame) {
1261 MCContext &Context = Streamer.getContext();
1262 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1263 bool VerboseAsm = Streamer.isVerboseAsm();
1265 // range-start range-length compact-unwind-enc personality-func lsda
1266 // _foo LfooEnd-_foo 0x00000023 0 0
1267 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1269 // .section __LD,__compact_unwind,regular,debug
1271 // # compact unwind for _foo
1273 // .set L1,LfooEnd-_foo
1279 // # compact unwind for _bar
1281 // .set L2,LbarEnd-_bar
1284 // .quad __gxx_personality
1285 // .quad except_tab1
1287 uint32_t Encoding = Frame.CompactUnwindEncoding;
1288 if (!Encoding) return;
1289 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1291 // The encoding needs to know we have an LSDA.
1292 if (!DwarfEHFrameOnly && Frame.Lsda)
1293 Encoding |= 0x40000000;
1296 unsigned FDEEncoding = MOFI->getFDEEncoding();
1297 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1298 if (VerboseAsm) Streamer.AddComment("Range Start");
1299 Streamer.EmitSymbolValue(Frame.Begin, Size);
1302 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1304 if (VerboseAsm) Streamer.AddComment("Range Length");
1305 Streamer.EmitAbsValue(Range, 4);
1308 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1309 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1310 Twine::utohexstr(Encoding));
1311 Streamer.EmitIntValue(Encoding, Size);
1313 // Personality Function
1314 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1315 if (VerboseAsm) Streamer.AddComment("Personality Function");
1316 if (!DwarfEHFrameOnly && Frame.Personality)
1317 Streamer.EmitSymbolValue(Frame.Personality, Size);
1319 Streamer.EmitIntValue(0, Size); // No personality fn
1322 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1323 if (VerboseAsm) Streamer.AddComment("LSDA");
1324 if (!DwarfEHFrameOnly && Frame.Lsda)
1325 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1327 Streamer.EmitIntValue(0, Size); // No LSDA
1330 const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
1331 const MCSymbol *personality,
1332 unsigned personalityEncoding,
1333 const MCSymbol *lsda,
1335 unsigned lsdaEncoding,
1337 MCContext &context = streamer.getContext();
1338 const MCRegisterInfo *MRI = context.getRegisterInfo();
1339 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1340 bool verboseAsm = streamer.isVerboseAsm();
1342 MCSymbol *sectionStart = context.CreateTempSymbol();
1343 streamer.EmitLabel(sectionStart);
1346 MCSymbol *sectionEnd = context.CreateTempSymbol();
1349 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1351 if (verboseAsm) streamer.AddComment("CIE Length");
1352 streamer.EmitAbsValue(Length, 4);
1355 unsigned CIE_ID = IsEH ? 0 : -1;
1356 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1357 streamer.EmitIntValue(CIE_ID, 4);
1360 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1361 // For DWARF2, we use CIE version 1
1362 // For DWARF3+, we use CIE version 3
1363 uint8_t CIEVersion = context.getDwarfVersion() <= 2 ? 1 : 3;
1364 streamer.EmitIntValue(CIEVersion, 1);
1366 // Augmentation String
1367 SmallString<8> Augmentation;
1369 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1370 Augmentation += "z";
1372 Augmentation += "P";
1374 Augmentation += "L";
1375 Augmentation += "R";
1377 Augmentation += "S";
1378 streamer.EmitBytes(Augmentation.str());
1380 streamer.EmitIntValue(0, 1);
1382 // Code Alignment Factor
1383 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1384 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1386 // Data Alignment Factor
1387 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1388 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1390 // Return Address Register
1391 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1392 if (CIEVersion == 1) {
1393 assert(MRI->getRARegister() <= 255 &&
1394 "DWARF 2 encodes return_address_register in one byte");
1395 streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true), 1);
1397 streamer.EmitULEB128IntValue(
1398 MRI->getDwarfRegNum(MRI->getRARegister(), true));
1401 // Augmentation Data Length (optional)
1403 unsigned augmentationLength = 0;
1406 // Personality Encoding
1407 augmentationLength += 1;
1409 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1412 augmentationLength += 1;
1413 // Encoding of the FDE pointers
1414 augmentationLength += 1;
1416 if (verboseAsm) streamer.AddComment("Augmentation Size");
1417 streamer.EmitULEB128IntValue(augmentationLength);
1419 // Augmentation Data (optional)
1421 // Personality Encoding
1422 EmitEncodingByte(streamer, personalityEncoding,
1423 "Personality Encoding");
1425 if (verboseAsm) streamer.AddComment("Personality");
1426 EmitPersonality(streamer, *personality, personalityEncoding);
1430 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1432 // Encoding of the FDE pointers
1433 EmitEncodingByte(streamer, MOFI->getFDEEncoding(), "FDE Encoding");
1436 // Initial Instructions
1438 const MCAsmInfo *MAI = context.getAsmInfo();
1440 const std::vector<MCCFIInstruction> &Instructions =
1441 MAI->getInitialFrameState();
1442 EmitCFIInstructions(streamer, Instructions, nullptr);
1446 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1448 streamer.EmitLabel(sectionEnd);
1449 return *sectionStart;
1452 MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
1453 const MCSymbol &cieStart,
1454 const MCDwarfFrameInfo &frame) {
1455 MCContext &context = streamer.getContext();
1456 MCSymbol *fdeStart = context.CreateTempSymbol();
1457 MCSymbol *fdeEnd = context.CreateTempSymbol();
1458 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1459 bool verboseAsm = streamer.isVerboseAsm();
1462 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1463 if (verboseAsm) streamer.AddComment("FDE Length");
1464 streamer.EmitAbsValue(Length, 4);
1466 streamer.EmitLabel(fdeStart);
1469 const MCAsmInfo *asmInfo = context.getAsmInfo();
1471 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1473 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1474 streamer.EmitAbsValue(offset, 4);
1475 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1476 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1478 streamer.EmitAbsValue(offset, 4);
1480 streamer.EmitSymbolValue(&cieStart, 4);
1484 unsigned PCEncoding =
1485 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1486 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1487 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1490 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1492 if (verboseAsm) streamer.AddComment("FDE address range");
1493 streamer.EmitAbsValue(Range, PCSize);
1496 // Augmentation Data Length
1497 unsigned augmentationLength = 0;
1500 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1502 if (verboseAsm) streamer.AddComment("Augmentation size");
1503 streamer.EmitULEB128IntValue(augmentationLength);
1505 // Augmentation Data
1507 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1508 "Language Specific Data Area");
1511 // Call Frame Instructions
1512 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1515 streamer.EmitValueToAlignment(PCSize);
1522 static const CIEKey getEmptyKey() {
1523 return CIEKey(nullptr, 0, -1, false, false);
1525 static const CIEKey getTombstoneKey() {
1526 return CIEKey(nullptr, -1, 0, false, false);
1529 CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
1530 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
1531 : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1532 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1533 IsSimple(IsSimple_) {}
1534 const MCSymbol *Personality;
1535 unsigned PersonalityEncoding;
1536 unsigned LsdaEncoding;
1544 struct DenseMapInfo<CIEKey> {
1545 static CIEKey getEmptyKey() {
1546 return CIEKey::getEmptyKey();
1548 static CIEKey getTombstoneKey() {
1549 return CIEKey::getTombstoneKey();
1551 static unsigned getHashValue(const CIEKey &Key) {
1552 return static_cast<unsigned>(hash_combine(Key.Personality,
1553 Key.PersonalityEncoding,
1558 static bool isEqual(const CIEKey &LHS,
1559 const CIEKey &RHS) {
1560 return LHS.Personality == RHS.Personality &&
1561 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1562 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1563 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1564 LHS.IsSimple == RHS.IsSimple;
1569 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1571 Streamer.generateCompactUnwindEncodings(MAB);
1573 MCContext &Context = Streamer.getContext();
1574 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1575 FrameEmitterImpl Emitter(IsEH);
1576 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1578 // Emit the compact unwind info if available.
1579 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1580 if (IsEH && MOFI->getCompactUnwindSection()) {
1581 bool SectionEmitted = false;
1582 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1583 const MCDwarfFrameInfo &Frame = FrameArray[i];
1584 if (Frame.CompactUnwindEncoding == 0) continue;
1585 if (!SectionEmitted) {
1586 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1587 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1588 SectionEmitted = true;
1590 NeedsEHFrameSection |=
1591 Frame.CompactUnwindEncoding ==
1592 MOFI->getCompactUnwindDwarfEHFrameOnly();
1593 Emitter.EmitCompactUnwind(Streamer, Frame);
1597 if (!NeedsEHFrameSection) return;
1599 const MCSection &Section =
1600 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1601 *MOFI->getDwarfFrameSection();
1603 Streamer.SwitchSection(&Section);
1604 MCSymbol *SectionStart = Context.CreateTempSymbol();
1605 Streamer.EmitLabel(SectionStart);
1606 Emitter.setSectionStart(SectionStart);
1608 MCSymbol *FDEEnd = nullptr;
1609 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1611 const MCSymbol *DummyDebugKey = nullptr;
1612 NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1613 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1614 const MCDwarfFrameInfo &Frame = FrameArray[i];
1616 // Emit the label from the previous iteration
1618 Streamer.EmitLabel(FDEEnd);
1622 if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1623 MOFI->getCompactUnwindDwarfEHFrameOnly())
1624 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1625 // of by the compact unwind encoding.
1628 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1629 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1630 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1632 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1633 Frame.PersonalityEncoding, Frame.Lsda,
1634 Frame.IsSignalFrame,
1638 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1641 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1643 Streamer.EmitLabel(FDEEnd);
1646 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1647 uint64_t AddrDelta) {
1648 MCContext &Context = Streamer.getContext();
1649 small_string_ostream<256> OS;
1650 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1651 Streamer.EmitBytes(OS.str());
1654 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1657 // Scale the address delta by the minimum instruction length.
1658 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1660 if (AddrDelta == 0) {
1661 } else if (isUIntN(6, AddrDelta)) {
1662 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1664 } else if (isUInt<8>(AddrDelta)) {
1665 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1666 OS << uint8_t(AddrDelta);
1667 } else if (isUInt<16>(AddrDelta)) {
1668 // FIXME: check what is the correct behavior on a big endian machine.
1669 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1670 OS << uint8_t( AddrDelta & 0xff);
1671 OS << uint8_t((AddrDelta >> 8) & 0xff);
1673 // FIXME: check what is the correct behavior on a big endian machine.
1674 assert(isUInt<32>(AddrDelta));
1675 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1676 OS << uint8_t( AddrDelta & 0xff);
1677 OS << uint8_t((AddrDelta >> 8) & 0xff);
1678 OS << uint8_t((AddrDelta >> 16) & 0xff);
1679 OS << uint8_t((AddrDelta >> 24) & 0xff);