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