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