xref: /llvm-project-15.0.7/llvm/lib/MC/MCDwarf.cpp (revision 55a32812)
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   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
478 
479   MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");
480 
481   // Next 2 bytes is the Version.
482   unsigned LineTableVersion = context.getDwarfVersion();
483   MCOS->emitInt16(LineTableVersion);
484 
485   // In v5, we get address info next.
486   if (LineTableVersion >= 5) {
487     MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
488     MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.
489   }
490 
491   MCSymbol *ProStartSym = context.createTempSymbol();
492 
493   // Create a symbol for the end of the prologue (to be set when we get there).
494   MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
495 
496   // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
497   // actually the length from after the length word, to the end of the prologue.
498   MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);
499 
500   MCOS->emitLabel(ProStartSym);
501 
502   // Parameters of the state machine, are next.
503   MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
504   // maximum_operations_per_instruction
505   // For non-VLIW architectures this field is always 1.
506   // FIXME: VLIW architectures need to update this field accordingly.
507   if (LineTableVersion >= 4)
508     MCOS->emitInt8(1);
509   MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
510   MCOS->emitInt8(Params.DWARF2LineBase);
511   MCOS->emitInt8(Params.DWARF2LineRange);
512   MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
513 
514   // Standard opcode lengths
515   for (char Length : StandardOpcodeLengths)
516     MCOS->emitInt8(Length);
517 
518   // Put out the directory and file tables.  The formats vary depending on
519   // the version.
520   if (LineTableVersion >= 5)
521     emitV5FileDirTables(MCOS, LineStr);
522   else
523     emitV2FileDirTables(MCOS);
524 
525   // This is the end of the prologue, so set the value of the symbol at the
526   // end of the prologue (that was used in a previous expression).
527   MCOS->emitLabel(ProEndSym);
528 
529   return std::make_pair(LineStartSym, LineEndSym);
530 }
531 
532 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS,
533                               MCDwarfLineTableParams Params,
534                               Optional<MCDwarfLineStr> &LineStr) const {
535   MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
536 
537   // Put out the line tables.
538   for (const auto &LineSec : MCLineSections.getMCLineEntries())
539     emitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
540 
541   // This is the end of the section, so set the value of the symbol at the end
542   // of this section (that was used in a previous expression).
543   MCOS->emitLabel(LineEndSym);
544 }
545 
546 Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory,
547                                                 StringRef &FileName,
548                                                 Optional<MD5::MD5Result> Checksum,
549                                                 Optional<StringRef> Source,
550                                                 uint16_t DwarfVersion,
551                                                 unsigned FileNumber) {
552   return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
553                            FileNumber);
554 }
555 
556 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
557                        StringRef &FileName, Optional<MD5::MD5Result> Checksum) {
558   if (RootFile.Name.empty() || RootFile.Name != FileName.data())
559     return false;
560   return RootFile.Checksum == Checksum;
561 }
562 
563 Expected<unsigned>
564 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory,
565                                    StringRef &FileName,
566                                    Optional<MD5::MD5Result> Checksum,
567                                    Optional<StringRef> Source,
568                                    uint16_t DwarfVersion,
569                                    unsigned FileNumber) {
570   if (Directory == CompilationDir)
571     Directory = "";
572   if (FileName.empty()) {
573     FileName = "<stdin>";
574     Directory = "";
575   }
576   assert(!FileName.empty());
577   // Keep track of whether any or all files have an MD5 checksum.
578   // If any files have embedded source, they all must.
579   if (MCDwarfFiles.empty()) {
580     trackMD5Usage(Checksum.hasValue());
581     HasSource = (Source != None);
582   }
583   if (isRootFile(RootFile, Directory, FileName, Checksum) && DwarfVersion >= 5)
584     return 0;
585   if (FileNumber == 0) {
586     // File numbers start with 1 and/or after any file numbers
587     // allocated by inline-assembler .file directives.
588     FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
589     SmallString<256> Buffer;
590     auto IterBool = SourceIdMap.insert(
591         std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
592                        FileNumber));
593     if (!IterBool.second)
594       return IterBool.first->second;
595   }
596   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
597   if (FileNumber >= MCDwarfFiles.size())
598     MCDwarfFiles.resize(FileNumber + 1);
599 
600   // Get the new MCDwarfFile slot for this FileNumber.
601   MCDwarfFile &File = MCDwarfFiles[FileNumber];
602 
603   // It is an error to see the same number more than once.
604   if (!File.Name.empty())
605     return make_error<StringError>("file number already allocated",
606                                    inconvertibleErrorCode());
607 
608   // If any files have embedded source, they all must.
609   if (HasSource != (Source != None))
610     return make_error<StringError>("inconsistent use of embedded source",
611                                    inconvertibleErrorCode());
612 
613   if (Directory.empty()) {
614     // Separate the directory part from the basename of the FileName.
615     StringRef tFileName = sys::path::filename(FileName);
616     if (!tFileName.empty()) {
617       Directory = sys::path::parent_path(FileName);
618       if (!Directory.empty())
619         FileName = tFileName;
620     }
621   }
622 
623   // Find or make an entry in the MCDwarfDirs vector for this Directory.
624   // Capture directory name.
625   unsigned DirIndex;
626   if (Directory.empty()) {
627     // For FileNames with no directories a DirIndex of 0 is used.
628     DirIndex = 0;
629   } else {
630     DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
631     if (DirIndex >= MCDwarfDirs.size())
632       MCDwarfDirs.push_back(std::string(Directory));
633     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
634     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
635     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
636     // are stored at MCDwarfFiles[FileNumber].Name .
637     DirIndex++;
638   }
639 
640   File.Name = std::string(FileName);
641   File.DirIndex = DirIndex;
642   File.Checksum = Checksum;
643   trackMD5Usage(Checksum.hasValue());
644   File.Source = Source;
645   if (Source)
646     HasSource = true;
647 
648   // return the allocated FileNumber.
649   return FileNumber;
650 }
651 
652 /// Utility function to emit the encoding to a streamer.
653 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
654                            int64_t LineDelta, uint64_t AddrDelta) {
655   MCContext &Context = MCOS->getContext();
656   SmallString<256> Tmp;
657   raw_svector_ostream OS(Tmp);
658   MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
659   MCOS->emitBytes(OS.str());
660 }
661 
662 /// Given a special op, return the address skip amount (in units of
663 /// DWARF2_LINE_MIN_INSN_LENGTH).
664 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
665   return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
666 }
667 
668 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
669 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
670                              int64_t LineDelta, uint64_t AddrDelta,
671                              raw_ostream &OS) {
672   uint64_t Temp, Opcode;
673   bool NeedCopy = false;
674 
675   // The maximum address skip amount that can be encoded with a special op.
676   uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
677 
678   // Scale the address delta by the minimum instruction length.
679   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
680 
681   // A LineDelta of INT64_MAX is a signal that this is actually a
682   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
683   // end_sequence to emit the matrix entry.
684   if (LineDelta == INT64_MAX) {
685     if (AddrDelta == MaxSpecialAddrDelta)
686       OS << char(dwarf::DW_LNS_const_add_pc);
687     else if (AddrDelta) {
688       OS << char(dwarf::DW_LNS_advance_pc);
689       encodeULEB128(AddrDelta, OS);
690     }
691     OS << char(dwarf::DW_LNS_extended_op);
692     OS << char(1);
693     OS << char(dwarf::DW_LNE_end_sequence);
694     return;
695   }
696 
697   // Bias the line delta by the base.
698   Temp = LineDelta - Params.DWARF2LineBase;
699 
700   // If the line increment is out of range of a special opcode, we must encode
701   // it with DW_LNS_advance_line.
702   if (Temp >= Params.DWARF2LineRange ||
703       Temp + Params.DWARF2LineOpcodeBase > 255) {
704     OS << char(dwarf::DW_LNS_advance_line);
705     encodeSLEB128(LineDelta, OS);
706 
707     LineDelta = 0;
708     Temp = 0 - Params.DWARF2LineBase;
709     NeedCopy = true;
710   }
711 
712   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
713   if (LineDelta == 0 && AddrDelta == 0) {
714     OS << char(dwarf::DW_LNS_copy);
715     return;
716   }
717 
718   // Bias the opcode by the special opcode base.
719   Temp += Params.DWARF2LineOpcodeBase;
720 
721   // Avoid overflow when addr_delta is large.
722   if (AddrDelta < 256 + MaxSpecialAddrDelta) {
723     // Try using a special opcode.
724     Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
725     if (Opcode <= 255) {
726       OS << char(Opcode);
727       return;
728     }
729 
730     // Try using DW_LNS_const_add_pc followed by special op.
731     Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
732     if (Opcode <= 255) {
733       OS << char(dwarf::DW_LNS_const_add_pc);
734       OS << char(Opcode);
735       return;
736     }
737   }
738 
739   // Otherwise use DW_LNS_advance_pc.
740   OS << char(dwarf::DW_LNS_advance_pc);
741   encodeULEB128(AddrDelta, OS);
742 
743   if (NeedCopy)
744     OS << char(dwarf::DW_LNS_copy);
745   else {
746     assert(Temp <= 255 && "Buggy special opcode encoding.");
747     OS << char(Temp);
748   }
749 }
750 
751 std::tuple<uint32_t, uint32_t, bool>
752 MCDwarfLineAddr::fixedEncode(MCContext &Context, int64_t LineDelta,
753                              uint64_t AddrDelta, raw_ostream &OS) {
754   uint32_t Offset, Size;
755   if (LineDelta != INT64_MAX) {
756     OS << char(dwarf::DW_LNS_advance_line);
757     encodeSLEB128(LineDelta, OS);
758   }
759 
760   // Use address delta to adjust address or use absolute address to adjust
761   // address.
762   bool SetDelta;
763   // According to DWARF spec., the DW_LNS_fixed_advance_pc opcode takes a
764   // single uhalf (unencoded) operand. So, the maximum value of AddrDelta
765   // is 65535. We set a conservative upper bound for it for relaxation.
766   if (AddrDelta > 60000) {
767     const MCAsmInfo *asmInfo = Context.getAsmInfo();
768     unsigned AddrSize = asmInfo->getCodePointerSize();
769 
770     OS << char(dwarf::DW_LNS_extended_op);
771     encodeULEB128(1 + AddrSize, OS);
772     OS << char(dwarf::DW_LNE_set_address);
773     // Generate fixup for the address.
774     Offset = OS.tell();
775     Size = AddrSize;
776     SetDelta = false;
777     OS.write_zeros(AddrSize);
778   } else {
779     OS << char(dwarf::DW_LNS_fixed_advance_pc);
780     // Generate fixup for 2-bytes address delta.
781     Offset = OS.tell();
782     Size = 2;
783     SetDelta = true;
784     OS << char(0);
785     OS << char(0);
786   }
787 
788   if (LineDelta == INT64_MAX) {
789     OS << char(dwarf::DW_LNS_extended_op);
790     OS << char(1);
791     OS << char(dwarf::DW_LNE_end_sequence);
792   } else {
793     OS << char(dwarf::DW_LNS_copy);
794   }
795 
796   return std::make_tuple(Offset, Size, SetDelta);
797 }
798 
799 // Utility function to write a tuple for .debug_abbrev.
800 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
801   MCOS->emitULEB128IntValue(Name);
802   MCOS->emitULEB128IntValue(Form);
803 }
804 
805 // When generating dwarf for assembly source files this emits
806 // the data for .debug_abbrev section which contains three DIEs.
807 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
808   MCContext &context = MCOS->getContext();
809   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
810 
811   // DW_TAG_compile_unit DIE abbrev (1).
812   MCOS->emitULEB128IntValue(1);
813   MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
814   MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
815   dwarf::Form SecOffsetForm =
816       context.getDwarfVersion() >= 4
817           ? dwarf::DW_FORM_sec_offset
818           : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
819                                                         : dwarf::DW_FORM_data4);
820   EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
821   if (context.getGenDwarfSectionSyms().size() > 1 &&
822       context.getDwarfVersion() >= 3) {
823     EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
824   } else {
825     EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
826     EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
827   }
828   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
829   if (!context.getCompilationDir().empty())
830     EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
831   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
832   if (!DwarfDebugFlags.empty())
833     EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
834   EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
835   EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
836   EmitAbbrev(MCOS, 0, 0);
837 
838   // DW_TAG_label DIE abbrev (2).
839   MCOS->emitULEB128IntValue(2);
840   MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
841   MCOS->emitInt8(dwarf::DW_CHILDREN_no);
842   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
843   EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
844   EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
845   EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
846   EmitAbbrev(MCOS, 0, 0);
847 
848   // Terminate the abbreviations for this compilation unit.
849   MCOS->emitInt8(0);
850 }
851 
852 // When generating dwarf for assembly source files this emits the data for
853 // .debug_aranges section. This section contains a header and a table of pairs
854 // of PointerSize'ed values for the address and size of section(s) with line
855 // table entries.
856 static void EmitGenDwarfAranges(MCStreamer *MCOS,
857                                 const MCSymbol *InfoSectionSymbol) {
858   MCContext &context = MCOS->getContext();
859 
860   auto &Sections = context.getGenDwarfSectionSyms();
861 
862   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
863 
864   unsigned UnitLengthBytes =
865       dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
866   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
867 
868   // This will be the length of the .debug_aranges section, first account for
869   // the size of each item in the header (see below where we emit these items).
870   int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
871 
872   // Figure the padding after the header before the table of address and size
873   // pairs who's values are PointerSize'ed.
874   const MCAsmInfo *asmInfo = context.getAsmInfo();
875   int AddrSize = asmInfo->getCodePointerSize();
876   int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
877   if (Pad == 2 * AddrSize)
878     Pad = 0;
879   Length += Pad;
880 
881   // Add the size of the pair of PointerSize'ed values for the address and size
882   // of each section we have in the table.
883   Length += 2 * AddrSize * Sections.size();
884   // And the pair of terminating zeros.
885   Length += 2 * AddrSize;
886 
887   // Emit the header for this section.
888   if (context.getDwarfFormat() == dwarf::DWARF64)
889     // The DWARF64 mark.
890     MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
891   // The 4 (8 for DWARF64) byte length not including the length of the unit
892   // length field itself.
893   MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
894   // The 2 byte version, which is 2.
895   MCOS->emitInt16(2);
896   // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
897   // from the start of the .debug_info.
898   if (InfoSectionSymbol)
899     MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
900                           asmInfo->needsDwarfSectionOffsetDirective());
901   else
902     MCOS->emitIntValue(0, OffsetSize);
903   // The 1 byte size of an address.
904   MCOS->emitInt8(AddrSize);
905   // The 1 byte size of a segment descriptor, we use a value of zero.
906   MCOS->emitInt8(0);
907   // Align the header with the padding if needed, before we put out the table.
908   for(int i = 0; i < Pad; i++)
909     MCOS->emitInt8(0);
910 
911   // Now emit the table of pairs of PointerSize'ed values for the section
912   // addresses and sizes.
913   for (MCSection *Sec : Sections) {
914     const MCSymbol *StartSymbol = Sec->getBeginSymbol();
915     MCSymbol *EndSymbol = Sec->getEndSymbol(context);
916     assert(StartSymbol && "StartSymbol must not be NULL");
917     assert(EndSymbol && "EndSymbol must not be NULL");
918 
919     const MCExpr *Addr = MCSymbolRefExpr::create(
920       StartSymbol, MCSymbolRefExpr::VK_None, context);
921     const MCExpr *Size =
922         makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
923     MCOS->emitValue(Addr, AddrSize);
924     emitAbsValue(*MCOS, Size, AddrSize);
925   }
926 
927   // And finally the pair of terminating zeros.
928   MCOS->emitIntValue(0, AddrSize);
929   MCOS->emitIntValue(0, AddrSize);
930 }
931 
932 // When generating dwarf for assembly source files this emits the data for
933 // .debug_info section which contains three parts.  The header, the compile_unit
934 // DIE and a list of label DIEs.
935 static void EmitGenDwarfInfo(MCStreamer *MCOS,
936                              const MCSymbol *AbbrevSectionSymbol,
937                              const MCSymbol *LineSectionSymbol,
938                              const MCSymbol *RangesSymbol) {
939   MCContext &context = MCOS->getContext();
940 
941   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
942 
943   // Create a symbol at the start and end of this section used in here for the
944   // expression to calculate the length in the header.
945   MCSymbol *InfoStart = context.createTempSymbol();
946   MCOS->emitLabel(InfoStart);
947   MCSymbol *InfoEnd = context.createTempSymbol();
948 
949   // First part: the header.
950 
951   unsigned UnitLengthBytes =
952       dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
953   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
954 
955   if (context.getDwarfFormat() == dwarf::DWARF64)
956     // Emit DWARF64 mark.
957     MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
958 
959   // The 4 (8 for DWARF64) byte total length of the information for this
960   // compilation unit, not including the unit length field itself.
961   const MCExpr *Length =
962       makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
963   emitAbsValue(*MCOS, Length, OffsetSize);
964 
965   // The 2 byte DWARF version.
966   MCOS->emitInt16(context.getDwarfVersion());
967 
968   // The DWARF v5 header has unit type, address size, abbrev offset.
969   // Earlier versions have abbrev offset, address size.
970   const MCAsmInfo &AsmInfo = *context.getAsmInfo();
971   int AddrSize = AsmInfo.getCodePointerSize();
972   if (context.getDwarfVersion() >= 5) {
973     MCOS->emitInt8(dwarf::DW_UT_compile);
974     MCOS->emitInt8(AddrSize);
975   }
976   // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
977   // the .debug_abbrev.
978   if (AbbrevSectionSymbol)
979     MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
980                           AsmInfo.needsDwarfSectionOffsetDirective());
981   else
982     // Since the abbrevs are at the start of the section, the offset is zero.
983     MCOS->emitIntValue(0, OffsetSize);
984   if (context.getDwarfVersion() <= 4)
985     MCOS->emitInt8(AddrSize);
986 
987   // Second part: the compile_unit DIE.
988 
989   // The DW_TAG_compile_unit DIE abbrev (1).
990   MCOS->emitULEB128IntValue(1);
991 
992   // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
993   // .debug_line section.
994   if (LineSectionSymbol)
995     MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
996                           AsmInfo.needsDwarfSectionOffsetDirective());
997   else
998     // The line table is at the start of the section, so the offset is zero.
999     MCOS->emitIntValue(0, OffsetSize);
1000 
1001   if (RangesSymbol) {
1002     // There are multiple sections containing code, so we must use
1003     // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
1004     // start of the .debug_ranges/.debug_rnglists.
1005     MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
1006   } else {
1007     // If we only have one non-empty code section, we can use the simpler
1008     // AT_low_pc and AT_high_pc attributes.
1009 
1010     // Find the first (and only) non-empty text section
1011     auto &Sections = context.getGenDwarfSectionSyms();
1012     const auto TextSection = Sections.begin();
1013     assert(TextSection != Sections.end() && "No text section found");
1014 
1015     MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
1016     MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
1017     assert(StartSymbol && "StartSymbol must not be NULL");
1018     assert(EndSymbol && "EndSymbol must not be NULL");
1019 
1020     // AT_low_pc, the first address of the default .text section.
1021     const MCExpr *Start = MCSymbolRefExpr::create(
1022         StartSymbol, MCSymbolRefExpr::VK_None, context);
1023     MCOS->emitValue(Start, AddrSize);
1024 
1025     // AT_high_pc, the last address of the default .text section.
1026     const MCExpr *End = MCSymbolRefExpr::create(
1027       EndSymbol, MCSymbolRefExpr::VK_None, context);
1028     MCOS->emitValue(End, AddrSize);
1029   }
1030 
1031   // AT_name, the name of the source file.  Reconstruct from the first directory
1032   // and file table entries.
1033   const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
1034   if (MCDwarfDirs.size() > 0) {
1035     MCOS->emitBytes(MCDwarfDirs[0]);
1036     MCOS->emitBytes(sys::path::get_separator());
1037   }
1038   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
1039   // MCDwarfFiles might be empty if we have an empty source file.
1040   // If it's not empty, [0] is unused and [1] is the first actual file.
1041   assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
1042   const MCDwarfFile &RootFile =
1043       MCDwarfFiles.empty()
1044           ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
1045           : MCDwarfFiles[1];
1046   MCOS->emitBytes(RootFile.Name);
1047   MCOS->emitInt8(0); // NULL byte to terminate the string.
1048 
1049   // AT_comp_dir, the working directory the assembly was done in.
1050   if (!context.getCompilationDir().empty()) {
1051     MCOS->emitBytes(context.getCompilationDir());
1052     MCOS->emitInt8(0); // NULL byte to terminate the string.
1053   }
1054 
1055   // AT_APPLE_flags, the command line arguments of the assembler tool.
1056   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
1057   if (!DwarfDebugFlags.empty()){
1058     MCOS->emitBytes(DwarfDebugFlags);
1059     MCOS->emitInt8(0); // NULL byte to terminate the string.
1060   }
1061 
1062   // AT_producer, the version of the assembler tool.
1063   StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
1064   if (!DwarfDebugProducer.empty())
1065     MCOS->emitBytes(DwarfDebugProducer);
1066   else
1067     MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
1068   MCOS->emitInt8(0); // NULL byte to terminate the string.
1069 
1070   // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dwarf2
1071   // draft has no standard code for assembler.
1072   MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
1073 
1074   // Third part: the list of label DIEs.
1075 
1076   // Loop on saved info for dwarf labels and create the DIEs for them.
1077   const std::vector<MCGenDwarfLabelEntry> &Entries =
1078       MCOS->getContext().getMCGenDwarfLabelEntries();
1079   for (const auto &Entry : Entries) {
1080     // The DW_TAG_label DIE abbrev (2).
1081     MCOS->emitULEB128IntValue(2);
1082 
1083     // AT_name, of the label without any leading underbar.
1084     MCOS->emitBytes(Entry.getName());
1085     MCOS->emitInt8(0); // NULL byte to terminate the string.
1086 
1087     // AT_decl_file, index into the file table.
1088     MCOS->emitInt32(Entry.getFileNumber());
1089 
1090     // AT_decl_line, source line number.
1091     MCOS->emitInt32(Entry.getLineNumber());
1092 
1093     // AT_low_pc, start address of the label.
1094     const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
1095                                              MCSymbolRefExpr::VK_None, context);
1096     MCOS->emitValue(AT_low_pc, AddrSize);
1097   }
1098 
1099   // Add the NULL DIE terminating the Compile Unit DIE's.
1100   MCOS->emitInt8(0);
1101 
1102   // Now set the value of the symbol at the end of the info section.
1103   MCOS->emitLabel(InfoEnd);
1104 }
1105 
1106 // When generating dwarf for assembly source files this emits the data for
1107 // .debug_ranges section. We only emit one range list, which spans all of the
1108 // executable sections of this file.
1109 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
1110   MCContext &context = MCOS->getContext();
1111   auto &Sections = context.getGenDwarfSectionSyms();
1112 
1113   const MCAsmInfo *AsmInfo = context.getAsmInfo();
1114   int AddrSize = AsmInfo->getCodePointerSize();
1115   MCSymbol *RangesSymbol;
1116 
1117   if (MCOS->getContext().getDwarfVersion() >= 5) {
1118     MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
1119     MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
1120     MCOS->AddComment("Offset entry count");
1121     MCOS->emitInt32(0);
1122     RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
1123     MCOS->emitLabel(RangesSymbol);
1124     for (MCSection *Sec : Sections) {
1125       const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1126       const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1127       const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1128           StartSymbol, MCSymbolRefExpr::VK_None, context);
1129       const MCExpr *SectionSize =
1130           makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1131       MCOS->emitInt8(dwarf::DW_RLE_start_length);
1132       MCOS->emitValue(SectionStartAddr, AddrSize);
1133       MCOS->emitULEB128Value(SectionSize);
1134     }
1135     MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
1136     MCOS->emitLabel(EndSymbol);
1137   } else {
1138     MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
1139     RangesSymbol = context.createTempSymbol("debug_ranges_start");
1140     MCOS->emitLabel(RangesSymbol);
1141     for (MCSection *Sec : Sections) {
1142       const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1143       const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1144 
1145       // Emit a base address selection entry for the section start.
1146       const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1147           StartSymbol, MCSymbolRefExpr::VK_None, context);
1148       MCOS->emitFill(AddrSize, 0xFF);
1149       MCOS->emitValue(SectionStartAddr, AddrSize);
1150 
1151       // Emit a range list entry spanning this section.
1152       const MCExpr *SectionSize =
1153           makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1154       MCOS->emitIntValue(0, AddrSize);
1155       emitAbsValue(*MCOS, SectionSize, AddrSize);
1156     }
1157 
1158     // Emit end of list entry
1159     MCOS->emitIntValue(0, AddrSize);
1160     MCOS->emitIntValue(0, AddrSize);
1161   }
1162 
1163   return RangesSymbol;
1164 }
1165 
1166 //
1167 // When generating dwarf for assembly source files this emits the Dwarf
1168 // sections.
1169 //
1170 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
1171   MCContext &context = MCOS->getContext();
1172 
1173   // Create the dwarf sections in this order (.debug_line already created).
1174   const MCAsmInfo *AsmInfo = context.getAsmInfo();
1175   bool CreateDwarfSectionSymbols =
1176       AsmInfo->doesDwarfUseRelocationsAcrossSections();
1177   MCSymbol *LineSectionSymbol = nullptr;
1178   if (CreateDwarfSectionSymbols)
1179     LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
1180   MCSymbol *AbbrevSectionSymbol = nullptr;
1181   MCSymbol *InfoSectionSymbol = nullptr;
1182   MCSymbol *RangesSymbol = nullptr;
1183 
1184   // Create end symbols for each section, and remove empty sections
1185   MCOS->getContext().finalizeDwarfSections(*MCOS);
1186 
1187   // If there are no sections to generate debug info for, we don't need
1188   // to do anything
1189   if (MCOS->getContext().getGenDwarfSectionSyms().empty())
1190     return;
1191 
1192   // We only use the .debug_ranges section if we have multiple code sections,
1193   // and we are emitting a DWARF version which supports it.
1194   const bool UseRangesSection =
1195       MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
1196       MCOS->getContext().getDwarfVersion() >= 3;
1197   CreateDwarfSectionSymbols |= UseRangesSection;
1198 
1199   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
1200   if (CreateDwarfSectionSymbols) {
1201     InfoSectionSymbol = context.createTempSymbol();
1202     MCOS->emitLabel(InfoSectionSymbol);
1203   }
1204   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
1205   if (CreateDwarfSectionSymbols) {
1206     AbbrevSectionSymbol = context.createTempSymbol();
1207     MCOS->emitLabel(AbbrevSectionSymbol);
1208   }
1209 
1210   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
1211 
1212   // Output the data for .debug_aranges section.
1213   EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
1214 
1215   if (UseRangesSection) {
1216     RangesSymbol = emitGenDwarfRanges(MCOS);
1217     assert(RangesSymbol);
1218   }
1219 
1220   // Output the data for .debug_abbrev section.
1221   EmitGenDwarfAbbrev(MCOS);
1222 
1223   // Output the data for .debug_info section.
1224   EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
1225 }
1226 
1227 //
1228 // When generating dwarf for assembly source files this is called when symbol
1229 // for a label is created.  If this symbol is not a temporary and is in the
1230 // section that dwarf is being generated for, save the needed info to create
1231 // a dwarf label.
1232 //
1233 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
1234                                      SourceMgr &SrcMgr, SMLoc &Loc) {
1235   // We won't create dwarf labels for temporary symbols.
1236   if (Symbol->isTemporary())
1237     return;
1238   MCContext &context = MCOS->getContext();
1239   // We won't create dwarf labels for symbols in sections that we are not
1240   // generating debug info for.
1241   if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
1242     return;
1243 
1244   // The dwarf label's name does not have the symbol name's leading
1245   // underbar if any.
1246   StringRef Name = Symbol->getName();
1247   if (Name.startswith("_"))
1248     Name = Name.substr(1, Name.size()-1);
1249 
1250   // Get the dwarf file number to be used for the dwarf label.
1251   unsigned FileNumber = context.getGenDwarfFileNumber();
1252 
1253   // Finding the line number is the expensive part which is why we just don't
1254   // pass it in as for some symbols we won't create a dwarf label.
1255   unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
1256   unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
1257 
1258   // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
1259   // values so that they don't have things like an ARM thumb bit from the
1260   // original symbol. So when used they won't get a low bit set after
1261   // relocation.
1262   MCSymbol *Label = context.createTempSymbol();
1263   MCOS->emitLabel(Label);
1264 
1265   // Create and entry for the info and add it to the other entries.
1266   MCOS->getContext().addMCGenDwarfLabelEntry(
1267       MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
1268 }
1269 
1270 static int getDataAlignmentFactor(MCStreamer &streamer) {
1271   MCContext &context = streamer.getContext();
1272   const MCAsmInfo *asmInfo = context.getAsmInfo();
1273   int size = asmInfo->getCalleeSaveStackSlotSize();
1274   if (asmInfo->isStackGrowthDirectionUp())
1275     return size;
1276   else
1277     return -size;
1278 }
1279 
1280 static unsigned getSizeForEncoding(MCStreamer &streamer,
1281                                    unsigned symbolEncoding) {
1282   MCContext &context = streamer.getContext();
1283   unsigned format = symbolEncoding & 0x0f;
1284   switch (format) {
1285   default: llvm_unreachable("Unknown Encoding");
1286   case dwarf::DW_EH_PE_absptr:
1287   case dwarf::DW_EH_PE_signed:
1288     return context.getAsmInfo()->getCodePointerSize();
1289   case dwarf::DW_EH_PE_udata2:
1290   case dwarf::DW_EH_PE_sdata2:
1291     return 2;
1292   case dwarf::DW_EH_PE_udata4:
1293   case dwarf::DW_EH_PE_sdata4:
1294     return 4;
1295   case dwarf::DW_EH_PE_udata8:
1296   case dwarf::DW_EH_PE_sdata8:
1297     return 8;
1298   }
1299 }
1300 
1301 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
1302                        unsigned symbolEncoding, bool isEH) {
1303   MCContext &context = streamer.getContext();
1304   const MCAsmInfo *asmInfo = context.getAsmInfo();
1305   const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
1306                                                  symbolEncoding,
1307                                                  streamer);
1308   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1309   if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1310     emitAbsValue(streamer, v, size);
1311   else
1312     streamer.emitValue(v, size);
1313 }
1314 
1315 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1316                             unsigned symbolEncoding) {
1317   MCContext &context = streamer.getContext();
1318   const MCAsmInfo *asmInfo = context.getAsmInfo();
1319   const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1320                                                          symbolEncoding,
1321                                                          streamer);
1322   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1323   streamer.emitValue(v, size);
1324 }
1325 
1326 namespace {
1327 
1328 class FrameEmitterImpl {
1329   int CFAOffset = 0;
1330   int InitialCFAOffset = 0;
1331   bool IsEH;
1332   MCObjectStreamer &Streamer;
1333 
1334 public:
1335   FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1336       : IsEH(IsEH), Streamer(Streamer) {}
1337 
1338   /// Emit the unwind information in a compact way.
1339   void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1340 
1341   const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
1342   void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1343                bool LastInSection, const MCSymbol &SectionStart);
1344   void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1345                            MCSymbol *BaseLabel);
1346   void emitCFIInstruction(const MCCFIInstruction &Instr);
1347 };
1348 
1349 } // end anonymous namespace
1350 
1351 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1352   Streamer.emitInt8(Encoding);
1353 }
1354 
1355 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
1356   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1357   auto *MRI = Streamer.getContext().getRegisterInfo();
1358 
1359   switch (Instr.getOperation()) {
1360   case MCCFIInstruction::OpRegister: {
1361     unsigned Reg1 = Instr.getRegister();
1362     unsigned Reg2 = Instr.getRegister2();
1363     if (!IsEH) {
1364       Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
1365       Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
1366     }
1367     Streamer.emitInt8(dwarf::DW_CFA_register);
1368     Streamer.emitULEB128IntValue(Reg1);
1369     Streamer.emitULEB128IntValue(Reg2);
1370     return;
1371   }
1372   case MCCFIInstruction::OpWindowSave:
1373     Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
1374     return;
1375 
1376   case MCCFIInstruction::OpNegateRAState:
1377     Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
1378     return;
1379 
1380   case MCCFIInstruction::OpUndefined: {
1381     unsigned Reg = Instr.getRegister();
1382     Streamer.emitInt8(dwarf::DW_CFA_undefined);
1383     Streamer.emitULEB128IntValue(Reg);
1384     return;
1385   }
1386   case MCCFIInstruction::OpAdjustCfaOffset:
1387   case MCCFIInstruction::OpDefCfaOffset: {
1388     const bool IsRelative =
1389       Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1390 
1391     Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
1392 
1393     if (IsRelative)
1394       CFAOffset += Instr.getOffset();
1395     else
1396       CFAOffset = Instr.getOffset();
1397 
1398     Streamer.emitULEB128IntValue(CFAOffset);
1399 
1400     return;
1401   }
1402   case MCCFIInstruction::OpDefCfa: {
1403     unsigned Reg = Instr.getRegister();
1404     if (!IsEH)
1405       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1406     Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
1407     Streamer.emitULEB128IntValue(Reg);
1408     CFAOffset = Instr.getOffset();
1409     Streamer.emitULEB128IntValue(CFAOffset);
1410 
1411     return;
1412   }
1413   case MCCFIInstruction::OpDefCfaRegister: {
1414     unsigned Reg = Instr.getRegister();
1415     if (!IsEH)
1416       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1417     Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
1418     Streamer.emitULEB128IntValue(Reg);
1419 
1420     return;
1421   }
1422   case MCCFIInstruction::OpOffset:
1423   case MCCFIInstruction::OpRelOffset: {
1424     const bool IsRelative =
1425       Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1426 
1427     unsigned Reg = Instr.getRegister();
1428     if (!IsEH)
1429       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1430 
1431     int Offset = Instr.getOffset();
1432     if (IsRelative)
1433       Offset -= CFAOffset;
1434     Offset = Offset / dataAlignmentFactor;
1435 
1436     if (Offset < 0) {
1437       Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
1438       Streamer.emitULEB128IntValue(Reg);
1439       Streamer.emitSLEB128IntValue(Offset);
1440     } else if (Reg < 64) {
1441       Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
1442       Streamer.emitULEB128IntValue(Offset);
1443     } else {
1444       Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
1445       Streamer.emitULEB128IntValue(Reg);
1446       Streamer.emitULEB128IntValue(Offset);
1447     }
1448     return;
1449   }
1450   case MCCFIInstruction::OpRememberState:
1451     Streamer.emitInt8(dwarf::DW_CFA_remember_state);
1452     return;
1453   case MCCFIInstruction::OpRestoreState:
1454     Streamer.emitInt8(dwarf::DW_CFA_restore_state);
1455     return;
1456   case MCCFIInstruction::OpSameValue: {
1457     unsigned Reg = Instr.getRegister();
1458     Streamer.emitInt8(dwarf::DW_CFA_same_value);
1459     Streamer.emitULEB128IntValue(Reg);
1460     return;
1461   }
1462   case MCCFIInstruction::OpRestore: {
1463     unsigned Reg = Instr.getRegister();
1464     if (!IsEH)
1465       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1466     if (Reg < 64) {
1467       Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
1468     } else {
1469       Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
1470       Streamer.emitULEB128IntValue(Reg);
1471     }
1472     return;
1473   }
1474   case MCCFIInstruction::OpGnuArgsSize:
1475     Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
1476     Streamer.emitULEB128IntValue(Instr.getOffset());
1477     return;
1478 
1479   case MCCFIInstruction::OpEscape:
1480     Streamer.emitBytes(Instr.getValues());
1481     return;
1482   }
1483   llvm_unreachable("Unhandled case in switch");
1484 }
1485 
1486 /// Emit frame instructions to describe the layout of the frame.
1487 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1488                                            MCSymbol *BaseLabel) {
1489   for (const MCCFIInstruction &Instr : Instrs) {
1490     MCSymbol *Label = Instr.getLabel();
1491     // Throw out move if the label is invalid.
1492     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1493 
1494     // Advance row if new location.
1495     if (BaseLabel && Label) {
1496       MCSymbol *ThisSym = Label;
1497       if (ThisSym != BaseLabel) {
1498         Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1499         BaseLabel = ThisSym;
1500       }
1501     }
1502 
1503     emitCFIInstruction(Instr);
1504   }
1505 }
1506 
1507 /// Emit the unwind information in a compact way.
1508 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1509   MCContext &Context = Streamer.getContext();
1510   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1511 
1512   // range-start range-length  compact-unwind-enc personality-func   lsda
1513   //  _foo       LfooEnd-_foo  0x00000023          0                 0
1514   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
1515   //
1516   //   .section __LD,__compact_unwind,regular,debug
1517   //
1518   //   # compact unwind for _foo
1519   //   .quad _foo
1520   //   .set L1,LfooEnd-_foo
1521   //   .long L1
1522   //   .long 0x01010001
1523   //   .quad 0
1524   //   .quad 0
1525   //
1526   //   # compact unwind for _bar
1527   //   .quad _bar
1528   //   .set L2,LbarEnd-_bar
1529   //   .long L2
1530   //   .long 0x01020011
1531   //   .quad __gxx_personality
1532   //   .quad except_tab1
1533 
1534   uint32_t Encoding = Frame.CompactUnwindEncoding;
1535   if (!Encoding) return;
1536   bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1537 
1538   // The encoding needs to know we have an LSDA.
1539   if (!DwarfEHFrameOnly && Frame.Lsda)
1540     Encoding |= 0x40000000;
1541 
1542   // Range Start
1543   unsigned FDEEncoding = MOFI->getFDEEncoding();
1544   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1545   Streamer.emitSymbolValue(Frame.Begin, Size);
1546 
1547   // Range Length
1548   const MCExpr *Range =
1549       makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
1550   emitAbsValue(Streamer, Range, 4);
1551 
1552   // Compact Encoding
1553   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1554   Streamer.emitIntValue(Encoding, Size);
1555 
1556   // Personality Function
1557   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1558   if (!DwarfEHFrameOnly && Frame.Personality)
1559     Streamer.emitSymbolValue(Frame.Personality, Size);
1560   else
1561     Streamer.emitIntValue(0, Size); // No personality fn
1562 
1563   // LSDA
1564   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1565   if (!DwarfEHFrameOnly && Frame.Lsda)
1566     Streamer.emitSymbolValue(Frame.Lsda, Size);
1567   else
1568     Streamer.emitIntValue(0, Size); // No LSDA
1569 }
1570 
1571 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1572   if (IsEH)
1573     return 1;
1574   switch (DwarfVersion) {
1575   case 2:
1576     return 1;
1577   case 3:
1578     return 3;
1579   case 4:
1580   case 5:
1581     return 4;
1582   }
1583   llvm_unreachable("Unknown version");
1584 }
1585 
1586 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
1587   MCContext &context = Streamer.getContext();
1588   const MCRegisterInfo *MRI = context.getRegisterInfo();
1589   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1590 
1591   MCSymbol *sectionStart = context.createTempSymbol();
1592   Streamer.emitLabel(sectionStart);
1593 
1594   MCSymbol *sectionEnd = context.createTempSymbol();
1595 
1596   dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1597   unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
1598   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1599   bool IsDwarf64 = Format == dwarf::DWARF64;
1600 
1601   if (IsDwarf64)
1602     // DWARF64 mark
1603     Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1604 
1605   // Length
1606   const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
1607                                                *sectionEnd, UnitLengthBytes);
1608   emitAbsValue(Streamer, Length, OffsetSize);
1609 
1610   // CIE ID
1611   uint64_t CIE_ID =
1612       IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
1613   Streamer.emitIntValue(CIE_ID, OffsetSize);
1614 
1615   // Version
1616   uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1617   Streamer.emitInt8(CIEVersion);
1618 
1619   if (IsEH) {
1620     SmallString<8> Augmentation;
1621     Augmentation += "z";
1622     if (Frame.Personality)
1623       Augmentation += "P";
1624     if (Frame.Lsda)
1625       Augmentation += "L";
1626     Augmentation += "R";
1627     if (Frame.IsSignalFrame)
1628       Augmentation += "S";
1629     if (Frame.IsBKeyFrame)
1630       Augmentation += "B";
1631     Streamer.emitBytes(Augmentation);
1632   }
1633   Streamer.emitInt8(0);
1634 
1635   if (CIEVersion >= 4) {
1636     // Address Size
1637     Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
1638 
1639     // Segment Descriptor Size
1640     Streamer.emitInt8(0);
1641   }
1642 
1643   // Code Alignment Factor
1644   Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1645 
1646   // Data Alignment Factor
1647   Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
1648 
1649   // Return Address Register
1650   unsigned RAReg = Frame.RAReg;
1651   if (RAReg == static_cast<unsigned>(INT_MAX))
1652     RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
1653 
1654   if (CIEVersion == 1) {
1655     assert(RAReg <= 255 &&
1656            "DWARF 2 encodes return_address_register in one byte");
1657     Streamer.emitInt8(RAReg);
1658   } else {
1659     Streamer.emitULEB128IntValue(RAReg);
1660   }
1661 
1662   // Augmentation Data Length (optional)
1663   unsigned augmentationLength = 0;
1664   if (IsEH) {
1665     if (Frame.Personality) {
1666       // Personality Encoding
1667       augmentationLength += 1;
1668       // Personality
1669       augmentationLength +=
1670           getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
1671     }
1672     if (Frame.Lsda)
1673       augmentationLength += 1;
1674     // Encoding of the FDE pointers
1675     augmentationLength += 1;
1676 
1677     Streamer.emitULEB128IntValue(augmentationLength);
1678 
1679     // Augmentation Data (optional)
1680     if (Frame.Personality) {
1681       // Personality Encoding
1682       emitEncodingByte(Streamer, Frame.PersonalityEncoding);
1683       // Personality
1684       EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
1685     }
1686 
1687     if (Frame.Lsda)
1688       emitEncodingByte(Streamer, Frame.LsdaEncoding);
1689 
1690     // Encoding of the FDE pointers
1691     emitEncodingByte(Streamer, MOFI->getFDEEncoding());
1692   }
1693 
1694   // Initial Instructions
1695 
1696   const MCAsmInfo *MAI = context.getAsmInfo();
1697   if (!Frame.IsSimple) {
1698     const std::vector<MCCFIInstruction> &Instructions =
1699         MAI->getInitialFrameState();
1700     emitCFIInstructions(Instructions, nullptr);
1701   }
1702 
1703   InitialCFAOffset = CFAOffset;
1704 
1705   // Padding
1706   Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize());
1707 
1708   Streamer.emitLabel(sectionEnd);
1709   return *sectionStart;
1710 }
1711 
1712 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
1713                                const MCDwarfFrameInfo &frame,
1714                                bool LastInSection,
1715                                const MCSymbol &SectionStart) {
1716   MCContext &context = Streamer.getContext();
1717   MCSymbol *fdeStart = context.createTempSymbol();
1718   MCSymbol *fdeEnd = context.createTempSymbol();
1719   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1720 
1721   CFAOffset = InitialCFAOffset;
1722 
1723   dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1724   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1725 
1726   if (Format == dwarf::DWARF64)
1727     // DWARF64 mark
1728     Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1729 
1730   // Length
1731   const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
1732   emitAbsValue(Streamer, Length, OffsetSize);
1733 
1734   Streamer.emitLabel(fdeStart);
1735 
1736   // CIE Pointer
1737   const MCAsmInfo *asmInfo = context.getAsmInfo();
1738   if (IsEH) {
1739     const MCExpr *offset =
1740         makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
1741     emitAbsValue(Streamer, offset, OffsetSize);
1742   } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1743     const MCExpr *offset =
1744         makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
1745     emitAbsValue(Streamer, offset, OffsetSize);
1746   } else {
1747     Streamer.emitSymbolValue(&cieStart, OffsetSize,
1748                              asmInfo->needsDwarfSectionOffsetDirective());
1749   }
1750 
1751   // PC Begin
1752   unsigned PCEncoding =
1753       IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1754   unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
1755   emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
1756 
1757   // PC Range
1758   const MCExpr *Range =
1759       makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
1760   emitAbsValue(Streamer, Range, PCSize);
1761 
1762   if (IsEH) {
1763     // Augmentation Data Length
1764     unsigned augmentationLength = 0;
1765 
1766     if (frame.Lsda)
1767       augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
1768 
1769     Streamer.emitULEB128IntValue(augmentationLength);
1770 
1771     // Augmentation Data
1772     if (frame.Lsda)
1773       emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
1774   }
1775 
1776   // Call Frame Instructions
1777   emitCFIInstructions(frame.Instructions, frame.Begin);
1778 
1779   // Padding
1780   // The size of a .eh_frame section has to be a multiple of the alignment
1781   // since a null CIE is interpreted as the end. Old systems overaligned
1782   // .eh_frame, so we do too and account for it in the last FDE.
1783   unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
1784   Streamer.emitValueToAlignment(Align);
1785 
1786   Streamer.emitLabel(fdeEnd);
1787 }
1788 
1789 namespace {
1790 
1791 struct CIEKey {
1792   static const CIEKey getEmptyKey() {
1793     return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX),
1794                   false);
1795   }
1796 
1797   static const CIEKey getTombstoneKey() {
1798     return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX),
1799                   false);
1800   }
1801 
1802   CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
1803          unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
1804          unsigned RAReg, bool IsBKeyFrame)
1805       : Personality(Personality), PersonalityEncoding(PersonalityEncoding),
1806         LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
1807         IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {}
1808 
1809   explicit CIEKey(const MCDwarfFrameInfo &Frame)
1810       : Personality(Frame.Personality),
1811         PersonalityEncoding(Frame.PersonalityEncoding),
1812         LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
1813         IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
1814         IsBKeyFrame(Frame.IsBKeyFrame) {}
1815 
1816   StringRef PersonalityName() const {
1817     if (!Personality)
1818       return StringRef();
1819     return Personality->getName();
1820   }
1821 
1822   bool operator<(const CIEKey &Other) const {
1823     return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
1824                            IsSignalFrame, IsSimple, RAReg) <
1825            std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
1826                            Other.LsdaEncoding, Other.IsSignalFrame,
1827                            Other.IsSimple, Other.RAReg);
1828   }
1829 
1830   const MCSymbol *Personality;
1831   unsigned PersonalityEncoding;
1832   unsigned LsdaEncoding;
1833   bool IsSignalFrame;
1834   bool IsSimple;
1835   unsigned RAReg;
1836   bool IsBKeyFrame;
1837 };
1838 
1839 } // end anonymous namespace
1840 
1841 namespace llvm {
1842 
1843 template <> struct DenseMapInfo<CIEKey> {
1844   static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
1845   static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
1846 
1847   static unsigned getHashValue(const CIEKey &Key) {
1848     return static_cast<unsigned>(hash_combine(
1849         Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
1850         Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame));
1851   }
1852 
1853   static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
1854     return LHS.Personality == RHS.Personality &&
1855            LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1856            LHS.LsdaEncoding == RHS.LsdaEncoding &&
1857            LHS.IsSignalFrame == RHS.IsSignalFrame &&
1858            LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg &&
1859            LHS.IsBKeyFrame == RHS.IsBKeyFrame;
1860   }
1861 };
1862 
1863 } // end namespace llvm
1864 
1865 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1866                                bool IsEH) {
1867   Streamer.generateCompactUnwindEncodings(MAB);
1868 
1869   MCContext &Context = Streamer.getContext();
1870   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1871   const MCAsmInfo *AsmInfo = Context.getAsmInfo();
1872   FrameEmitterImpl Emitter(IsEH, Streamer);
1873   ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1874 
1875   // Emit the compact unwind info if available.
1876   bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1877   if (IsEH && MOFI->getCompactUnwindSection()) {
1878     bool SectionEmitted = false;
1879     for (const MCDwarfFrameInfo &Frame : FrameArray) {
1880       if (Frame.CompactUnwindEncoding == 0) continue;
1881       if (!SectionEmitted) {
1882         Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1883         Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize());
1884         SectionEmitted = true;
1885       }
1886       NeedsEHFrameSection |=
1887         Frame.CompactUnwindEncoding ==
1888           MOFI->getCompactUnwindDwarfEHFrameOnly();
1889       Emitter.EmitCompactUnwind(Frame);
1890     }
1891   }
1892 
1893   if (!NeedsEHFrameSection) return;
1894 
1895   MCSection &Section =
1896       IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1897            : *MOFI->getDwarfFrameSection();
1898 
1899   Streamer.SwitchSection(&Section);
1900   MCSymbol *SectionStart = Context.createTempSymbol();
1901   Streamer.emitLabel(SectionStart);
1902 
1903   DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1904 
1905   const MCSymbol *DummyDebugKey = nullptr;
1906   bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
1907   // Sort the FDEs by their corresponding CIE before we emit them.
1908   // This isn't technically necessary according to the DWARF standard,
1909   // but the Android libunwindstack rejects eh_frame sections where
1910   // an FDE refers to a CIE other than the closest previous CIE.
1911   std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
1912   llvm::stable_sort(FrameArrayX,
1913                     [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
1914                       return CIEKey(X) < CIEKey(Y);
1915                     });
1916   for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
1917     const MCDwarfFrameInfo &Frame = *I;
1918     ++I;
1919     if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
1920           MOFI->getCompactUnwindDwarfEHFrameOnly())
1921       // Don't generate an EH frame if we don't need one. I.e., it's taken care
1922       // of by the compact unwind encoding.
1923       continue;
1924 
1925     CIEKey Key(Frame);
1926     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1927     if (!CIEStart)
1928       CIEStart = &Emitter.EmitCIE(Frame);
1929 
1930     Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
1931   }
1932 }
1933 
1934 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1935                                          uint64_t AddrDelta) {
1936   MCContext &Context = Streamer.getContext();
1937   SmallString<256> Tmp;
1938   raw_svector_ostream OS(Tmp);
1939   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1940   Streamer.emitBytes(OS.str());
1941 }
1942 
1943 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1944                                            uint64_t AddrDelta, raw_ostream &OS,
1945                                            uint32_t *Offset, uint32_t *Size) {
1946   // Scale the address delta by the minimum instruction length.
1947   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1948 
1949   bool WithFixups = false;
1950   if (Offset && Size)
1951     WithFixups = true;
1952 
1953   support::endianness E =
1954       Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
1955   if (AddrDelta == 0) {
1956     if (WithFixups) {
1957       *Offset = 0;
1958       *Size = 0;
1959     }
1960   } else if (isUIntN(6, AddrDelta)) {
1961     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1962     if (WithFixups) {
1963       *Offset = OS.tell();
1964       *Size = 6;
1965       OS << uint8_t(dwarf::DW_CFA_advance_loc);
1966     } else
1967       OS << Opcode;
1968   } else if (isUInt<8>(AddrDelta)) {
1969     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1970     if (WithFixups) {
1971       *Offset = OS.tell();
1972       *Size = 8;
1973       OS.write_zeros(1);
1974     } else
1975       OS << uint8_t(AddrDelta);
1976   } else if (isUInt<16>(AddrDelta)) {
1977     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1978     if (WithFixups) {
1979       *Offset = OS.tell();
1980       *Size = 16;
1981       OS.write_zeros(2);
1982     } else
1983       support::endian::write<uint16_t>(OS, AddrDelta, E);
1984   } else {
1985     assert(isUInt<32>(AddrDelta));
1986     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1987     if (WithFixups) {
1988       *Offset = OS.tell();
1989       *Size = 32;
1990       OS.write_zeros(4);
1991     } else
1992       support::endian::write<uint32_t>(OS, AddrDelta, E);
1993   }
1994 }
1995