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