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