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