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