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