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