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