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