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