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