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