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