OSDN Git Service

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