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