LCOV - code coverage report
Current view: top level - lib/MC - MCDwarf.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 734 749 98.0 %
Date: 2017-09-14 15:23:50 Functions: 31 31 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13