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