MCDwarf.cpp revision 266715
1//===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/MC/MCDwarf.h"
11#include "llvm/ADT/Hashing.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/Twine.h"
14#include "llvm/Config/config.h"
15#include "llvm/MC/MCAsmInfo.h"
16#include "llvm/MC/MCContext.h"
17#include "llvm/MC/MCExpr.h"
18#include "llvm/MC/MCObjectFileInfo.h"
19#include "llvm/MC/MCRegisterInfo.h"
20#include "llvm/MC/MCStreamer.h"
21#include "llvm/MC/MCSymbol.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/LEB128.h"
25#include "llvm/Support/Path.h"
26#include "llvm/Support/SourceMgr.h"
27#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
30// Given a special op, return the address skip amount (in units of
31// DWARF2_LINE_MIN_INSN_LENGTH.
32#define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
33
34// The maximum address skip amount that can be encoded with a special op.
35#define MAX_SPECIAL_ADDR_DELTA         SPECIAL_ADDR(255)
36
37// First special line opcode - leave room for the standard opcodes.
38// Note: If you want to change this, you'll have to update the
39// "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
40#define DWARF2_LINE_OPCODE_BASE         13
41
42// Minimum line offset in a special line info. opcode.  This value
43// was chosen to give a reasonable range of values.
44#define DWARF2_LINE_BASE                -5
45
46// Range of line offsets in a special line info. opcode.
47#define DWARF2_LINE_RANGE               14
48
49static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
50  unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
51  if (MinInsnLength == 1)
52    return AddrDelta;
53  if (AddrDelta % MinInsnLength != 0) {
54    // TODO: report this error, but really only once.
55    ;
56  }
57  return AddrDelta / MinInsnLength;
58}
59
60//
61// This is called when an instruction is assembled into the specified section
62// and if there is information from the last .loc directive that has yet to have
63// a line entry made for it is made.
64//
65void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
66  if (!MCOS->getContext().getDwarfLocSeen())
67    return;
68
69  // Create a symbol at in the current section for use in the line entry.
70  MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
71  // Set the value of the symbol to use for the MCLineEntry.
72  MCOS->EmitLabel(LineSym);
73
74  // Get the current .loc info saved in the context.
75  const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
76
77  // Create a (local) line entry with the symbol and the current .loc info.
78  MCLineEntry LineEntry(LineSym, DwarfLoc);
79
80  // clear DwarfLocSeen saying the current .loc info is now used.
81  MCOS->getContext().ClearDwarfLocSeen();
82
83  // Get the MCLineSection for this section, if one does not exist for this
84  // section create it.
85  const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
86    MCOS->getContext().getMCLineSections();
87  MCLineSection *LineSection = MCLineSections.lookup(Section);
88  if (!LineSection) {
89    // Create a new MCLineSection.  This will be deleted after the dwarf line
90    // table is created using it by iterating through the MCLineSections
91    // DenseMap.
92    LineSection = new MCLineSection;
93    // Save a pointer to the new LineSection into the MCLineSections DenseMap.
94    MCOS->getContext().addMCLineSection(Section, LineSection);
95  }
96
97  // Add the line entry to this section's entries.
98  LineSection->addLineEntry(LineEntry,
99                            MCOS->getContext().getDwarfCompileUnitID());
100}
101
102//
103// This helper routine returns an expression of End - Start + IntVal .
104//
105static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
106                                                  const MCSymbol &Start,
107                                                  const MCSymbol &End,
108                                                  int IntVal) {
109  MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
110  const MCExpr *Res =
111    MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
112  const MCExpr *RHS =
113    MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
114  const MCExpr *Res1 =
115    MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
116  const MCExpr *Res2 =
117    MCConstantExpr::Create(IntVal, MCOS.getContext());
118  const MCExpr *Res3 =
119    MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
120  return Res3;
121}
122
123//
124// This emits the Dwarf line table for the specified section from the entries
125// in the LineSection.
126//
127static inline void EmitDwarfLineTable(MCStreamer *MCOS,
128                                      const MCSection *Section,
129                                      const MCLineSection *LineSection,
130                                      unsigned CUID) {
131  // This LineSection does not contain any LineEntry for the given Compile Unit.
132  if (!LineSection->containEntriesForID(CUID))
133    return;
134
135  unsigned FileNum = 1;
136  unsigned LastLine = 1;
137  unsigned Column = 0;
138  unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
139  unsigned Isa = 0;
140  MCSymbol *LastLabel = NULL;
141
142  // Loop through each MCLineEntry and encode the dwarf line number table.
143  for (MCLineSection::const_iterator
144         it = LineSection->getMCLineEntries(CUID).begin(),
145         ie = LineSection->getMCLineEntries(CUID).end(); it != ie; ++it) {
146
147    if (FileNum != it->getFileNum()) {
148      FileNum = it->getFileNum();
149      MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
150      MCOS->EmitULEB128IntValue(FileNum);
151    }
152    if (Column != it->getColumn()) {
153      Column = it->getColumn();
154      MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
155      MCOS->EmitULEB128IntValue(Column);
156    }
157    if (Isa != it->getIsa()) {
158      Isa = it->getIsa();
159      MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
160      MCOS->EmitULEB128IntValue(Isa);
161    }
162    if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
163      Flags = it->getFlags();
164      MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
165    }
166    if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
167      MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
168    if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
169      MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
170    if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
171      MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
172
173    int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
174    MCSymbol *Label = it->getLabel();
175
176    // At this point we want to emit/create the sequence to encode the delta in
177    // line numbers and the increment of the address from the previous Label
178    // and the current Label.
179    const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
180    MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
181                                   asmInfo->getPointerSize());
182
183    LastLine = it->getLine();
184    LastLabel = Label;
185  }
186
187  // Emit a DW_LNE_end_sequence for the end of the section.
188  // Using the pointer Section create a temporary label at the end of the
189  // section and use that and the LastLabel to compute the address delta
190  // and use INT64_MAX as the line delta which is the signal that this is
191  // actually a DW_LNE_end_sequence.
192
193  // Switch to the section to be able to create a symbol at its end.
194  // TODO: keep track of the last subsection so that this symbol appears in the
195  // correct place.
196  MCOS->SwitchSection(Section);
197
198  MCContext &context = MCOS->getContext();
199  // Create a symbol at the end of the section.
200  MCSymbol *SectionEnd = context.CreateTempSymbol();
201  // Set the value of the symbol, as we are at the end of the section.
202  MCOS->EmitLabel(SectionEnd);
203
204  // Switch back the dwarf line section.
205  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
206
207  const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
208  MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
209                                 asmInfo->getPointerSize());
210}
211
212//
213// This emits the Dwarf file and the line tables.
214//
215const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
216  MCContext &context = MCOS->getContext();
217  // Switch to the section where the table will be emitted into.
218  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
219
220  const DenseMap<unsigned, MCSymbol *> &MCLineTableSymbols =
221    MCOS->getContext().getMCLineTableSymbols();
222  // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does
223  // not exist, CUID will be 0 and MCLineTableSymbols will be empty.
224  // Handle Compile Unit 0, the line table start symbol is the section symbol.
225  const MCSymbol *LineStartSym = EmitCU(MCOS, 0);
226  // Handle the rest of the Compile Units.
227  for (unsigned Is = 1, Ie = MCLineTableSymbols.size(); Is < Ie; Is++)
228    EmitCU(MCOS, Is);
229
230  // Now delete the MCLineSections that were created in MCLineEntry::Make()
231  // and used to emit the line table.
232  const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
233    MCOS->getContext().getMCLineSections();
234  for (DenseMap<const MCSection *, MCLineSection *>::const_iterator it =
235       MCLineSections.begin(), ie = MCLineSections.end(); it != ie;
236       ++it)
237    delete it->second;
238
239  return LineStartSym;
240}
241
242const MCSymbol *MCDwarfFileTable::EmitCU(MCStreamer *MCOS, unsigned CUID) {
243  MCContext &context = MCOS->getContext();
244
245  // Create a symbol at the beginning of the line table.
246  MCSymbol *LineStartSym = MCOS->getContext().getMCLineTableSymbol(CUID);
247  if (!LineStartSym)
248    LineStartSym = context.CreateTempSymbol();
249  // Set the value of the symbol, as we are at the start of the line table.
250  MCOS->EmitLabel(LineStartSym);
251
252  // Create a symbol for the end of the section (to be set when we get there).
253  MCSymbol *LineEndSym = context.CreateTempSymbol();
254
255  // The first 4 bytes is the total length of the information for this
256  // compilation unit (not including these 4 bytes for the length).
257  MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
258                     4);
259
260  // Next 2 bytes is the Version, which is Dwarf 2.
261  MCOS->EmitIntValue(2, 2);
262
263  // Create a symbol for the end of the prologue (to be set when we get there).
264  MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
265
266  // Length of the prologue, is the next 4 bytes.  Which is the start of the
267  // section to the end of the prologue.  Not including the 4 bytes for the
268  // total length, the 2 bytes for the version, and these 4 bytes for the
269  // length of the prologue.
270  MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
271                                           (4 + 2 + 4)), 4);
272
273  // Parameters of the state machine, are next.
274  MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
275  MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
276  MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
277  MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
278  MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
279
280  // Standard opcode lengths
281  MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
282  MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
283  MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
284  MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
285  MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
286  MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
287  MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
288  MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
289  MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
290  MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
291  MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
292  MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
293
294  // Put out the directory and file tables.
295
296  // First the directory table.
297  const SmallVectorImpl<StringRef> &MCDwarfDirs =
298    context.getMCDwarfDirs(CUID);
299  for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
300    MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
301    MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
302  }
303  MCOS->EmitIntValue(0, 1); // Terminate the directory list
304
305  // Second the file table.
306  const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
307    MCOS->getContext().getMCDwarfFiles(CUID);
308  for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
309    MCOS->EmitBytes(MCDwarfFiles[i]->getName()); // FileName
310    MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
311    // the Directory num
312    MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
313    MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
314    MCOS->EmitIntValue(0, 1); // filesize (always 0)
315  }
316  MCOS->EmitIntValue(0, 1); // Terminate the file list
317
318  // This is the end of the prologue, so set the value of the symbol at the
319  // end of the prologue (that was used in a previous expression).
320  MCOS->EmitLabel(ProEndSym);
321
322  // Put out the line tables.
323  const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
324    MCOS->getContext().getMCLineSections();
325  const std::vector<const MCSection *> &MCLineSectionOrder =
326    MCOS->getContext().getMCLineSectionOrder();
327  for (std::vector<const MCSection*>::const_iterator it =
328         MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
329       ++it) {
330    const MCSection *Sec = *it;
331    const MCLineSection *Line = MCLineSections.lookup(Sec);
332    EmitDwarfLineTable(MCOS, Sec, Line, CUID);
333  }
334
335  if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines()
336      && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
337    // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
338    // it requires:
339    // total_length >= prologue_length + 10
340    // We are 4 bytes short, since we have total_length = 51 and
341    // prologue_length = 45
342
343    // The regular end_sequence should be sufficient.
344    MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
345  }
346
347  // This is the end of the section, so set the value of the symbol at the end
348  // of this section (that was used in a previous expression).
349  MCOS->EmitLabel(LineEndSym);
350
351  return LineStartSym;
352}
353
354/// Utility function to emit the encoding to a streamer.
355void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
356                           uint64_t AddrDelta) {
357  MCContext &Context = MCOS->getContext();
358  SmallString<256> Tmp;
359  raw_svector_ostream OS(Tmp);
360  MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
361  MCOS->EmitBytes(OS.str());
362}
363
364/// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
365void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
366                             uint64_t AddrDelta, raw_ostream &OS) {
367  uint64_t Temp, Opcode;
368  bool NeedCopy = false;
369
370  // Scale the address delta by the minimum instruction length.
371  AddrDelta = ScaleAddrDelta(Context, AddrDelta);
372
373  // A LineDelta of INT64_MAX is a signal that this is actually a
374  // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
375  // end_sequence to emit the matrix entry.
376  if (LineDelta == INT64_MAX) {
377    if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
378      OS << char(dwarf::DW_LNS_const_add_pc);
379    else {
380      OS << char(dwarf::DW_LNS_advance_pc);
381      encodeULEB128(AddrDelta, OS);
382    }
383    OS << char(dwarf::DW_LNS_extended_op);
384    OS << char(1);
385    OS << char(dwarf::DW_LNE_end_sequence);
386    return;
387  }
388
389  // Bias the line delta by the base.
390  Temp = LineDelta - DWARF2_LINE_BASE;
391
392  // If the line increment is out of range of a special opcode, we must encode
393  // it with DW_LNS_advance_line.
394  if (Temp >= DWARF2_LINE_RANGE) {
395    OS << char(dwarf::DW_LNS_advance_line);
396    encodeSLEB128(LineDelta, OS);
397
398    LineDelta = 0;
399    Temp = 0 - DWARF2_LINE_BASE;
400    NeedCopy = true;
401  }
402
403  // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
404  if (LineDelta == 0 && AddrDelta == 0) {
405    OS << char(dwarf::DW_LNS_copy);
406    return;
407  }
408
409  // Bias the opcode by the special opcode base.
410  Temp += DWARF2_LINE_OPCODE_BASE;
411
412  // Avoid overflow when addr_delta is large.
413  if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
414    // Try using a special opcode.
415    Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
416    if (Opcode <= 255) {
417      OS << char(Opcode);
418      return;
419    }
420
421    // Try using DW_LNS_const_add_pc followed by special op.
422    Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
423    if (Opcode <= 255) {
424      OS << char(dwarf::DW_LNS_const_add_pc);
425      OS << char(Opcode);
426      return;
427    }
428  }
429
430  // Otherwise use DW_LNS_advance_pc.
431  OS << char(dwarf::DW_LNS_advance_pc);
432  encodeULEB128(AddrDelta, OS);
433
434  if (NeedCopy)
435    OS << char(dwarf::DW_LNS_copy);
436  else
437    OS << char(Temp);
438}
439
440void MCDwarfFile::print(raw_ostream &OS) const {
441  OS << '"' << getName() << '"';
442}
443
444#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
445void MCDwarfFile::dump() const {
446  print(dbgs());
447}
448#endif
449
450// Utility function to write a tuple for .debug_abbrev.
451static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
452  MCOS->EmitULEB128IntValue(Name);
453  MCOS->EmitULEB128IntValue(Form);
454}
455
456// When generating dwarf for assembly source files this emits
457// the data for .debug_abbrev section which contains three DIEs.
458static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
459  MCContext &context = MCOS->getContext();
460  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
461
462  // DW_TAG_compile_unit DIE abbrev (1).
463  MCOS->EmitULEB128IntValue(1);
464  MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
465  MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
466  EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
467  EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
468  EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
469  EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
470  if (!context.getCompilationDir().empty())
471    EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
472  StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
473  if (!DwarfDebugFlags.empty())
474    EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
475  EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
476  EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
477  EmitAbbrev(MCOS, 0, 0);
478
479  // DW_TAG_label DIE abbrev (2).
480  MCOS->EmitULEB128IntValue(2);
481  MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
482  MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
483  EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
484  EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
485  EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
486  EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
487  EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
488  EmitAbbrev(MCOS, 0, 0);
489
490  // DW_TAG_unspecified_parameters DIE abbrev (3).
491  MCOS->EmitULEB128IntValue(3);
492  MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
493  MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
494  EmitAbbrev(MCOS, 0, 0);
495
496  // Terminate the abbreviations for this compilation unit.
497  MCOS->EmitIntValue(0, 1);
498}
499
500// When generating dwarf for assembly source files this emits the data for
501// .debug_aranges section.  Which contains a header and a table of pairs of
502// PointerSize'ed values for the address and size of section(s) with line table
503// entries (just the default .text in our case) and a terminating pair of zeros.
504static void EmitGenDwarfAranges(MCStreamer *MCOS,
505                                const MCSymbol *InfoSectionSymbol) {
506  MCContext &context = MCOS->getContext();
507
508  // Create a symbol at the end of the section that we are creating the dwarf
509  // debugging info to use later in here as part of the expression to calculate
510  // the size of the section for the table.
511  MCOS->SwitchSection(context.getGenDwarfSection());
512  MCSymbol *SectionEndSym = context.CreateTempSymbol();
513  MCOS->EmitLabel(SectionEndSym);
514  context.setGenDwarfSectionEndSym(SectionEndSym);
515
516  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
517
518  // This will be the length of the .debug_aranges section, first account for
519  // the size of each item in the header (see below where we emit these items).
520  int Length = 4 + 2 + 4 + 1 + 1;
521
522  // Figure the padding after the header before the table of address and size
523  // pairs who's values are PointerSize'ed.
524  const MCAsmInfo *asmInfo = context.getAsmInfo();
525  int AddrSize = asmInfo->getPointerSize();
526  int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
527  if (Pad == 2 * AddrSize)
528    Pad = 0;
529  Length += Pad;
530
531  // Add the size of the pair of PointerSize'ed values for the address and size
532  // of the one default .text section we have in the table.
533  Length += 2 * AddrSize;
534  // And the pair of terminating zeros.
535  Length += 2 * AddrSize;
536
537
538  // Emit the header for this section.
539  // The 4 byte length not including the 4 byte value for the length.
540  MCOS->EmitIntValue(Length - 4, 4);
541  // The 2 byte version, which is 2.
542  MCOS->EmitIntValue(2, 2);
543  // The 4 byte offset to the compile unit in the .debug_info from the start
544  // of the .debug_info.
545  if (InfoSectionSymbol)
546    MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
547  else
548    MCOS->EmitIntValue(0, 4);
549  // The 1 byte size of an address.
550  MCOS->EmitIntValue(AddrSize, 1);
551  // The 1 byte size of a segment descriptor, we use a value of zero.
552  MCOS->EmitIntValue(0, 1);
553  // Align the header with the padding if needed, before we put out the table.
554  for(int i = 0; i < Pad; i++)
555    MCOS->EmitIntValue(0, 1);
556
557  // Now emit the table of pairs of PointerSize'ed values for the section(s)
558  // address and size, in our case just the one default .text section.
559  const MCExpr *Addr = MCSymbolRefExpr::Create(
560    context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
561  const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
562    *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
563  MCOS->EmitAbsValue(Addr, AddrSize);
564  MCOS->EmitAbsValue(Size, AddrSize);
565
566  // And finally the pair of terminating zeros.
567  MCOS->EmitIntValue(0, AddrSize);
568  MCOS->EmitIntValue(0, AddrSize);
569}
570
571// When generating dwarf for assembly source files this emits the data for
572// .debug_info section which contains three parts.  The header, the compile_unit
573// DIE and a list of label DIEs.
574static void EmitGenDwarfInfo(MCStreamer *MCOS,
575                             const MCSymbol *AbbrevSectionSymbol,
576                             const MCSymbol *LineSectionSymbol) {
577  MCContext &context = MCOS->getContext();
578
579  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
580
581  // Create a symbol at the start and end of this section used in here for the
582  // expression to calculate the length in the header.
583  MCSymbol *InfoStart = context.CreateTempSymbol();
584  MCOS->EmitLabel(InfoStart);
585  MCSymbol *InfoEnd = context.CreateTempSymbol();
586
587  // First part: the header.
588
589  // The 4 byte total length of the information for this compilation unit, not
590  // including these 4 bytes.
591  const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
592  MCOS->EmitAbsValue(Length, 4);
593
594  // The 2 byte DWARF version, which is 2.
595  MCOS->EmitIntValue(2, 2);
596
597  // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
598  // it is at the start of that section so this is zero.
599  if (AbbrevSectionSymbol) {
600    MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
601  } else {
602    MCOS->EmitIntValue(0, 4);
603  }
604
605  const MCAsmInfo *asmInfo = context.getAsmInfo();
606  int AddrSize = asmInfo->getPointerSize();
607  // The 1 byte size of an address.
608  MCOS->EmitIntValue(AddrSize, 1);
609
610  // Second part: the compile_unit DIE.
611
612  // The DW_TAG_compile_unit DIE abbrev (1).
613  MCOS->EmitULEB128IntValue(1);
614
615  // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
616  // which is at the start of that section so this is zero.
617  if (LineSectionSymbol) {
618    MCOS->EmitSymbolValue(LineSectionSymbol, 4);
619  } else {
620    MCOS->EmitIntValue(0, 4);
621  }
622
623  // AT_low_pc, the first address of the default .text section.
624  const MCExpr *Start = MCSymbolRefExpr::Create(
625    context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
626  MCOS->EmitAbsValue(Start, AddrSize);
627
628  // AT_high_pc, the last address of the default .text section.
629  const MCExpr *End = MCSymbolRefExpr::Create(
630    context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
631  MCOS->EmitAbsValue(End, AddrSize);
632
633  // AT_name, the name of the source file.  Reconstruct from the first directory
634  // and file table entries.
635  const SmallVectorImpl<StringRef> &MCDwarfDirs =
636    context.getMCDwarfDirs();
637  if (MCDwarfDirs.size() > 0) {
638    MCOS->EmitBytes(MCDwarfDirs[0]);
639    MCOS->EmitBytes("/");
640  }
641  const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
642    MCOS->getContext().getMCDwarfFiles();
643  MCOS->EmitBytes(MCDwarfFiles[1]->getName());
644  MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
645
646  // AT_comp_dir, the working directory the assembly was done in.
647  if (!context.getCompilationDir().empty()) {
648    MCOS->EmitBytes(context.getCompilationDir());
649    MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
650  }
651
652  // AT_APPLE_flags, the command line arguments of the assembler tool.
653  StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
654  if (!DwarfDebugFlags.empty()){
655    MCOS->EmitBytes(DwarfDebugFlags);
656    MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
657  }
658
659  // AT_producer, the version of the assembler tool.
660  StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
661  if (!DwarfDebugProducer.empty()){
662    MCOS->EmitBytes(DwarfDebugProducer);
663  }
664  else {
665    MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
666    MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
667    MCOS->EmitBytes(StringRef(")"));
668  }
669  MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
670
671  // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dwarf2
672  // draft has no standard code for assembler.
673  MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
674
675  // Third part: the list of label DIEs.
676
677  // Loop on saved info for dwarf labels and create the DIEs for them.
678  const std::vector<const MCGenDwarfLabelEntry *> &Entries =
679    MCOS->getContext().getMCGenDwarfLabelEntries();
680  for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
681       Entries.begin(), ie = Entries.end(); it != ie;
682       ++it) {
683    const MCGenDwarfLabelEntry *Entry = *it;
684
685    // The DW_TAG_label DIE abbrev (2).
686    MCOS->EmitULEB128IntValue(2);
687
688    // AT_name, of the label without any leading underbar.
689    MCOS->EmitBytes(Entry->getName());
690    MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
691
692    // AT_decl_file, index into the file table.
693    MCOS->EmitIntValue(Entry->getFileNumber(), 4);
694
695    // AT_decl_line, source line number.
696    MCOS->EmitIntValue(Entry->getLineNumber(), 4);
697
698    // AT_low_pc, start address of the label.
699    const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
700                                             MCSymbolRefExpr::VK_None, context);
701    MCOS->EmitAbsValue(AT_low_pc, AddrSize);
702
703    // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
704    MCOS->EmitIntValue(0, 1);
705
706    // The DW_TAG_unspecified_parameters DIE abbrev (3).
707    MCOS->EmitULEB128IntValue(3);
708
709    // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
710    MCOS->EmitIntValue(0, 1);
711  }
712  // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
713  // for the dwarf labels.
714  for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
715       Entries.begin(), ie = Entries.end(); it != ie;
716       ++it) {
717    const MCGenDwarfLabelEntry *Entry = *it;
718    delete Entry;
719  }
720
721  // Add the NULL DIE terminating the Compile Unit DIE's.
722  MCOS->EmitIntValue(0, 1);
723
724  // Now set the value of the symbol at the end of the info section.
725  MCOS->EmitLabel(InfoEnd);
726}
727
728//
729// When generating dwarf for assembly source files this emits the Dwarf
730// sections.
731//
732void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
733  // Create the dwarf sections in this order (.debug_line already created).
734  MCContext &context = MCOS->getContext();
735  const MCAsmInfo *AsmInfo = context.getAsmInfo();
736  bool CreateDwarfSectionSymbols =
737      AsmInfo->doesDwarfUseRelocationsAcrossSections();
738  if (!CreateDwarfSectionSymbols)
739    LineSectionSymbol = NULL;
740  MCSymbol *AbbrevSectionSymbol = NULL;
741  MCSymbol *InfoSectionSymbol = NULL;
742  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
743  if (CreateDwarfSectionSymbols) {
744    InfoSectionSymbol = context.CreateTempSymbol();
745    MCOS->EmitLabel(InfoSectionSymbol);
746  }
747  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
748  if (CreateDwarfSectionSymbols) {
749    AbbrevSectionSymbol = context.CreateTempSymbol();
750    MCOS->EmitLabel(AbbrevSectionSymbol);
751  }
752  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
753
754  // If there are no line table entries then do not emit any section contents.
755  if (context.getMCLineSections().empty())
756    return;
757
758  // Output the data for .debug_aranges section.
759  EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
760
761  // Output the data for .debug_abbrev section.
762  EmitGenDwarfAbbrev(MCOS);
763
764  // Output the data for .debug_info section.
765  EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
766}
767
768//
769// When generating dwarf for assembly source files this is called when symbol
770// for a label is created.  If this symbol is not a temporary and is in the
771// section that dwarf is being generated for, save the needed info to create
772// a dwarf label.
773//
774void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
775                                     SourceMgr &SrcMgr, SMLoc &Loc) {
776  // We won't create dwarf labels for temporary symbols or symbols not in
777  // the default text.
778  if (Symbol->isTemporary())
779    return;
780  MCContext &context = MCOS->getContext();
781  if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
782    return;
783
784  // The dwarf label's name does not have the symbol name's leading
785  // underbar if any.
786  StringRef Name = Symbol->getName();
787  if (Name.startswith("_"))
788    Name = Name.substr(1, Name.size()-1);
789
790  // Get the dwarf file number to be used for the dwarf label.
791  unsigned FileNumber = context.getGenDwarfFileNumber();
792
793  // Finding the line number is the expensive part which is why we just don't
794  // pass it in as for some symbols we won't create a dwarf label.
795  int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
796  unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
797
798  // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
799  // values so that they don't have things like an ARM thumb bit from the
800  // original symbol. So when used they won't get a low bit set after
801  // relocation.
802  MCSymbol *Label = context.CreateTempSymbol();
803  MCOS->EmitLabel(Label);
804
805  // Create and entry for the info and add it to the other entries.
806  MCGenDwarfLabelEntry *Entry =
807    new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
808  MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
809}
810
811static int getDataAlignmentFactor(MCStreamer &streamer) {
812  MCContext &context = streamer.getContext();
813  const MCAsmInfo *asmInfo = context.getAsmInfo();
814  int size = asmInfo->getCalleeSaveStackSlotSize();
815  if (asmInfo->isStackGrowthDirectionUp())
816    return size;
817  else
818    return -size;
819}
820
821static unsigned getSizeForEncoding(MCStreamer &streamer,
822                                   unsigned symbolEncoding) {
823  MCContext &context = streamer.getContext();
824  unsigned format = symbolEncoding & 0x0f;
825  switch (format) {
826  default: llvm_unreachable("Unknown Encoding");
827  case dwarf::DW_EH_PE_absptr:
828  case dwarf::DW_EH_PE_signed:
829    return context.getAsmInfo()->getPointerSize();
830  case dwarf::DW_EH_PE_udata2:
831  case dwarf::DW_EH_PE_sdata2:
832    return 2;
833  case dwarf::DW_EH_PE_udata4:
834  case dwarf::DW_EH_PE_sdata4:
835    return 4;
836  case dwarf::DW_EH_PE_udata8:
837  case dwarf::DW_EH_PE_sdata8:
838    return 8;
839  }
840}
841
842static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
843                       unsigned symbolEncoding, bool isEH,
844                       const char *comment = 0) {
845  MCContext &context = streamer.getContext();
846  const MCAsmInfo *asmInfo = context.getAsmInfo();
847  const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
848                                                 symbolEncoding,
849                                                 streamer);
850  unsigned size = getSizeForEncoding(streamer, symbolEncoding);
851  if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
852  if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
853    streamer.EmitAbsValue(v, size);
854  else
855    streamer.EmitValue(v, size);
856}
857
858static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
859                            unsigned symbolEncoding) {
860  MCContext &context = streamer.getContext();
861  const MCAsmInfo *asmInfo = context.getAsmInfo();
862  const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
863                                                         symbolEncoding,
864                                                         streamer);
865  unsigned size = getSizeForEncoding(streamer, symbolEncoding);
866  streamer.EmitValue(v, size);
867}
868
869namespace {
870  class FrameEmitterImpl {
871    int CFAOffset;
872    int CIENum;
873    bool UsingCFI;
874    bool IsEH;
875    const MCSymbol *SectionStart;
876  public:
877    FrameEmitterImpl(bool usingCFI, bool isEH)
878      : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
879        SectionStart(0) {}
880
881    void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
882
883    /// EmitCompactUnwind - Emit the unwind information in a compact way.
884    void EmitCompactUnwind(MCStreamer &streamer,
885                           const MCDwarfFrameInfo &frame);
886
887    const MCSymbol &EmitCIE(MCStreamer &streamer,
888                            const MCSymbol *personality,
889                            unsigned personalityEncoding,
890                            const MCSymbol *lsda,
891                            bool IsSignalFrame,
892                            unsigned lsdaEncoding);
893    MCSymbol *EmitFDE(MCStreamer &streamer,
894                      const MCSymbol &cieStart,
895                      const MCDwarfFrameInfo &frame);
896    void EmitCFIInstructions(MCStreamer &streamer,
897                             ArrayRef<MCCFIInstruction> Instrs,
898                             MCSymbol *BaseLabel);
899    void EmitCFIInstruction(MCStreamer &Streamer,
900                            const MCCFIInstruction &Instr);
901  };
902
903} // end anonymous namespace
904
905static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
906                             StringRef Prefix) {
907  if (Streamer.isVerboseAsm()) {
908    const char *EncStr;
909    switch (Encoding) {
910    default: EncStr = "<unknown encoding>"; break;
911    case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
912    case dwarf::DW_EH_PE_omit:   EncStr = "omit"; break;
913    case dwarf::DW_EH_PE_pcrel:  EncStr = "pcrel"; break;
914    case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
915    case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
916    case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
917    case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
918    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
919      EncStr = "pcrel udata4";
920      break;
921    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
922      EncStr = "pcrel sdata4";
923      break;
924    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
925      EncStr = "pcrel udata8";
926      break;
927    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
928      EncStr = "screl sdata8";
929      break;
930    case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
931      EncStr = "indirect pcrel udata4";
932      break;
933    case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
934      EncStr = "indirect pcrel sdata4";
935      break;
936    case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
937      EncStr = "indirect pcrel udata8";
938      break;
939    case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
940      EncStr = "indirect pcrel sdata8";
941      break;
942    }
943
944    Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
945  }
946
947  Streamer.EmitIntValue(Encoding, 1);
948}
949
950void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
951                                          const MCCFIInstruction &Instr) {
952  int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
953  bool VerboseAsm = Streamer.isVerboseAsm();
954
955  switch (Instr.getOperation()) {
956  case MCCFIInstruction::OpRegister: {
957    unsigned Reg1 = Instr.getRegister();
958    unsigned Reg2 = Instr.getRegister2();
959    if (VerboseAsm) {
960      Streamer.AddComment("DW_CFA_register");
961      Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
962      Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
963    }
964    Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
965    Streamer.EmitULEB128IntValue(Reg1);
966    Streamer.EmitULEB128IntValue(Reg2);
967    return;
968  }
969  case MCCFIInstruction::OpWindowSave: {
970    Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
971    return;
972  }
973  case MCCFIInstruction::OpUndefined: {
974    unsigned Reg = Instr.getRegister();
975    if (VerboseAsm) {
976      Streamer.AddComment("DW_CFA_undefined");
977      Streamer.AddComment(Twine("Reg ") + Twine(Reg));
978    }
979    Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
980    Streamer.EmitULEB128IntValue(Reg);
981    return;
982  }
983  case MCCFIInstruction::OpAdjustCfaOffset:
984  case MCCFIInstruction::OpDefCfaOffset: {
985    const bool IsRelative =
986      Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
987
988    if (VerboseAsm)
989      Streamer.AddComment("DW_CFA_def_cfa_offset");
990    Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
991
992    if (IsRelative)
993      CFAOffset += Instr.getOffset();
994    else
995      CFAOffset = -Instr.getOffset();
996
997    if (VerboseAsm)
998      Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
999    Streamer.EmitULEB128IntValue(CFAOffset);
1000
1001    return;
1002  }
1003  case MCCFIInstruction::OpDefCfa: {
1004    if (VerboseAsm)
1005      Streamer.AddComment("DW_CFA_def_cfa");
1006    Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1007
1008    if (VerboseAsm)
1009      Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1010    Streamer.EmitULEB128IntValue(Instr.getRegister());
1011
1012    CFAOffset = -Instr.getOffset();
1013
1014    if (VerboseAsm)
1015      Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1016    Streamer.EmitULEB128IntValue(CFAOffset);
1017
1018    return;
1019  }
1020
1021  case MCCFIInstruction::OpDefCfaRegister: {
1022    if (VerboseAsm)
1023      Streamer.AddComment("DW_CFA_def_cfa_register");
1024    Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1025
1026    if (VerboseAsm)
1027      Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1028    Streamer.EmitULEB128IntValue(Instr.getRegister());
1029
1030    return;
1031  }
1032
1033  case MCCFIInstruction::OpOffset:
1034  case MCCFIInstruction::OpRelOffset: {
1035    const bool IsRelative =
1036      Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1037
1038    unsigned Reg = Instr.getRegister();
1039    int Offset = Instr.getOffset();
1040    if (IsRelative)
1041      Offset -= CFAOffset;
1042    Offset = Offset / dataAlignmentFactor;
1043
1044    if (Offset < 0) {
1045      if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1046      Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1047      if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1048      Streamer.EmitULEB128IntValue(Reg);
1049      if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1050      Streamer.EmitSLEB128IntValue(Offset);
1051    } else if (Reg < 64) {
1052      if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1053                                          Twine(Reg) + ")");
1054      Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1055      if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1056      Streamer.EmitULEB128IntValue(Offset);
1057    } else {
1058      if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1059      Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1060      if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1061      Streamer.EmitULEB128IntValue(Reg);
1062      if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1063      Streamer.EmitULEB128IntValue(Offset);
1064    }
1065    return;
1066  }
1067  case MCCFIInstruction::OpRememberState:
1068    if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1069    Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1070    return;
1071  case MCCFIInstruction::OpRestoreState:
1072    if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1073    Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1074    return;
1075  case MCCFIInstruction::OpSameValue: {
1076    unsigned Reg = Instr.getRegister();
1077    if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1078    Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1079    if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1080    Streamer.EmitULEB128IntValue(Reg);
1081    return;
1082  }
1083  case MCCFIInstruction::OpRestore: {
1084    unsigned Reg = Instr.getRegister();
1085    if (VerboseAsm) {
1086      Streamer.AddComment("DW_CFA_restore");
1087      Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1088    }
1089    Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1090    return;
1091  }
1092  case MCCFIInstruction::OpEscape:
1093    if (VerboseAsm) Streamer.AddComment("Escape bytes");
1094    Streamer.EmitBytes(Instr.getValues());
1095    return;
1096  }
1097  llvm_unreachable("Unhandled case in switch");
1098}
1099
1100/// EmitFrameMoves - Emit frame instructions to describe the layout of the
1101/// frame.
1102void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1103                                           ArrayRef<MCCFIInstruction> Instrs,
1104                                           MCSymbol *BaseLabel) {
1105  for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1106    const MCCFIInstruction &Instr = Instrs[i];
1107    MCSymbol *Label = Instr.getLabel();
1108    // Throw out move if the label is invalid.
1109    if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1110
1111    // Advance row if new location.
1112    if (BaseLabel && Label) {
1113      MCSymbol *ThisSym = Label;
1114      if (ThisSym != BaseLabel) {
1115        if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1116        streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1117        BaseLabel = ThisSym;
1118      }
1119    }
1120
1121    EmitCFIInstruction(streamer, Instr);
1122  }
1123}
1124
1125/// EmitCompactUnwind - Emit the unwind information in a compact way.
1126void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1127                                         const MCDwarfFrameInfo &Frame) {
1128  MCContext &Context = Streamer.getContext();
1129  const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1130  bool VerboseAsm = Streamer.isVerboseAsm();
1131
1132  // range-start range-length  compact-unwind-enc personality-func   lsda
1133  //  _foo       LfooEnd-_foo  0x00000023          0                 0
1134  //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
1135  //
1136  //   .section __LD,__compact_unwind,regular,debug
1137  //
1138  //   # compact unwind for _foo
1139  //   .quad _foo
1140  //   .set L1,LfooEnd-_foo
1141  //   .long L1
1142  //   .long 0x01010001
1143  //   .quad 0
1144  //   .quad 0
1145  //
1146  //   # compact unwind for _bar
1147  //   .quad _bar
1148  //   .set L2,LbarEnd-_bar
1149  //   .long L2
1150  //   .long 0x01020011
1151  //   .quad __gxx_personality
1152  //   .quad except_tab1
1153
1154  uint32_t Encoding = Frame.CompactUnwindEncoding;
1155  if (!Encoding) return;
1156  bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1157
1158  // The encoding needs to know we have an LSDA.
1159  if (!DwarfEHFrameOnly && Frame.Lsda)
1160    Encoding |= 0x40000000;
1161
1162  // Range Start
1163  unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1164  unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1165  if (VerboseAsm) Streamer.AddComment("Range Start");
1166  Streamer.EmitSymbolValue(Frame.Function, Size);
1167
1168  // Range Length
1169  const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1170                                              *Frame.End, 0);
1171  if (VerboseAsm) Streamer.AddComment("Range Length");
1172  Streamer.EmitAbsValue(Range, 4);
1173
1174  // Compact Encoding
1175  Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1176  if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1177                                      Twine::utohexstr(Encoding));
1178  Streamer.EmitIntValue(Encoding, Size);
1179
1180  // Personality Function
1181  Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1182  if (VerboseAsm) Streamer.AddComment("Personality Function");
1183  if (!DwarfEHFrameOnly && Frame.Personality)
1184    Streamer.EmitSymbolValue(Frame.Personality, Size);
1185  else
1186    Streamer.EmitIntValue(0, Size); // No personality fn
1187
1188  // LSDA
1189  Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1190  if (VerboseAsm) Streamer.AddComment("LSDA");
1191  if (!DwarfEHFrameOnly && Frame.Lsda)
1192    Streamer.EmitSymbolValue(Frame.Lsda, Size);
1193  else
1194    Streamer.EmitIntValue(0, Size); // No LSDA
1195}
1196
1197const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1198                                          const MCSymbol *personality,
1199                                          unsigned personalityEncoding,
1200                                          const MCSymbol *lsda,
1201                                          bool IsSignalFrame,
1202                                          unsigned lsdaEncoding) {
1203  MCContext &context = streamer.getContext();
1204  const MCRegisterInfo *MRI = context.getRegisterInfo();
1205  const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1206  bool verboseAsm = streamer.isVerboseAsm();
1207
1208  MCSymbol *sectionStart;
1209  if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1210    sectionStart = context.CreateTempSymbol();
1211  else
1212    sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1213
1214  streamer.EmitLabel(sectionStart);
1215  CIENum++;
1216
1217  MCSymbol *sectionEnd = context.CreateTempSymbol();
1218
1219  // Length
1220  const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1221                                               *sectionEnd, 4);
1222  if (verboseAsm) streamer.AddComment("CIE Length");
1223  streamer.EmitAbsValue(Length, 4);
1224
1225  // CIE ID
1226  unsigned CIE_ID = IsEH ? 0 : -1;
1227  if (verboseAsm) streamer.AddComment("CIE ID Tag");
1228  streamer.EmitIntValue(CIE_ID, 4);
1229
1230  // Version
1231  if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1232  streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1233
1234  // Augmentation String
1235  SmallString<8> Augmentation;
1236  if (IsEH) {
1237    if (verboseAsm) streamer.AddComment("CIE Augmentation");
1238    Augmentation += "z";
1239    if (personality)
1240      Augmentation += "P";
1241    if (lsda)
1242      Augmentation += "L";
1243    Augmentation += "R";
1244    if (IsSignalFrame)
1245      Augmentation += "S";
1246    streamer.EmitBytes(Augmentation.str());
1247  }
1248  streamer.EmitIntValue(0, 1);
1249
1250  // Code Alignment Factor
1251  if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1252  streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1253
1254  // Data Alignment Factor
1255  if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1256  streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1257
1258  // Return Address Register
1259  if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1260  streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1261
1262  // Augmentation Data Length (optional)
1263
1264  unsigned augmentationLength = 0;
1265  if (IsEH) {
1266    if (personality) {
1267      // Personality Encoding
1268      augmentationLength += 1;
1269      // Personality
1270      augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1271    }
1272    if (lsda)
1273      augmentationLength += 1;
1274    // Encoding of the FDE pointers
1275    augmentationLength += 1;
1276
1277    if (verboseAsm) streamer.AddComment("Augmentation Size");
1278    streamer.EmitULEB128IntValue(augmentationLength);
1279
1280    // Augmentation Data (optional)
1281    if (personality) {
1282      // Personality Encoding
1283      EmitEncodingByte(streamer, personalityEncoding,
1284                       "Personality Encoding");
1285      // Personality
1286      if (verboseAsm) streamer.AddComment("Personality");
1287      EmitPersonality(streamer, *personality, personalityEncoding);
1288    }
1289
1290    if (lsda)
1291      EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1292
1293    // Encoding of the FDE pointers
1294    EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1295                     "FDE Encoding");
1296  }
1297
1298  // Initial Instructions
1299
1300  const MCAsmInfo *MAI = context.getAsmInfo();
1301  const std::vector<MCCFIInstruction> &Instructions =
1302      MAI->getInitialFrameState();
1303  EmitCFIInstructions(streamer, Instructions, NULL);
1304
1305  // Padding
1306  streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1307
1308  streamer.EmitLabel(sectionEnd);
1309  return *sectionStart;
1310}
1311
1312MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1313                                    const MCSymbol &cieStart,
1314                                    const MCDwarfFrameInfo &frame) {
1315  MCContext &context = streamer.getContext();
1316  MCSymbol *fdeStart = context.CreateTempSymbol();
1317  MCSymbol *fdeEnd = context.CreateTempSymbol();
1318  const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1319  bool verboseAsm = streamer.isVerboseAsm();
1320
1321  if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1322    MCSymbol *EHSym =
1323      context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1324    streamer.EmitEHSymAttributes(frame.Function, EHSym);
1325    streamer.EmitLabel(EHSym);
1326  }
1327
1328  // Length
1329  const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1330  if (verboseAsm) streamer.AddComment("FDE Length");
1331  streamer.EmitAbsValue(Length, 4);
1332
1333  streamer.EmitLabel(fdeStart);
1334
1335  // CIE Pointer
1336  const MCAsmInfo *asmInfo = context.getAsmInfo();
1337  if (IsEH) {
1338    const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1339                                                 0);
1340    if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1341    streamer.EmitAbsValue(offset, 4);
1342  } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1343    const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1344                                                 cieStart, 0);
1345    streamer.EmitAbsValue(offset, 4);
1346  } else {
1347    streamer.EmitSymbolValue(&cieStart, 4);
1348  }
1349
1350  // PC Begin
1351  unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1352                             : (unsigned)dwarf::DW_EH_PE_absptr;
1353  unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1354  EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1355
1356  // PC Range
1357  const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1358                                              *frame.End, 0);
1359  if (verboseAsm) streamer.AddComment("FDE address range");
1360  streamer.EmitAbsValue(Range, PCSize);
1361
1362  if (IsEH) {
1363    // Augmentation Data Length
1364    unsigned augmentationLength = 0;
1365
1366    if (frame.Lsda)
1367      augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1368
1369    if (verboseAsm) streamer.AddComment("Augmentation size");
1370    streamer.EmitULEB128IntValue(augmentationLength);
1371
1372    // Augmentation Data
1373    if (frame.Lsda)
1374      EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1375                    "Language Specific Data Area");
1376  }
1377
1378  // Call Frame Instructions
1379  EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1380
1381  // Padding
1382  streamer.EmitValueToAlignment(PCSize);
1383
1384  return fdeEnd;
1385}
1386
1387namespace {
1388  struct CIEKey {
1389    static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false); }
1390    static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false); }
1391
1392    CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1393           unsigned LsdaEncoding_, bool IsSignalFrame_) :
1394      Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1395      LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_) {
1396    }
1397    const MCSymbol* Personality;
1398    unsigned PersonalityEncoding;
1399    unsigned LsdaEncoding;
1400    bool IsSignalFrame;
1401  };
1402}
1403
1404namespace llvm {
1405  template <>
1406  struct DenseMapInfo<CIEKey> {
1407    static CIEKey getEmptyKey() {
1408      return CIEKey::getEmptyKey();
1409    }
1410    static CIEKey getTombstoneKey() {
1411      return CIEKey::getTombstoneKey();
1412    }
1413    static unsigned getHashValue(const CIEKey &Key) {
1414      return static_cast<unsigned>(hash_combine(Key.Personality,
1415                                                Key.PersonalityEncoding,
1416                                                Key.LsdaEncoding,
1417                                                Key.IsSignalFrame));
1418    }
1419    static bool isEqual(const CIEKey &LHS,
1420                        const CIEKey &RHS) {
1421      return LHS.Personality == RHS.Personality &&
1422        LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1423        LHS.LsdaEncoding == RHS.LsdaEncoding &&
1424        LHS.IsSignalFrame == RHS.IsSignalFrame;
1425    }
1426  };
1427}
1428
1429void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1430                               bool UsingCFI, bool IsEH) {
1431  Streamer.generateCompactUnwindEncodings(MAB);
1432
1433  MCContext &Context = Streamer.getContext();
1434  const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1435  FrameEmitterImpl Emitter(UsingCFI, IsEH);
1436  ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1437
1438  // Emit the compact unwind info if available.
1439  if (IsEH && MOFI->getCompactUnwindSection()) {
1440    bool SectionEmitted = false;
1441    for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1442      const MCDwarfFrameInfo &Frame = FrameArray[i];
1443      if (Frame.CompactUnwindEncoding == 0) continue;
1444      if (!SectionEmitted) {
1445        Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1446        Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1447        SectionEmitted = true;
1448      }
1449      Emitter.EmitCompactUnwind(Streamer, Frame);
1450    }
1451  }
1452
1453  const MCSection &Section =
1454    IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1455           *MOFI->getDwarfFrameSection();
1456  Streamer.SwitchSection(&Section);
1457  MCSymbol *SectionStart = Context.CreateTempSymbol();
1458  Streamer.EmitLabel(SectionStart);
1459  Emitter.setSectionStart(SectionStart);
1460
1461  MCSymbol *FDEEnd = NULL;
1462  DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1463
1464  const MCSymbol *DummyDebugKey = NULL;
1465  for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1466    const MCDwarfFrameInfo &Frame = FrameArray[i];
1467    CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1468               Frame.LsdaEncoding, Frame.IsSignalFrame);
1469    const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1470    if (!CIEStart)
1471      CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1472                                  Frame.PersonalityEncoding, Frame.Lsda,
1473                                  Frame.IsSignalFrame,
1474                                  Frame.LsdaEncoding);
1475
1476    FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1477
1478    if (i != n - 1)
1479      Streamer.EmitLabel(FDEEnd);
1480  }
1481
1482  Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1483  if (FDEEnd)
1484    Streamer.EmitLabel(FDEEnd);
1485}
1486
1487void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1488                                         uint64_t AddrDelta) {
1489  MCContext &Context = Streamer.getContext();
1490  SmallString<256> Tmp;
1491  raw_svector_ostream OS(Tmp);
1492  MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1493  Streamer.EmitBytes(OS.str());
1494}
1495
1496void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1497                                           uint64_t AddrDelta,
1498                                           raw_ostream &OS) {
1499  // Scale the address delta by the minimum instruction length.
1500  AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1501
1502  if (AddrDelta == 0) {
1503  } else if (isUIntN(6, AddrDelta)) {
1504    uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1505    OS << Opcode;
1506  } else if (isUInt<8>(AddrDelta)) {
1507    OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1508    OS << uint8_t(AddrDelta);
1509  } else if (isUInt<16>(AddrDelta)) {
1510    // FIXME: check what is the correct behavior on a big endian machine.
1511    OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1512    OS << uint8_t( AddrDelta       & 0xff);
1513    OS << uint8_t((AddrDelta >> 8) & 0xff);
1514  } else {
1515    // FIXME: check what is the correct behavior on a big endian machine.
1516    assert(isUInt<32>(AddrDelta));
1517    OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1518    OS << uint8_t( AddrDelta        & 0xff);
1519    OS << uint8_t((AddrDelta >> 8)  & 0xff);
1520    OS << uint8_t((AddrDelta >> 16) & 0xff);
1521    OS << uint8_t((AddrDelta >> 24) & 0xff);
1522
1523  }
1524}
1525