[MCJIT] Improve the "stub not found" diagnostic in RuntimeDyldChecker.
[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   if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
348       MCLineSections.getMCLineEntries().empty()) {
349     // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
350     // it requires:
351     // total_length >= prologue_length + 10
352     // We are 4 bytes short, since we have total_length = 51 and
353     // prologue_length = 45
354
355     // The regular end_sequence should be sufficient.
356     MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
357   }
358
359   // This is the end of the section, so set the value of the symbol at the end
360   // of this section (that was used in a previous expression).
361   MCOS->EmitLabel(LineEndSym);
362 }
363
364 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
365                                    unsigned FileNumber) {
366   return Header.getFile(Directory, FileName, FileNumber);
367 }
368
369 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
370                                          StringRef &FileName,
371                                          unsigned FileNumber) {
372   if (Directory == CompilationDir)
373     Directory = "";
374   if (FileName.empty()) {
375     FileName = "<stdin>";
376     Directory = "";
377   }
378   assert(!FileName.empty());
379   if (FileNumber == 0) {
380     FileNumber = SourceIdMap.size() + 1;
381     assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
382            "Don't mix autonumbered and explicit numbered line table usage");
383     StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(
384         (Directory + Twine('\0') + FileName).str(), FileNumber);
385     if (Ent.getValue() != FileNumber)
386       return Ent.getValue();
387   }
388   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
389   MCDwarfFiles.resize(FileNumber + 1);
390
391   // Get the new MCDwarfFile slot for this FileNumber.
392   MCDwarfFile &File = MCDwarfFiles[FileNumber];
393
394   // It is an error to use see the same number more than once.
395   if (!File.Name.empty())
396     return 0;
397
398   if (Directory.empty()) {
399     // Separate the directory part from the basename of the FileName.
400     StringRef tFileName = sys::path::filename(FileName);
401     if (!tFileName.empty()) {
402       Directory = sys::path::parent_path(FileName);
403       if (!Directory.empty())
404         FileName = tFileName;
405     }
406   }
407
408   // Find or make an entry in the MCDwarfDirs vector for this Directory.
409   // Capture directory name.
410   unsigned DirIndex;
411   if (Directory.empty()) {
412     // For FileNames with no directories a DirIndex of 0 is used.
413     DirIndex = 0;
414   } else {
415     DirIndex = 0;
416     for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
417       if (Directory == MCDwarfDirs[DirIndex])
418         break;
419     }
420     if (DirIndex >= MCDwarfDirs.size())
421       MCDwarfDirs.push_back(Directory);
422     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
423     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
424     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
425     // are stored at MCDwarfFiles[FileNumber].Name .
426     DirIndex++;
427   }
428
429   File.Name = FileName;
430   File.DirIndex = DirIndex;
431
432   // return the allocated FileNumber.
433   return FileNumber;
434 }
435
436 /// Utility function to emit the encoding to a streamer.
437 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
438                            uint64_t AddrDelta) {
439   MCContext &Context = MCOS->getContext();
440   SmallString<256> Tmp;
441   raw_svector_ostream OS(Tmp);
442   MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
443   MCOS->EmitBytes(OS.str());
444 }
445
446 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
447 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
448                              uint64_t AddrDelta, raw_ostream &OS) {
449   uint64_t Temp, Opcode;
450   bool NeedCopy = false;
451
452   // Scale the address delta by the minimum instruction length.
453   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
454
455   // A LineDelta of INT64_MAX is a signal that this is actually a
456   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
457   // end_sequence to emit the matrix entry.
458   if (LineDelta == INT64_MAX) {
459     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
460       OS << char(dwarf::DW_LNS_const_add_pc);
461     else {
462       OS << char(dwarf::DW_LNS_advance_pc);
463       encodeULEB128(AddrDelta, OS);
464     }
465     OS << char(dwarf::DW_LNS_extended_op);
466     OS << char(1);
467     OS << char(dwarf::DW_LNE_end_sequence);
468     return;
469   }
470
471   // Bias the line delta by the base.
472   Temp = LineDelta - DWARF2_LINE_BASE;
473
474   // If the line increment is out of range of a special opcode, we must encode
475   // it with DW_LNS_advance_line.
476   if (Temp >= DWARF2_LINE_RANGE) {
477     OS << char(dwarf::DW_LNS_advance_line);
478     encodeSLEB128(LineDelta, OS);
479
480     LineDelta = 0;
481     Temp = 0 - DWARF2_LINE_BASE;
482     NeedCopy = true;
483   }
484
485   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
486   if (LineDelta == 0 && AddrDelta == 0) {
487     OS << char(dwarf::DW_LNS_copy);
488     return;
489   }
490
491   // Bias the opcode by the special opcode base.
492   Temp += DWARF2_LINE_OPCODE_BASE;
493
494   // Avoid overflow when addr_delta is large.
495   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
496     // Try using a special opcode.
497     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
498     if (Opcode <= 255) {
499       OS << char(Opcode);
500       return;
501     }
502
503     // Try using DW_LNS_const_add_pc followed by special op.
504     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
505     if (Opcode <= 255) {
506       OS << char(dwarf::DW_LNS_const_add_pc);
507       OS << char(Opcode);
508       return;
509     }
510   }
511
512   // Otherwise use DW_LNS_advance_pc.
513   OS << char(dwarf::DW_LNS_advance_pc);
514   encodeULEB128(AddrDelta, OS);
515
516   if (NeedCopy)
517     OS << char(dwarf::DW_LNS_copy);
518   else
519     OS << char(Temp);
520 }
521
522 // Utility function to write a tuple for .debug_abbrev.
523 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
524   MCOS->EmitULEB128IntValue(Name);
525   MCOS->EmitULEB128IntValue(Form);
526 }
527
528 // When generating dwarf for assembly source files this emits
529 // the data for .debug_abbrev section which contains three DIEs.
530 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
531   MCContext &context = MCOS->getContext();
532   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
533
534   // DW_TAG_compile_unit DIE abbrev (1).
535   MCOS->EmitULEB128IntValue(1);
536   MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
537   MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
538   EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
539   if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1) {
540     EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
541   } else {
542     EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
543     EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
544   }
545   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
546   if (!context.getCompilationDir().empty())
547     EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
548   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
549   if (!DwarfDebugFlags.empty())
550     EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
551   EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
552   EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
553   EmitAbbrev(MCOS, 0, 0);
554
555   // DW_TAG_label DIE abbrev (2).
556   MCOS->EmitULEB128IntValue(2);
557   MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
558   MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
559   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
560   EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
561   EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
562   EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
563   EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
564   EmitAbbrev(MCOS, 0, 0);
565
566   // DW_TAG_unspecified_parameters DIE abbrev (3).
567   MCOS->EmitULEB128IntValue(3);
568   MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
569   MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
570   EmitAbbrev(MCOS, 0, 0);
571
572   // Terminate the abbreviations for this compilation unit.
573   MCOS->EmitIntValue(0, 1);
574 }
575
576 // When generating dwarf for assembly source files this emits the data for
577 // .debug_aranges section. This section contains a header and a table of pairs
578 // of PointerSize'ed values for the address and size of section(s) with line
579 // table entries.
580 static void EmitGenDwarfAranges(MCStreamer *MCOS,
581                                 const MCSymbol *InfoSectionSymbol) {
582   MCContext &context = MCOS->getContext();
583
584   auto &Sections = context.getGenDwarfSectionSyms();
585
586   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
587
588   // This will be the length of the .debug_aranges section, first account for
589   // the size of each item in the header (see below where we emit these items).
590   int Length = 4 + 2 + 4 + 1 + 1;
591
592   // Figure the padding after the header before the table of address and size
593   // pairs who's values are PointerSize'ed.
594   const MCAsmInfo *asmInfo = context.getAsmInfo();
595   int AddrSize = asmInfo->getPointerSize();
596   int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
597   if (Pad == 2 * AddrSize)
598     Pad = 0;
599   Length += Pad;
600
601   // Add the size of the pair of PointerSize'ed values for the address and size
602   // of each section we have in the table.
603   Length += 2 * AddrSize * Sections.size();
604   // And the pair of terminating zeros.
605   Length += 2 * AddrSize;
606
607
608   // Emit the header for this section.
609   // The 4 byte length not including the 4 byte value for the length.
610   MCOS->EmitIntValue(Length - 4, 4);
611   // The 2 byte version, which is 2.
612   MCOS->EmitIntValue(2, 2);
613   // The 4 byte offset to the compile unit in the .debug_info from the start
614   // of the .debug_info.
615   if (InfoSectionSymbol)
616     MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
617                           asmInfo->needsDwarfSectionOffsetDirective());
618   else
619     MCOS->EmitIntValue(0, 4);
620   // The 1 byte size of an address.
621   MCOS->EmitIntValue(AddrSize, 1);
622   // The 1 byte size of a segment descriptor, we use a value of zero.
623   MCOS->EmitIntValue(0, 1);
624   // Align the header with the padding if needed, before we put out the table.
625   for(int i = 0; i < Pad; i++)
626     MCOS->EmitIntValue(0, 1);
627
628   // Now emit the table of pairs of PointerSize'ed values for the section
629   // addresses and sizes.
630   for (const auto &sec : Sections) {
631     MCSymbol *StartSymbol = sec.second.first;
632     MCSymbol *EndSymbol = sec.second.second;
633     assert(StartSymbol && "StartSymbol must not be NULL");
634     assert(EndSymbol && "EndSymbol must not be NULL");
635
636     const MCExpr *Addr = MCSymbolRefExpr::Create(
637       StartSymbol, MCSymbolRefExpr::VK_None, context);
638     const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
639       *StartSymbol, *EndSymbol, 0);
640     MCOS->EmitValue(Addr, AddrSize);
641     emitAbsValue(*MCOS, Size, AddrSize);
642   }
643
644   // And finally the pair of terminating zeros.
645   MCOS->EmitIntValue(0, AddrSize);
646   MCOS->EmitIntValue(0, AddrSize);
647 }
648
649 // When generating dwarf for assembly source files this emits the data for
650 // .debug_info section which contains three parts.  The header, the compile_unit
651 // DIE and a list of label DIEs.
652 static void EmitGenDwarfInfo(MCStreamer *MCOS,
653                              const MCSymbol *AbbrevSectionSymbol,
654                              const MCSymbol *LineSectionSymbol,
655                              const MCSymbol *RangesSectionSymbol) {
656   MCContext &context = MCOS->getContext();
657
658   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
659
660   // Create a symbol at the start and end of this section used in here for the
661   // expression to calculate the length in the header.
662   MCSymbol *InfoStart = context.CreateTempSymbol();
663   MCOS->EmitLabel(InfoStart);
664   MCSymbol *InfoEnd = context.CreateTempSymbol();
665
666   // First part: the header.
667
668   // The 4 byte total length of the information for this compilation unit, not
669   // including these 4 bytes.
670   const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
671   emitAbsValue(*MCOS, Length, 4);
672
673   // The 2 byte DWARF version.
674   MCOS->EmitIntValue(context.getDwarfVersion(), 2);
675
676   const MCAsmInfo &AsmInfo = *context.getAsmInfo();
677   // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
678   // it is at the start of that section so this is zero.
679   if (AbbrevSectionSymbol == nullptr)
680     MCOS->EmitIntValue(0, 4);
681   else
682     MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
683                           AsmInfo.needsDwarfSectionOffsetDirective());
684
685   const MCAsmInfo *asmInfo = context.getAsmInfo();
686   int AddrSize = asmInfo->getPointerSize();
687   // The 1 byte size of an address.
688   MCOS->EmitIntValue(AddrSize, 1);
689
690   // Second part: the compile_unit DIE.
691
692   // The DW_TAG_compile_unit DIE abbrev (1).
693   MCOS->EmitULEB128IntValue(1);
694
695   // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
696   // which is at the start of that section so this is zero.
697   if (LineSectionSymbol)
698     MCOS->EmitSymbolValue(LineSectionSymbol, 4,
699                           AsmInfo.needsDwarfSectionOffsetDirective());
700   else
701     MCOS->EmitIntValue(0, 4);
702
703   if (RangesSectionSymbol) {
704     // There are multiple sections containing code, so we must use the
705     // .debug_ranges sections.
706
707     // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
708     // to the address range list for this compilation unit.
709     MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
710   } else {
711     // If we only have one non-empty code section, we can use the simpler
712     // AT_low_pc and AT_high_pc attributes.
713
714     // Find the first (and only) non-empty text section
715     auto &Sections = context.getGenDwarfSectionSyms();
716     const auto TextSection = Sections.begin();
717     assert(TextSection != Sections.end() && "No text section found");
718
719     MCSymbol *StartSymbol = TextSection->second.first;
720     MCSymbol *EndSymbol = TextSection->second.second;
721     assert(StartSymbol && "StartSymbol must not be NULL");
722     assert(EndSymbol && "EndSymbol must not be NULL");
723
724     // AT_low_pc, the first address of the default .text section.
725     const MCExpr *Start = MCSymbolRefExpr::Create(
726         StartSymbol, MCSymbolRefExpr::VK_None, context);
727     MCOS->EmitValue(Start, AddrSize);
728
729     // AT_high_pc, the last address of the default .text section.
730     const MCExpr *End = MCSymbolRefExpr::Create(
731       EndSymbol, MCSymbolRefExpr::VK_None, context);
732     MCOS->EmitValue(End, AddrSize);
733   }
734
735   // AT_name, the name of the source file.  Reconstruct from the first directory
736   // and file table entries.
737   const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
738   if (MCDwarfDirs.size() > 0) {
739     MCOS->EmitBytes(MCDwarfDirs[0]);
740     MCOS->EmitBytes(sys::path::get_separator());
741   }
742   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
743     MCOS->getContext().getMCDwarfFiles();
744   MCOS->EmitBytes(MCDwarfFiles[1].Name);
745   MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
746
747   // AT_comp_dir, the working directory the assembly was done in.
748   if (!context.getCompilationDir().empty()) {
749     MCOS->EmitBytes(context.getCompilationDir());
750     MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
751   }
752
753   // AT_APPLE_flags, the command line arguments of the assembler tool.
754   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
755   if (!DwarfDebugFlags.empty()){
756     MCOS->EmitBytes(DwarfDebugFlags);
757     MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
758   }
759
760   // AT_producer, the version of the assembler tool.
761   StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
762   if (!DwarfDebugProducer.empty())
763     MCOS->EmitBytes(DwarfDebugProducer);
764   else
765     MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
766   MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
767
768   // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dwarf2
769   // draft has no standard code for assembler.
770   MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
771
772   // Third part: the list of label DIEs.
773
774   // Loop on saved info for dwarf labels and create the DIEs for them.
775   const std::vector<MCGenDwarfLabelEntry> &Entries =
776       MCOS->getContext().getMCGenDwarfLabelEntries();
777   for (const auto &Entry : Entries) {
778     // The DW_TAG_label DIE abbrev (2).
779     MCOS->EmitULEB128IntValue(2);
780
781     // AT_name, of the label without any leading underbar.
782     MCOS->EmitBytes(Entry.getName());
783     MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
784
785     // AT_decl_file, index into the file table.
786     MCOS->EmitIntValue(Entry.getFileNumber(), 4);
787
788     // AT_decl_line, source line number.
789     MCOS->EmitIntValue(Entry.getLineNumber(), 4);
790
791     // AT_low_pc, start address of the label.
792     const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry.getLabel(),
793                                              MCSymbolRefExpr::VK_None, context);
794     MCOS->EmitValue(AT_low_pc, AddrSize);
795
796     // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
797     MCOS->EmitIntValue(0, 1);
798
799     // The DW_TAG_unspecified_parameters DIE abbrev (3).
800     MCOS->EmitULEB128IntValue(3);
801
802     // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
803     MCOS->EmitIntValue(0, 1);
804   }
805
806   // Add the NULL DIE terminating the Compile Unit DIE's.
807   MCOS->EmitIntValue(0, 1);
808
809   // Now set the value of the symbol at the end of the info section.
810   MCOS->EmitLabel(InfoEnd);
811 }
812
813 // When generating dwarf for assembly source files this emits the data for
814 // .debug_ranges section. We only emit one range list, which spans all of the
815 // executable sections of this file.
816 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
817   MCContext &context = MCOS->getContext();
818   auto &Sections = context.getGenDwarfSectionSyms();
819
820   const MCAsmInfo *AsmInfo = context.getAsmInfo();
821   int AddrSize = AsmInfo->getPointerSize();
822
823   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
824
825   for (const auto sec : Sections) {
826
827     MCSymbol *StartSymbol = sec.second.first;
828     MCSymbol *EndSymbol = sec.second.second;
829     assert(StartSymbol && "StartSymbol must not be NULL");
830     assert(EndSymbol && "EndSymbol must not be NULL");
831
832     // Emit a base address selection entry for the start of this section
833     const MCExpr *SectionStartAddr = MCSymbolRefExpr::Create(
834       StartSymbol, MCSymbolRefExpr::VK_None, context);
835     MCOS->EmitFill(AddrSize, 0xFF);
836     MCOS->EmitValue(SectionStartAddr, AddrSize);
837
838     // Emit a range list entry spanning this section
839     const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
840       *StartSymbol, *EndSymbol, 0);
841     MCOS->EmitIntValue(0, AddrSize);
842     emitAbsValue(*MCOS, SectionSize, AddrSize);
843   }
844
845   // Emit end of list entry
846   MCOS->EmitIntValue(0, AddrSize);
847   MCOS->EmitIntValue(0, AddrSize);
848 }
849
850 //
851 // When generating dwarf for assembly source files this emits the Dwarf
852 // sections.
853 //
854 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
855   MCContext &context = MCOS->getContext();
856
857   // Create the dwarf sections in this order (.debug_line already created).
858   const MCAsmInfo *AsmInfo = context.getAsmInfo();
859   bool CreateDwarfSectionSymbols =
860       AsmInfo->doesDwarfUseRelocationsAcrossSections();
861   MCSymbol *LineSectionSymbol = nullptr;
862   if (CreateDwarfSectionSymbols)
863     LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
864   MCSymbol *AbbrevSectionSymbol = nullptr;
865   MCSymbol *InfoSectionSymbol = nullptr;
866   MCSymbol *RangesSectionSymbol = NULL;
867
868   // Create end symbols for each section, and remove empty sections
869   MCOS->getContext().finalizeDwarfSections(*MCOS);
870
871   // If there are no sections to generate debug info for, we don't need
872   // to do anything
873   if (MCOS->getContext().getGenDwarfSectionSyms().empty())
874     return;
875
876   // We only need to use the .debug_ranges section if we have multiple
877   // code sections.
878   const bool UseRangesSection =
879       MCOS->getContext().getGenDwarfSectionSyms().size() > 1;
880   CreateDwarfSectionSymbols |= UseRangesSection;
881
882   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
883   if (CreateDwarfSectionSymbols) {
884     InfoSectionSymbol = context.CreateTempSymbol();
885     MCOS->EmitLabel(InfoSectionSymbol);
886   }
887   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
888   if (CreateDwarfSectionSymbols) {
889     AbbrevSectionSymbol = context.CreateTempSymbol();
890     MCOS->EmitLabel(AbbrevSectionSymbol);
891   }
892   if (UseRangesSection) {
893     MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
894     if (CreateDwarfSectionSymbols) {
895       RangesSectionSymbol = context.CreateTempSymbol();
896       MCOS->EmitLabel(RangesSectionSymbol);
897     }
898   }
899
900   assert((RangesSectionSymbol != NULL) || !UseRangesSection);
901
902   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
903
904   // Output the data for .debug_aranges section.
905   EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
906
907   if (UseRangesSection)
908     EmitGenDwarfRanges(MCOS);
909
910   // Output the data for .debug_abbrev section.
911   EmitGenDwarfAbbrev(MCOS);
912
913   // Output the data for .debug_info section.
914   EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
915                    RangesSectionSymbol);
916 }
917
918 //
919 // When generating dwarf for assembly source files this is called when symbol
920 // for a label is created.  If this symbol is not a temporary and is in the
921 // section that dwarf is being generated for, save the needed info to create
922 // a dwarf label.
923 //
924 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
925                                      SourceMgr &SrcMgr, SMLoc &Loc) {
926   // We won't create dwarf labels for temporary symbols.
927   if (Symbol->isTemporary())
928     return;
929   MCContext &context = MCOS->getContext();
930   // We won't create dwarf labels for symbols in sections that we are not
931   // generating debug info for.
932   if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
933     return;
934
935   // The dwarf label's name does not have the symbol name's leading
936   // underbar if any.
937   StringRef Name = Symbol->getName();
938   if (Name.startswith("_"))
939     Name = Name.substr(1, Name.size()-1);
940
941   // Get the dwarf file number to be used for the dwarf label.
942   unsigned FileNumber = context.getGenDwarfFileNumber();
943
944   // Finding the line number is the expensive part which is why we just don't
945   // pass it in as for some symbols we won't create a dwarf label.
946   unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
947   unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
948
949   // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
950   // values so that they don't have things like an ARM thumb bit from the
951   // original symbol. So when used they won't get a low bit set after
952   // relocation.
953   MCSymbol *Label = context.CreateTempSymbol();
954   MCOS->EmitLabel(Label);
955
956   // Create and entry for the info and add it to the other entries.
957   MCOS->getContext().addMCGenDwarfLabelEntry(
958       MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
959 }
960
961 static int getDataAlignmentFactor(MCStreamer &streamer) {
962   MCContext &context = streamer.getContext();
963   const MCAsmInfo *asmInfo = context.getAsmInfo();
964   int size = asmInfo->getCalleeSaveStackSlotSize();
965   if (asmInfo->isStackGrowthDirectionUp())
966     return size;
967   else
968     return -size;
969 }
970
971 static unsigned getSizeForEncoding(MCStreamer &streamer,
972                                    unsigned symbolEncoding) {
973   MCContext &context = streamer.getContext();
974   unsigned format = symbolEncoding & 0x0f;
975   switch (format) {
976   default: llvm_unreachable("Unknown Encoding");
977   case dwarf::DW_EH_PE_absptr:
978   case dwarf::DW_EH_PE_signed:
979     return context.getAsmInfo()->getPointerSize();
980   case dwarf::DW_EH_PE_udata2:
981   case dwarf::DW_EH_PE_sdata2:
982     return 2;
983   case dwarf::DW_EH_PE_udata4:
984   case dwarf::DW_EH_PE_sdata4:
985     return 4;
986   case dwarf::DW_EH_PE_udata8:
987   case dwarf::DW_EH_PE_sdata8:
988     return 8;
989   }
990 }
991
992 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
993                        unsigned symbolEncoding, bool isEH) {
994   MCContext &context = streamer.getContext();
995   const MCAsmInfo *asmInfo = context.getAsmInfo();
996   const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
997                                                  symbolEncoding,
998                                                  streamer);
999   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1000   if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1001     emitAbsValue(streamer, v, size);
1002   else
1003     streamer.EmitValue(v, size);
1004 }
1005
1006 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1007                             unsigned symbolEncoding) {
1008   MCContext &context = streamer.getContext();
1009   const MCAsmInfo *asmInfo = context.getAsmInfo();
1010   const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1011                                                          symbolEncoding,
1012                                                          streamer);
1013   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1014   streamer.EmitValue(v, size);
1015 }
1016
1017 namespace {
1018   class FrameEmitterImpl {
1019     int CFAOffset;
1020     bool IsEH;
1021     const MCSymbol *SectionStart;
1022   public:
1023     FrameEmitterImpl(bool isEH)
1024         : CFAOffset(0), IsEH(isEH), SectionStart(nullptr) {}
1025
1026     void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
1027
1028     /// Emit the unwind information in a compact way.
1029     void EmitCompactUnwind(MCObjectStreamer &streamer,
1030                            const MCDwarfFrameInfo &frame);
1031
1032     const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
1033                             const MCSymbol *personality,
1034                             unsigned personalityEncoding,
1035                             const MCSymbol *lsda,
1036                             bool IsSignalFrame,
1037                             unsigned lsdaEncoding,
1038                             bool IsSimple);
1039     MCSymbol *EmitFDE(MCObjectStreamer &streamer,
1040                       const MCSymbol &cieStart,
1041                       const MCDwarfFrameInfo &frame);
1042     void EmitCFIInstructions(MCObjectStreamer &streamer,
1043                              ArrayRef<MCCFIInstruction> Instrs,
1044                              MCSymbol *BaseLabel);
1045     void EmitCFIInstruction(MCObjectStreamer &Streamer,
1046                             const MCCFIInstruction &Instr);
1047   };
1048
1049 } // end anonymous namespace
1050
1051 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1052   Streamer.EmitIntValue(Encoding, 1);
1053 }
1054
1055 void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
1056                                           const MCCFIInstruction &Instr) {
1057   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1058
1059   switch (Instr.getOperation()) {
1060   case MCCFIInstruction::OpRegister: {
1061     unsigned Reg1 = Instr.getRegister();
1062     unsigned Reg2 = Instr.getRegister2();
1063     Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1064     Streamer.EmitULEB128IntValue(Reg1);
1065     Streamer.EmitULEB128IntValue(Reg2);
1066     return;
1067   }
1068   case MCCFIInstruction::OpWindowSave: {
1069     Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1070     return;
1071   }
1072   case MCCFIInstruction::OpUndefined: {
1073     unsigned Reg = Instr.getRegister();
1074     Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1075     Streamer.EmitULEB128IntValue(Reg);
1076     return;
1077   }
1078   case MCCFIInstruction::OpAdjustCfaOffset:
1079   case MCCFIInstruction::OpDefCfaOffset: {
1080     const bool IsRelative =
1081       Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1082
1083     Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1084
1085     if (IsRelative)
1086       CFAOffset += Instr.getOffset();
1087     else
1088       CFAOffset = -Instr.getOffset();
1089
1090     Streamer.EmitULEB128IntValue(CFAOffset);
1091
1092     return;
1093   }
1094   case MCCFIInstruction::OpDefCfa: {
1095     Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1096     Streamer.EmitULEB128IntValue(Instr.getRegister());
1097     CFAOffset = -Instr.getOffset();
1098     Streamer.EmitULEB128IntValue(CFAOffset);
1099
1100     return;
1101   }
1102
1103   case MCCFIInstruction::OpDefCfaRegister: {
1104     Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1105     Streamer.EmitULEB128IntValue(Instr.getRegister());
1106
1107     return;
1108   }
1109
1110   case MCCFIInstruction::OpOffset:
1111   case MCCFIInstruction::OpRelOffset: {
1112     const bool IsRelative =
1113       Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1114
1115     unsigned Reg = Instr.getRegister();
1116     int Offset = Instr.getOffset();
1117     if (IsRelative)
1118       Offset -= CFAOffset;
1119     Offset = Offset / dataAlignmentFactor;
1120
1121     if (Offset < 0) {
1122       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1123       Streamer.EmitULEB128IntValue(Reg);
1124       Streamer.EmitSLEB128IntValue(Offset);
1125     } else if (Reg < 64) {
1126       Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1127       Streamer.EmitULEB128IntValue(Offset);
1128     } else {
1129       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1130       Streamer.EmitULEB128IntValue(Reg);
1131       Streamer.EmitULEB128IntValue(Offset);
1132     }
1133     return;
1134   }
1135   case MCCFIInstruction::OpRememberState:
1136     Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1137     return;
1138   case MCCFIInstruction::OpRestoreState:
1139     Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1140     return;
1141   case MCCFIInstruction::OpSameValue: {
1142     unsigned Reg = Instr.getRegister();
1143     Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1144     Streamer.EmitULEB128IntValue(Reg);
1145     return;
1146   }
1147   case MCCFIInstruction::OpRestore: {
1148     unsigned Reg = Instr.getRegister();
1149     Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1150     return;
1151   }
1152   case MCCFIInstruction::OpEscape:
1153     Streamer.EmitBytes(Instr.getValues());
1154     return;
1155   }
1156   llvm_unreachable("Unhandled case in switch");
1157 }
1158
1159 /// Emit frame instructions to describe the layout of the frame.
1160 void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
1161                                            ArrayRef<MCCFIInstruction> Instrs,
1162                                            MCSymbol *BaseLabel) {
1163   for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1164     const MCCFIInstruction &Instr = Instrs[i];
1165     MCSymbol *Label = Instr.getLabel();
1166     // Throw out move if the label is invalid.
1167     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1168
1169     // Advance row if new location.
1170     if (BaseLabel && Label) {
1171       MCSymbol *ThisSym = Label;
1172       if (ThisSym != BaseLabel) {
1173         streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1174         BaseLabel = ThisSym;
1175       }
1176     }
1177
1178     EmitCFIInstruction(streamer, Instr);
1179   }
1180 }
1181
1182 /// Emit the unwind information in a compact way.
1183 void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
1184                                          const MCDwarfFrameInfo &Frame) {
1185   MCContext &Context = Streamer.getContext();
1186   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1187
1188   // range-start range-length  compact-unwind-enc personality-func   lsda
1189   //  _foo       LfooEnd-_foo  0x00000023          0                 0
1190   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
1191   //
1192   //   .section __LD,__compact_unwind,regular,debug
1193   //
1194   //   # compact unwind for _foo
1195   //   .quad _foo
1196   //   .set L1,LfooEnd-_foo
1197   //   .long L1
1198   //   .long 0x01010001
1199   //   .quad 0
1200   //   .quad 0
1201   //
1202   //   # compact unwind for _bar
1203   //   .quad _bar
1204   //   .set L2,LbarEnd-_bar
1205   //   .long L2
1206   //   .long 0x01020011
1207   //   .quad __gxx_personality
1208   //   .quad except_tab1
1209
1210   uint32_t Encoding = Frame.CompactUnwindEncoding;
1211   if (!Encoding) return;
1212   bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1213
1214   // The encoding needs to know we have an LSDA.
1215   if (!DwarfEHFrameOnly && Frame.Lsda)
1216     Encoding |= 0x40000000;
1217
1218   // Range Start
1219   unsigned FDEEncoding = MOFI->getFDEEncoding();
1220   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1221   Streamer.EmitSymbolValue(Frame.Begin, Size);
1222
1223   // Range Length
1224   const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1225                                               *Frame.End, 0);
1226   emitAbsValue(Streamer, Range, 4);
1227
1228   // Compact Encoding
1229   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1230   Streamer.EmitIntValue(Encoding, Size);
1231
1232   // Personality Function
1233   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1234   if (!DwarfEHFrameOnly && Frame.Personality)
1235     Streamer.EmitSymbolValue(Frame.Personality, Size);
1236   else
1237     Streamer.EmitIntValue(0, Size); // No personality fn
1238
1239   // LSDA
1240   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1241   if (!DwarfEHFrameOnly && Frame.Lsda)
1242     Streamer.EmitSymbolValue(Frame.Lsda, Size);
1243   else
1244     Streamer.EmitIntValue(0, Size); // No LSDA
1245 }
1246
1247 const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
1248                                           const MCSymbol *personality,
1249                                           unsigned personalityEncoding,
1250                                           const MCSymbol *lsda,
1251                                           bool IsSignalFrame,
1252                                           unsigned lsdaEncoding,
1253                                           bool IsSimple) {
1254   MCContext &context = streamer.getContext();
1255   const MCRegisterInfo *MRI = context.getRegisterInfo();
1256   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1257
1258   MCSymbol *sectionStart = context.CreateTempSymbol();
1259   streamer.EmitLabel(sectionStart);
1260
1261   MCSymbol *sectionEnd = context.CreateTempSymbol();
1262
1263   // Length
1264   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1265                                                *sectionEnd, 4);
1266   emitAbsValue(streamer, Length, 4);
1267
1268   // CIE ID
1269   unsigned CIE_ID = IsEH ? 0 : -1;
1270   streamer.EmitIntValue(CIE_ID, 4);
1271
1272   // Version
1273   // For DWARF2, we use CIE version 1
1274   // For DWARF3+, we use CIE version 3
1275   uint8_t CIEVersion = context.getDwarfVersion() <= 2 ? 1 : 3;
1276   streamer.EmitIntValue(CIEVersion, 1);
1277
1278   // Augmentation String
1279   SmallString<8> Augmentation;
1280   if (IsEH) {
1281     Augmentation += "z";
1282     if (personality)
1283       Augmentation += "P";
1284     if (lsda)
1285       Augmentation += "L";
1286     Augmentation += "R";
1287     if (IsSignalFrame)
1288       Augmentation += "S";
1289     streamer.EmitBytes(Augmentation.str());
1290   }
1291   streamer.EmitIntValue(0, 1);
1292
1293   // Code Alignment Factor
1294   streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1295
1296   // Data Alignment Factor
1297   streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1298
1299   // Return Address Register
1300   if (CIEVersion == 1) {
1301     assert(MRI->getRARegister() <= 255 &&
1302            "DWARF 2 encodes return_address_register in one byte");
1303     streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true), 1);
1304   } else {
1305     streamer.EmitULEB128IntValue(
1306         MRI->getDwarfRegNum(MRI->getRARegister(), true));
1307   }
1308
1309   // Augmentation Data Length (optional)
1310
1311   unsigned augmentationLength = 0;
1312   if (IsEH) {
1313     if (personality) {
1314       // Personality Encoding
1315       augmentationLength += 1;
1316       // Personality
1317       augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1318     }
1319     if (lsda)
1320       augmentationLength += 1;
1321     // Encoding of the FDE pointers
1322     augmentationLength += 1;
1323
1324     streamer.EmitULEB128IntValue(augmentationLength);
1325
1326     // Augmentation Data (optional)
1327     if (personality) {
1328       // Personality Encoding
1329       emitEncodingByte(streamer, personalityEncoding);
1330       // Personality
1331       EmitPersonality(streamer, *personality, personalityEncoding);
1332     }
1333
1334     if (lsda)
1335       emitEncodingByte(streamer, lsdaEncoding);
1336
1337     // Encoding of the FDE pointers
1338     emitEncodingByte(streamer, MOFI->getFDEEncoding());
1339   }
1340
1341   // Initial Instructions
1342
1343   const MCAsmInfo *MAI = context.getAsmInfo();
1344   if (!IsSimple) {
1345     const std::vector<MCCFIInstruction> &Instructions =
1346         MAI->getInitialFrameState();
1347     EmitCFIInstructions(streamer, Instructions, nullptr);
1348   }
1349
1350   // Padding
1351   streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1352
1353   streamer.EmitLabel(sectionEnd);
1354   return *sectionStart;
1355 }
1356
1357 MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
1358                                     const MCSymbol &cieStart,
1359                                     const MCDwarfFrameInfo &frame) {
1360   MCContext &context = streamer.getContext();
1361   MCSymbol *fdeStart = context.CreateTempSymbol();
1362   MCSymbol *fdeEnd = context.CreateTempSymbol();
1363   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1364
1365   // Length
1366   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1367   emitAbsValue(streamer, Length, 4);
1368
1369   streamer.EmitLabel(fdeStart);
1370
1371   // CIE Pointer
1372   const MCAsmInfo *asmInfo = context.getAsmInfo();
1373   if (IsEH) {
1374     const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1375                                                  0);
1376     emitAbsValue(streamer, offset, 4);
1377   } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1378     const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1379                                                  cieStart, 0);
1380     emitAbsValue(streamer, offset, 4);
1381   } else {
1382     streamer.EmitSymbolValue(&cieStart, 4);
1383   }
1384
1385   // PC Begin
1386   unsigned PCEncoding =
1387       IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1388   unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1389   emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
1390
1391   // PC Range
1392   const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1393                                               *frame.End, 0);
1394   emitAbsValue(streamer, Range, PCSize);
1395
1396   if (IsEH) {
1397     // Augmentation Data Length
1398     unsigned augmentationLength = 0;
1399
1400     if (frame.Lsda)
1401       augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1402
1403     streamer.EmitULEB128IntValue(augmentationLength);
1404
1405     // Augmentation Data
1406     if (frame.Lsda)
1407       emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
1408   }
1409
1410   // Call Frame Instructions
1411   EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1412
1413   // Padding
1414   streamer.EmitValueToAlignment(PCSize);
1415
1416   return fdeEnd;
1417 }
1418
1419 namespace {
1420   struct CIEKey {
1421     static const CIEKey getEmptyKey() {
1422       return CIEKey(nullptr, 0, -1, false, false);
1423     }
1424     static const CIEKey getTombstoneKey() {
1425       return CIEKey(nullptr, -1, 0, false, false);
1426     }
1427
1428     CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
1429            unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
1430         : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1431           LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1432           IsSimple(IsSimple_) {}
1433     const MCSymbol *Personality;
1434     unsigned PersonalityEncoding;
1435     unsigned LsdaEncoding;
1436     bool IsSignalFrame;
1437     bool IsSimple;
1438   };
1439 }
1440
1441 namespace llvm {
1442   template <>
1443   struct DenseMapInfo<CIEKey> {
1444     static CIEKey getEmptyKey() {
1445       return CIEKey::getEmptyKey();
1446     }
1447     static CIEKey getTombstoneKey() {
1448       return CIEKey::getTombstoneKey();
1449     }
1450     static unsigned getHashValue(const CIEKey &Key) {
1451       return static_cast<unsigned>(hash_combine(Key.Personality,
1452                                                 Key.PersonalityEncoding,
1453                                                 Key.LsdaEncoding,
1454                                                 Key.IsSignalFrame,
1455                                                 Key.IsSimple));
1456     }
1457     static bool isEqual(const CIEKey &LHS,
1458                         const CIEKey &RHS) {
1459       return LHS.Personality == RHS.Personality &&
1460         LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1461         LHS.LsdaEncoding == RHS.LsdaEncoding &&
1462         LHS.IsSignalFrame == RHS.IsSignalFrame &&
1463         LHS.IsSimple == RHS.IsSimple;
1464     }
1465   };
1466 }
1467
1468 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1469                                bool IsEH) {
1470   Streamer.generateCompactUnwindEncodings(MAB);
1471
1472   MCContext &Context = Streamer.getContext();
1473   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1474   FrameEmitterImpl Emitter(IsEH);
1475   ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1476
1477   // Emit the compact unwind info if available.
1478   bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1479   if (IsEH && MOFI->getCompactUnwindSection()) {
1480     bool SectionEmitted = false;
1481     for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1482       const MCDwarfFrameInfo &Frame = FrameArray[i];
1483       if (Frame.CompactUnwindEncoding == 0) continue;
1484       if (!SectionEmitted) {
1485         Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1486         Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1487         SectionEmitted = true;
1488       }
1489       NeedsEHFrameSection |=
1490         Frame.CompactUnwindEncoding ==
1491           MOFI->getCompactUnwindDwarfEHFrameOnly();
1492       Emitter.EmitCompactUnwind(Streamer, Frame);
1493     }
1494   }
1495
1496   if (!NeedsEHFrameSection) return;
1497
1498   const MCSection &Section =
1499     IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1500            *MOFI->getDwarfFrameSection();
1501
1502   Streamer.SwitchSection(&Section);
1503   MCSymbol *SectionStart = Context.CreateTempSymbol();
1504   Streamer.EmitLabel(SectionStart);
1505   Emitter.setSectionStart(SectionStart);
1506
1507   MCSymbol *FDEEnd = nullptr;
1508   DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1509
1510   const MCSymbol *DummyDebugKey = nullptr;
1511   NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1512   for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1513     const MCDwarfFrameInfo &Frame = FrameArray[i];
1514
1515     // Emit the label from the previous iteration
1516     if (FDEEnd) {
1517       Streamer.EmitLabel(FDEEnd);
1518       FDEEnd = nullptr;
1519     }
1520
1521     if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1522           MOFI->getCompactUnwindDwarfEHFrameOnly())
1523       // Don't generate an EH frame if we don't need one. I.e., it's taken care
1524       // of by the compact unwind encoding.
1525       continue;
1526
1527     CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1528                Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1529     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1530     if (!CIEStart)
1531       CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1532                                   Frame.PersonalityEncoding, Frame.Lsda,
1533                                   Frame.IsSignalFrame,
1534                                   Frame.LsdaEncoding,
1535                                   Frame.IsSimple);
1536
1537     FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1538   }
1539
1540   Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1541   if (FDEEnd)
1542     Streamer.EmitLabel(FDEEnd);
1543 }
1544
1545 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1546                                          uint64_t AddrDelta) {
1547   MCContext &Context = Streamer.getContext();
1548   SmallString<256> Tmp;
1549   raw_svector_ostream OS(Tmp);
1550   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1551   Streamer.EmitBytes(OS.str());
1552 }
1553
1554 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1555                                            uint64_t AddrDelta,
1556                                            raw_ostream &OS) {
1557   // Scale the address delta by the minimum instruction length.
1558   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1559
1560   if (AddrDelta == 0) {
1561   } else if (isUIntN(6, AddrDelta)) {
1562     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1563     OS << Opcode;
1564   } else if (isUInt<8>(AddrDelta)) {
1565     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1566     OS << uint8_t(AddrDelta);
1567   } else if (isUInt<16>(AddrDelta)) {
1568     // FIXME: check what is the correct behavior on a big endian machine.
1569     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1570     OS << uint8_t( AddrDelta       & 0xff);
1571     OS << uint8_t((AddrDelta >> 8) & 0xff);
1572   } else {
1573     // FIXME: check what is the correct behavior on a big endian machine.
1574     assert(isUInt<32>(AddrDelta));
1575     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1576     OS << uint8_t( AddrDelta        & 0xff);
1577     OS << uint8_t((AddrDelta >> 8)  & 0xff);
1578     OS << uint8_t((AddrDelta >> 16) & 0xff);
1579     OS << uint8_t((AddrDelta >> 24) & 0xff);
1580
1581   }
1582 }