xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCDwarf.cpp (revision 36b606ae6aa4b24061096ba18582e0a08ccd5dba)
10b57cec5SDimitry Andric //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/MC/MCDwarf.h"
100b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
110b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
120b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
130b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
140fca6ea1SDimitry Andric #include "llvm/ADT/ScopeExit.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
190b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
200b57cec5SDimitry Andric #include "llvm/Config/config.h"
210b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
220b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
230b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
240b57cec5SDimitry Andric #include "llvm/MC/MCObjectFileInfo.h"
250b57cec5SDimitry Andric #include "llvm/MC/MCObjectStreamer.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCSection.h"
280b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
290b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
300b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
310b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
320b57cec5SDimitry Andric #include "llvm/Support/EndianStream.h"
330b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
340b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
350b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
360b57cec5SDimitry Andric #include "llvm/Support/Path.h"
370b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
380b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
390b57cec5SDimitry Andric #include <cassert>
400b57cec5SDimitry Andric #include <cstdint>
41bdd1243dSDimitry Andric #include <optional>
420b57cec5SDimitry Andric #include <string>
430b57cec5SDimitry Andric #include <utility>
440b57cec5SDimitry Andric #include <vector>
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric using namespace llvm;
470b57cec5SDimitry Andric 
emitListsTableHeaderStart(MCStreamer & S)485ffd83dbSDimitry Andric MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
49e8d8bef9SDimitry Andric   MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");
50e8d8bef9SDimitry Andric   MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");
515ffd83dbSDimitry Andric   auto DwarfFormat = S.getContext().getDwarfFormat();
525ffd83dbSDimitry Andric   if (DwarfFormat == dwarf::DWARF64) {
535ffd83dbSDimitry Andric     S.AddComment("DWARF64 mark");
545ffd83dbSDimitry Andric     S.emitInt32(dwarf::DW_LENGTH_DWARF64);
555ffd83dbSDimitry Andric   }
565ffd83dbSDimitry Andric   S.AddComment("Length");
575ffd83dbSDimitry Andric   S.emitAbsoluteSymbolDiff(End, Start,
585ffd83dbSDimitry Andric                            dwarf::getDwarfOffsetByteSize(DwarfFormat));
595ffd83dbSDimitry Andric   S.emitLabel(Start);
605ffd83dbSDimitry Andric   S.AddComment("Version");
615ffd83dbSDimitry Andric   S.emitInt16(S.getContext().getDwarfVersion());
625ffd83dbSDimitry Andric   S.AddComment("Address size");
635ffd83dbSDimitry Andric   S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
645ffd83dbSDimitry Andric   S.AddComment("Segment selector size");
655ffd83dbSDimitry Andric   S.emitInt8(0);
665ffd83dbSDimitry Andric   return End;
675ffd83dbSDimitry Andric }
685ffd83dbSDimitry Andric 
ScaleAddrDelta(MCContext & Context,uint64_t AddrDelta)690b57cec5SDimitry Andric static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
700b57cec5SDimitry Andric   unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
710b57cec5SDimitry Andric   if (MinInsnLength == 1)
720b57cec5SDimitry Andric     return AddrDelta;
730b57cec5SDimitry Andric   if (AddrDelta % MinInsnLength != 0) {
740b57cec5SDimitry Andric     // TODO: report this error, but really only once.
750b57cec5SDimitry Andric     ;
760b57cec5SDimitry Andric   }
770b57cec5SDimitry Andric   return AddrDelta / MinInsnLength;
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
MCDwarfLineStr(MCContext & Ctx)80349cc55cSDimitry Andric MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {
81349cc55cSDimitry Andric   UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
8206c3fb27SDimitry Andric   if (UseRelocs) {
8306c3fb27SDimitry Andric     MCSection *DwarfLineStrSection =
8406c3fb27SDimitry Andric         Ctx.getObjectFileInfo()->getDwarfLineStrSection();
8506c3fb27SDimitry Andric     assert(DwarfLineStrSection && "DwarfLineStrSection must not be NULL");
8606c3fb27SDimitry Andric     LineStrLabel = DwarfLineStrSection->getBeginSymbol();
8706c3fb27SDimitry Andric   }
88349cc55cSDimitry Andric }
89349cc55cSDimitry Andric 
900b57cec5SDimitry Andric //
910b57cec5SDimitry Andric // This is called when an instruction is assembled into the specified section
920b57cec5SDimitry Andric // and if there is information from the last .loc directive that has yet to have
930b57cec5SDimitry Andric // a line entry made for it is made.
940b57cec5SDimitry Andric //
make(MCStreamer * MCOS,MCSection * Section)95fe6060f1SDimitry Andric void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {
960b57cec5SDimitry Andric   if (!MCOS->getContext().getDwarfLocSeen())
970b57cec5SDimitry Andric     return;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   // Create a symbol at in the current section for use in the line entry.
1000b57cec5SDimitry Andric   MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
1010b57cec5SDimitry Andric   // Set the value of the symbol to use for the MCDwarfLineEntry.
1025ffd83dbSDimitry Andric   MCOS->emitLabel(LineSym);
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   // Get the current .loc info saved in the context.
1050b57cec5SDimitry Andric   const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   // Create a (local) line entry with the symbol and the current .loc info.
1080b57cec5SDimitry Andric   MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // clear DwarfLocSeen saying the current .loc info is now used.
1110b57cec5SDimitry Andric   MCOS->getContext().clearDwarfLocSeen();
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   // Add the line entry to this section's entries.
1140b57cec5SDimitry Andric   MCOS->getContext()
1150b57cec5SDimitry Andric       .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
1160b57cec5SDimitry Andric       .getMCLineSections()
1170b57cec5SDimitry Andric       .addLineEntry(LineEntry, Section);
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric //
121bdd1243dSDimitry Andric // This helper routine returns an expression of End - Start - IntVal .
1220b57cec5SDimitry Andric //
makeEndMinusStartExpr(MCContext & Ctx,const MCSymbol & Start,const MCSymbol & End,int IntVal)1235ffd83dbSDimitry Andric static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
1240b57cec5SDimitry Andric                                                   const MCSymbol &Start,
1250b57cec5SDimitry Andric                                                   const MCSymbol &End,
1260b57cec5SDimitry Andric                                                   int IntVal) {
1270b57cec5SDimitry Andric   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1285ffd83dbSDimitry Andric   const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
1295ffd83dbSDimitry Andric   const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
1305ffd83dbSDimitry Andric   const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
1315ffd83dbSDimitry Andric   const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
1325ffd83dbSDimitry Andric   const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
1330b57cec5SDimitry Andric   return Res3;
1340b57cec5SDimitry Andric }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric //
1370b57cec5SDimitry Andric // This helper routine returns an expression of Start + IntVal .
1380b57cec5SDimitry Andric //
1390b57cec5SDimitry Andric static inline const MCExpr *
makeStartPlusIntExpr(MCContext & Ctx,const MCSymbol & Start,int IntVal)1400b57cec5SDimitry Andric makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
1410b57cec5SDimitry Andric   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1420b57cec5SDimitry Andric   const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
1430b57cec5SDimitry Andric   const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
1440b57cec5SDimitry Andric   const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
1450b57cec5SDimitry Andric   return Res;
1460b57cec5SDimitry Andric }
1470b57cec5SDimitry Andric 
addEndEntry(MCSymbol * EndLabel)148349cc55cSDimitry Andric void MCLineSection::addEndEntry(MCSymbol *EndLabel) {
149349cc55cSDimitry Andric   auto *Sec = &EndLabel->getSection();
150349cc55cSDimitry Andric   // The line table may be empty, which we should skip adding an end entry.
151349cc55cSDimitry Andric   // There are two cases:
152349cc55cSDimitry Andric   // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in
153349cc55cSDimitry Andric   //     place instead of adding a line entry if the target has
154349cc55cSDimitry Andric   //     usesDwarfFileAndLocDirectives.
155349cc55cSDimitry Andric   // (2) MCObjectStreamer - if a function has incomplete debug info where
156349cc55cSDimitry Andric   //     instructions don't have DILocations, the line entries are missing.
157349cc55cSDimitry Andric   auto I = MCLineDivisions.find(Sec);
158349cc55cSDimitry Andric   if (I != MCLineDivisions.end()) {
159349cc55cSDimitry Andric     auto &Entries = I->second;
160349cc55cSDimitry Andric     auto EndEntry = Entries.back();
161349cc55cSDimitry Andric     EndEntry.setEndLabel(EndLabel);
162349cc55cSDimitry Andric     Entries.push_back(EndEntry);
163349cc55cSDimitry Andric   }
164349cc55cSDimitry Andric }
165349cc55cSDimitry Andric 
1660b57cec5SDimitry Andric //
1670b57cec5SDimitry Andric // This emits the Dwarf line table for the specified section from the entries
1680b57cec5SDimitry Andric // in the LineSection.
1690b57cec5SDimitry Andric //
emitOne(MCStreamer * MCOS,MCSection * Section,const MCLineSection::MCDwarfLineEntryCollection & LineEntries)170349cc55cSDimitry Andric void MCDwarfLineTable::emitOne(
171fe6060f1SDimitry Andric     MCStreamer *MCOS, MCSection *Section,
1720b57cec5SDimitry Andric     const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
173349cc55cSDimitry Andric 
174349cc55cSDimitry Andric   unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;
175349cc55cSDimitry Andric   MCSymbol *LastLabel;
176349cc55cSDimitry Andric   auto init = [&]() {
177349cc55cSDimitry Andric     FileNum = 1;
178349cc55cSDimitry Andric     LastLine = 1;
179349cc55cSDimitry Andric     Column = 0;
180349cc55cSDimitry Andric     Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
181349cc55cSDimitry Andric     Isa = 0;
182349cc55cSDimitry Andric     Discriminator = 0;
183349cc55cSDimitry Andric     LastLabel = nullptr;
184349cc55cSDimitry Andric   };
185349cc55cSDimitry Andric   init();
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
188349cc55cSDimitry Andric   bool EndEntryEmitted = false;
1890b57cec5SDimitry Andric   for (const MCDwarfLineEntry &LineEntry : LineEntries) {
190349cc55cSDimitry Andric     MCSymbol *Label = LineEntry.getLabel();
191349cc55cSDimitry Andric     const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
192349cc55cSDimitry Andric     if (LineEntry.IsEndEntry) {
193349cc55cSDimitry Andric       MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label,
194349cc55cSDimitry Andric                                      asmInfo->getCodePointerSize());
195349cc55cSDimitry Andric       init();
196349cc55cSDimitry Andric       EndEntryEmitted = true;
197349cc55cSDimitry Andric       continue;
198349cc55cSDimitry Andric     }
199349cc55cSDimitry Andric 
2000b57cec5SDimitry Andric     int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric     if (FileNum != LineEntry.getFileNum()) {
2030b57cec5SDimitry Andric       FileNum = LineEntry.getFileNum();
2045ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_set_file);
2055ffd83dbSDimitry Andric       MCOS->emitULEB128IntValue(FileNum);
2060b57cec5SDimitry Andric     }
2070b57cec5SDimitry Andric     if (Column != LineEntry.getColumn()) {
2080b57cec5SDimitry Andric       Column = LineEntry.getColumn();
2095ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_set_column);
2105ffd83dbSDimitry Andric       MCOS->emitULEB128IntValue(Column);
2110b57cec5SDimitry Andric     }
2120b57cec5SDimitry Andric     if (Discriminator != LineEntry.getDiscriminator() &&
2130b57cec5SDimitry Andric         MCOS->getContext().getDwarfVersion() >= 4) {
2140b57cec5SDimitry Andric       Discriminator = LineEntry.getDiscriminator();
2150b57cec5SDimitry Andric       unsigned Size = getULEB128Size(Discriminator);
2165ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_extended_op);
2175ffd83dbSDimitry Andric       MCOS->emitULEB128IntValue(Size + 1);
2185ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
2195ffd83dbSDimitry Andric       MCOS->emitULEB128IntValue(Discriminator);
2200b57cec5SDimitry Andric     }
2210b57cec5SDimitry Andric     if (Isa != LineEntry.getIsa()) {
2220b57cec5SDimitry Andric       Isa = LineEntry.getIsa();
2235ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_set_isa);
2245ffd83dbSDimitry Andric       MCOS->emitULEB128IntValue(Isa);
2250b57cec5SDimitry Andric     }
2260b57cec5SDimitry Andric     if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
2270b57cec5SDimitry Andric       Flags = LineEntry.getFlags();
2285ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
2290b57cec5SDimitry Andric     }
2300b57cec5SDimitry Andric     if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
2315ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
2320b57cec5SDimitry Andric     if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
2335ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
2340b57cec5SDimitry Andric     if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
2355ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     // At this point we want to emit/create the sequence to encode the delta in
2380b57cec5SDimitry Andric     // line numbers and the increment of the address from the previous Label
2390b57cec5SDimitry Andric     // and the current Label.
2405ffd83dbSDimitry Andric     MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
2410b57cec5SDimitry Andric                                    asmInfo->getCodePointerSize());
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric     Discriminator = 0;
2440b57cec5SDimitry Andric     LastLine = LineEntry.getLine();
2450b57cec5SDimitry Andric     LastLabel = Label;
2460b57cec5SDimitry Andric   }
2470b57cec5SDimitry Andric 
248fe6060f1SDimitry Andric   // Generate DWARF line end entry.
249349cc55cSDimitry Andric   // We do not need this for DwarfDebug that explicitly terminates the line
250349cc55cSDimitry Andric   // table using ranges whenever CU or section changes. However, the MC path
251349cc55cSDimitry Andric   // does not track ranges nor terminate the line table. In that case,
252349cc55cSDimitry Andric   // conservatively use the section end symbol to end the line table.
253349cc55cSDimitry Andric   if (!EndEntryEmitted)
254fe6060f1SDimitry Andric     MCOS->emitDwarfLineEndEntry(Section, LastLabel);
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric //
2580b57cec5SDimitry Andric // This emits the Dwarf file and the line tables.
2590b57cec5SDimitry Andric //
emit(MCStreamer * MCOS,MCDwarfLineTableParams Params)260fe6060f1SDimitry Andric void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {
2610b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   auto &LineTables = context.getMCDwarfLineTables();
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   // Bail out early so we don't switch to the debug_line section needlessly and
2660b57cec5SDimitry Andric   // in doing so create an unnecessary (if empty) section.
2670b57cec5SDimitry Andric   if (LineTables.empty())
2680b57cec5SDimitry Andric     return;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   // In a v5 non-split line table, put the strings in a separate section.
271bdd1243dSDimitry Andric   std::optional<MCDwarfLineStr> LineStr;
2720b57cec5SDimitry Andric   if (context.getDwarfVersion() >= 5)
273a4a491e2SDimitry Andric     LineStr.emplace(context);
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   // Switch to the section where the table will be emitted into.
27681ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection());
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   // Handle the rest of the Compile Units.
2790b57cec5SDimitry Andric   for (const auto &CUIDTablePair : LineTables) {
280fe6060f1SDimitry Andric     CUIDTablePair.second.emitCU(MCOS, Params, LineStr);
2810b57cec5SDimitry Andric   }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   if (LineStr)
2840b57cec5SDimitry Andric     LineStr->emitSection(MCOS);
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric 
Emit(MCStreamer & MCOS,MCDwarfLineTableParams Params,MCSection * Section) const2870b57cec5SDimitry Andric void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
2880b57cec5SDimitry Andric                                MCSection *Section) const {
2890b57cec5SDimitry Andric   if (!HasSplitLineTable)
2900b57cec5SDimitry Andric     return;
291bdd1243dSDimitry Andric   std::optional<MCDwarfLineStr> NoLineStr(std::nullopt);
29281ad6265SDimitry Andric   MCOS.switchSection(Section);
293bdd1243dSDimitry Andric   MCOS.emitLabel(Header.Emit(&MCOS, Params, std::nullopt, NoLineStr).second);
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric std::pair<MCSymbol *, MCSymbol *>
Emit(MCStreamer * MCOS,MCDwarfLineTableParams Params,std::optional<MCDwarfLineStr> & LineStr) const2970b57cec5SDimitry Andric MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
298bdd1243dSDimitry Andric                              std::optional<MCDwarfLineStr> &LineStr) const {
2990b57cec5SDimitry Andric   static const char StandardOpcodeLengths[] = {
3000b57cec5SDimitry Andric       0, // length of DW_LNS_copy
3010b57cec5SDimitry Andric       1, // length of DW_LNS_advance_pc
3020b57cec5SDimitry Andric       1, // length of DW_LNS_advance_line
3030b57cec5SDimitry Andric       1, // length of DW_LNS_set_file
3040b57cec5SDimitry Andric       1, // length of DW_LNS_set_column
3050b57cec5SDimitry Andric       0, // length of DW_LNS_negate_stmt
3060b57cec5SDimitry Andric       0, // length of DW_LNS_set_basic_block
3070b57cec5SDimitry Andric       0, // length of DW_LNS_const_add_pc
3080b57cec5SDimitry Andric       1, // length of DW_LNS_fixed_advance_pc
3090b57cec5SDimitry Andric       0, // length of DW_LNS_set_prologue_end
3100b57cec5SDimitry Andric       0, // length of DW_LNS_set_epilogue_begin
3110b57cec5SDimitry Andric       1  // DW_LNS_set_isa
3120b57cec5SDimitry Andric   };
313bdd1243dSDimitry Andric   assert(std::size(StandardOpcodeLengths) >=
3140b57cec5SDimitry Andric          (Params.DWARF2LineOpcodeBase - 1U));
315bdd1243dSDimitry Andric   return Emit(MCOS, Params,
316bdd1243dSDimitry Andric               ArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
3170b57cec5SDimitry Andric               LineStr);
3180b57cec5SDimitry Andric }
3190b57cec5SDimitry Andric 
forceExpAbs(MCStreamer & OS,const MCExpr * Expr)3200b57cec5SDimitry Andric static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
3210b57cec5SDimitry Andric   MCContext &Context = OS.getContext();
3220b57cec5SDimitry Andric   assert(!isa<MCSymbolRefExpr>(Expr));
3230b57cec5SDimitry Andric   if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
3240b57cec5SDimitry Andric     return Expr;
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   MCSymbol *ABS = Context.createTempSymbol();
3275ffd83dbSDimitry Andric   OS.emitAssignment(ABS, Expr);
3280b57cec5SDimitry Andric   return MCSymbolRefExpr::create(ABS, Context);
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
emitAbsValue(MCStreamer & OS,const MCExpr * Value,unsigned Size)3310b57cec5SDimitry Andric static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
3320b57cec5SDimitry Andric   const MCExpr *ABS = forceExpAbs(OS, Value);
3335ffd83dbSDimitry Andric   OS.emitValue(ABS, Size);
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric 
emitSection(MCStreamer * MCOS)3360b57cec5SDimitry Andric void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
3370b57cec5SDimitry Andric   // Switch to the .debug_line_str section.
33881ad6265SDimitry Andric   MCOS->switchSection(
3390b57cec5SDimitry Andric       MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
34081ad6265SDimitry Andric   SmallString<0> Data = getFinalizedData();
34181ad6265SDimitry Andric   MCOS->emitBinaryData(Data.str());
34281ad6265SDimitry Andric }
34381ad6265SDimitry Andric 
getFinalizedData()34481ad6265SDimitry Andric SmallString<0> MCDwarfLineStr::getFinalizedData() {
3450b57cec5SDimitry Andric   // Emit the strings without perturbing the offsets we used.
34681ad6265SDimitry Andric   if (!LineStrings.isFinalized())
3470b57cec5SDimitry Andric     LineStrings.finalizeInOrder();
3480b57cec5SDimitry Andric   SmallString<0> Data;
3490b57cec5SDimitry Andric   Data.resize(LineStrings.getSize());
3500b57cec5SDimitry Andric   LineStrings.write((uint8_t *)Data.data());
35181ad6265SDimitry Andric   return Data;
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric 
addString(StringRef Path)35406c3fb27SDimitry Andric size_t MCDwarfLineStr::addString(StringRef Path) {
35506c3fb27SDimitry Andric   return LineStrings.add(Path);
35606c3fb27SDimitry Andric }
35706c3fb27SDimitry Andric 
emitRef(MCStreamer * MCOS,StringRef Path)3580b57cec5SDimitry Andric void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
3595ffd83dbSDimitry Andric   int RefSize =
3605ffd83dbSDimitry Andric       dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
36106c3fb27SDimitry Andric   size_t Offset = addString(Path);
3620b57cec5SDimitry Andric   if (UseRelocs) {
3630b57cec5SDimitry Andric     MCContext &Ctx = MCOS->getContext();
3640fca6ea1SDimitry Andric     if (Ctx.getAsmInfo()->needsDwarfSectionOffsetDirective()) {
3650fca6ea1SDimitry Andric       MCOS->emitCOFFSecRel32(LineStrLabel, Offset);
3660fca6ea1SDimitry Andric     } else {
3670fca6ea1SDimitry Andric       MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset),
3680fca6ea1SDimitry Andric                       RefSize);
3690fca6ea1SDimitry Andric     }
3700b57cec5SDimitry Andric   } else
3715ffd83dbSDimitry Andric     MCOS->emitIntValue(Offset, RefSize);
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
emitV2FileDirTables(MCStreamer * MCOS) const3740b57cec5SDimitry Andric void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
3750b57cec5SDimitry Andric   // First the directory table.
3760b57cec5SDimitry Andric   for (auto &Dir : MCDwarfDirs) {
3775ffd83dbSDimitry Andric     MCOS->emitBytes(Dir);                // The DirectoryName, and...
3785ffd83dbSDimitry Andric     MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
3790b57cec5SDimitry Andric   }
3805ffd83dbSDimitry Andric   MCOS->emitInt8(0); // Terminate the directory list.
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   // Second the file table.
3830b57cec5SDimitry Andric   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
3840b57cec5SDimitry Andric     assert(!MCDwarfFiles[i].Name.empty());
3855ffd83dbSDimitry Andric     MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...
3865ffd83dbSDimitry Andric     MCOS->emitBytes(StringRef("\0", 1));   // its null terminator.
3875ffd83dbSDimitry Andric     MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.
3885ffd83dbSDimitry Andric     MCOS->emitInt8(0); // Last modification timestamp (always 0).
3895ffd83dbSDimitry Andric     MCOS->emitInt8(0); // File size (always 0).
3900b57cec5SDimitry Andric   }
3915ffd83dbSDimitry Andric   MCOS->emitInt8(0); // Terminate the file list.
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
emitOneV5FileEntry(MCStreamer * MCOS,const MCDwarfFile & DwarfFile,bool EmitMD5,bool HasAnySource,std::optional<MCDwarfLineStr> & LineStr)3940b57cec5SDimitry Andric static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
3955f757f3fSDimitry Andric                                bool EmitMD5, bool HasAnySource,
396bdd1243dSDimitry Andric                                std::optional<MCDwarfLineStr> &LineStr) {
3970b57cec5SDimitry Andric   assert(!DwarfFile.Name.empty());
3980b57cec5SDimitry Andric   if (LineStr)
3990b57cec5SDimitry Andric     LineStr->emitRef(MCOS, DwarfFile.Name);
4000b57cec5SDimitry Andric   else {
4015ffd83dbSDimitry Andric     MCOS->emitBytes(DwarfFile.Name);     // FileName and...
4025ffd83dbSDimitry Andric     MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
4030b57cec5SDimitry Andric   }
4045ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.
4050b57cec5SDimitry Andric   if (EmitMD5) {
4060b57cec5SDimitry Andric     const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
4075ffd83dbSDimitry Andric     MCOS->emitBinaryData(
40881ad6265SDimitry Andric         StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size()));
4090b57cec5SDimitry Andric   }
4105f757f3fSDimitry Andric   if (HasAnySource) {
4110b57cec5SDimitry Andric     if (LineStr)
41281ad6265SDimitry Andric       LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef()));
4130b57cec5SDimitry Andric     else {
41481ad6265SDimitry Andric       MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); // Source and...
4155ffd83dbSDimitry Andric       MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
4160b57cec5SDimitry Andric     }
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
emitV5FileDirTables(MCStreamer * MCOS,std::optional<MCDwarfLineStr> & LineStr) const4200b57cec5SDimitry Andric void MCDwarfLineTableHeader::emitV5FileDirTables(
421bdd1243dSDimitry Andric     MCStreamer *MCOS, std::optional<MCDwarfLineStr> &LineStr) const {
4220b57cec5SDimitry Andric   // The directory format, which is just a list of the directory paths.  In a
4230b57cec5SDimitry Andric   // non-split object, these are references to .debug_line_str; in a split
4240b57cec5SDimitry Andric   // object, they are inline strings.
4255ffd83dbSDimitry Andric   MCOS->emitInt8(1);
4265ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
4275ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
4280b57cec5SDimitry Andric                                     : dwarf::DW_FORM_string);
4295ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
4300b57cec5SDimitry Andric   // Try not to emit an empty compilation directory.
431a4a491e2SDimitry Andric   SmallString<256> Dir;
432a4a491e2SDimitry Andric   StringRef CompDir = MCOS->getContext().getCompilationDir();
433a4a491e2SDimitry Andric   if (!CompilationDir.empty()) {
434a4a491e2SDimitry Andric     Dir = CompilationDir;
435a4a491e2SDimitry Andric     MCOS->getContext().remapDebugPath(Dir);
436a4a491e2SDimitry Andric     CompDir = Dir.str();
437a4a491e2SDimitry Andric     if (LineStr)
438a4a491e2SDimitry Andric       CompDir = LineStr->getSaver().save(CompDir);
439a4a491e2SDimitry Andric   }
4400b57cec5SDimitry Andric   if (LineStr) {
4410b57cec5SDimitry Andric     // Record path strings, emit references here.
4420b57cec5SDimitry Andric     LineStr->emitRef(MCOS, CompDir);
4430b57cec5SDimitry Andric     for (const auto &Dir : MCDwarfDirs)
4440b57cec5SDimitry Andric       LineStr->emitRef(MCOS, Dir);
4450b57cec5SDimitry Andric   } else {
4460b57cec5SDimitry Andric     // The list of directory paths.  Compilation directory comes first.
4475ffd83dbSDimitry Andric     MCOS->emitBytes(CompDir);
4485ffd83dbSDimitry Andric     MCOS->emitBytes(StringRef("\0", 1));
4490b57cec5SDimitry Andric     for (const auto &Dir : MCDwarfDirs) {
4505ffd83dbSDimitry Andric       MCOS->emitBytes(Dir);                // The DirectoryName, and...
4515ffd83dbSDimitry Andric       MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
4520b57cec5SDimitry Andric     }
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // The file format, which is the inline null-terminated filename and a
4560b57cec5SDimitry Andric   // directory index.  We don't track file size/timestamp so don't emit them
4570b57cec5SDimitry Andric   // in the v5 table.  Emit MD5 checksums and source if we have them.
4580b57cec5SDimitry Andric   uint64_t Entries = 2;
4590b57cec5SDimitry Andric   if (HasAllMD5)
4600b57cec5SDimitry Andric     Entries += 1;
4615f757f3fSDimitry Andric   if (HasAnySource)
4620b57cec5SDimitry Andric     Entries += 1;
4635ffd83dbSDimitry Andric   MCOS->emitInt8(Entries);
4645ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
4655ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
4660b57cec5SDimitry Andric                                     : dwarf::DW_FORM_string);
4675ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
4685ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
4690b57cec5SDimitry Andric   if (HasAllMD5) {
4705ffd83dbSDimitry Andric     MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
4715ffd83dbSDimitry Andric     MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
4720b57cec5SDimitry Andric   }
4735f757f3fSDimitry Andric   if (HasAnySource) {
4745ffd83dbSDimitry Andric     MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
4755ffd83dbSDimitry Andric     MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
4760b57cec5SDimitry Andric                                       : dwarf::DW_FORM_string);
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric   // Then the counted list of files. The root file is file #0, then emit the
4790b57cec5SDimitry Andric   // files as provide by .file directives.
4800b57cec5SDimitry Andric   // MCDwarfFiles has an unused element [0] so use size() not size()+1.
4810b57cec5SDimitry Andric   // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
4825ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
4830b57cec5SDimitry Andric   // To accommodate assembler source written for DWARF v4 but trying to emit
4840b57cec5SDimitry Andric   // v5: If we didn't see a root file explicitly, replicate file #1.
4850b57cec5SDimitry Andric   assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
4860b57cec5SDimitry Andric          "No root file and no .file directives");
4870b57cec5SDimitry Andric   emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
4885f757f3fSDimitry Andric                      HasAllMD5, HasAnySource, LineStr);
4890b57cec5SDimitry Andric   for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
4905f757f3fSDimitry Andric     emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasAnySource, LineStr);
4910b57cec5SDimitry Andric }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric std::pair<MCSymbol *, MCSymbol *>
Emit(MCStreamer * MCOS,MCDwarfLineTableParams Params,ArrayRef<char> StandardOpcodeLengths,std::optional<MCDwarfLineStr> & LineStr) const4940b57cec5SDimitry Andric MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
4950b57cec5SDimitry Andric                              ArrayRef<char> StandardOpcodeLengths,
496bdd1243dSDimitry Andric                              std::optional<MCDwarfLineStr> &LineStr) const {
4970b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   // Create a symbol at the beginning of the line table.
5000b57cec5SDimitry Andric   MCSymbol *LineStartSym = Label;
5010b57cec5SDimitry Andric   if (!LineStartSym)
5020b57cec5SDimitry Andric     LineStartSym = context.createTempSymbol();
503fe6060f1SDimitry Andric 
5040b57cec5SDimitry Andric   // Set the value of the symbol, as we are at the start of the line table.
505fe6060f1SDimitry Andric   MCOS->emitDwarfLineStartLabel(LineStartSym);
5060b57cec5SDimitry Andric 
5075ffd83dbSDimitry Andric   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
5085ffd83dbSDimitry Andric 
509fe6060f1SDimitry Andric   MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   // Next 2 bytes is the Version.
5120b57cec5SDimitry Andric   unsigned LineTableVersion = context.getDwarfVersion();
5135ffd83dbSDimitry Andric   MCOS->emitInt16(LineTableVersion);
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   // In v5, we get address info next.
5160b57cec5SDimitry Andric   if (LineTableVersion >= 5) {
5175ffd83dbSDimitry Andric     MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
5185ffd83dbSDimitry Andric     MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric 
521fe6060f1SDimitry Andric   // Create symbols for the start/end of the prologue.
522fe6060f1SDimitry Andric   MCSymbol *ProStartSym = context.createTempSymbol("prologue_start");
523fe6060f1SDimitry Andric   MCSymbol *ProEndSym = context.createTempSymbol("prologue_end");
5240b57cec5SDimitry Andric 
5255ffd83dbSDimitry Andric   // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
5265ffd83dbSDimitry Andric   // actually the length from after the length word, to the end of the prologue.
527fe6060f1SDimitry Andric   MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);
528fe6060f1SDimitry Andric 
529fe6060f1SDimitry Andric   MCOS->emitLabel(ProStartSym);
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   // Parameters of the state machine, are next.
5325ffd83dbSDimitry Andric   MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
5330b57cec5SDimitry Andric   // maximum_operations_per_instruction
5340b57cec5SDimitry Andric   // For non-VLIW architectures this field is always 1.
5350b57cec5SDimitry Andric   // FIXME: VLIW architectures need to update this field accordingly.
5360b57cec5SDimitry Andric   if (LineTableVersion >= 4)
5375ffd83dbSDimitry Andric     MCOS->emitInt8(1);
5385ffd83dbSDimitry Andric   MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
5395ffd83dbSDimitry Andric   MCOS->emitInt8(Params.DWARF2LineBase);
5405ffd83dbSDimitry Andric   MCOS->emitInt8(Params.DWARF2LineRange);
5415ffd83dbSDimitry Andric   MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   // Standard opcode lengths
5440b57cec5SDimitry Andric   for (char Length : StandardOpcodeLengths)
5455ffd83dbSDimitry Andric     MCOS->emitInt8(Length);
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric   // Put out the directory and file tables.  The formats vary depending on
5480b57cec5SDimitry Andric   // the version.
5490b57cec5SDimitry Andric   if (LineTableVersion >= 5)
5500b57cec5SDimitry Andric     emitV5FileDirTables(MCOS, LineStr);
5510b57cec5SDimitry Andric   else
5520b57cec5SDimitry Andric     emitV2FileDirTables(MCOS);
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   // This is the end of the prologue, so set the value of the symbol at the
5550b57cec5SDimitry Andric   // end of the prologue (that was used in a previous expression).
5565ffd83dbSDimitry Andric   MCOS->emitLabel(ProEndSym);
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   return std::make_pair(LineStartSym, LineEndSym);
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric 
emitCU(MCStreamer * MCOS,MCDwarfLineTableParams Params,std::optional<MCDwarfLineStr> & LineStr) const561fe6060f1SDimitry Andric void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
562bdd1243dSDimitry Andric                               std::optional<MCDwarfLineStr> &LineStr) const {
5630b57cec5SDimitry Andric   MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   // Put out the line tables.
5660b57cec5SDimitry Andric   for (const auto &LineSec : MCLineSections.getMCLineEntries())
567349cc55cSDimitry Andric     emitOne(MCOS, LineSec.first, LineSec.second);
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   // This is the end of the section, so set the value of the symbol at the end
5700b57cec5SDimitry Andric   // of this section (that was used in a previous expression).
5715ffd83dbSDimitry Andric   MCOS->emitLabel(LineEndSym);
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric 
574bdd1243dSDimitry Andric Expected<unsigned>
tryGetFile(StringRef & Directory,StringRef & FileName,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,uint16_t DwarfVersion,unsigned FileNumber)575bdd1243dSDimitry Andric MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName,
576bdd1243dSDimitry Andric                              std::optional<MD5::MD5Result> Checksum,
577bdd1243dSDimitry Andric                              std::optional<StringRef> Source,
578bdd1243dSDimitry Andric                              uint16_t DwarfVersion, unsigned FileNumber) {
5790b57cec5SDimitry Andric   return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
5800b57cec5SDimitry Andric                            FileNumber);
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
isRootFile(const MCDwarfFile & RootFile,StringRef & Directory,StringRef & FileName,std::optional<MD5::MD5Result> Checksum)5838bcb0991SDimitry Andric static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
584bdd1243dSDimitry Andric                        StringRef &FileName,
585bdd1243dSDimitry Andric                        std::optional<MD5::MD5Result> Checksum) {
58604eeddc0SDimitry Andric   if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
5870b57cec5SDimitry Andric     return false;
5880b57cec5SDimitry Andric   return RootFile.Checksum == Checksum;
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric Expected<unsigned>
tryGetFile(StringRef & Directory,StringRef & FileName,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,uint16_t DwarfVersion,unsigned FileNumber)592bdd1243dSDimitry Andric MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName,
593bdd1243dSDimitry Andric                                    std::optional<MD5::MD5Result> Checksum,
594bdd1243dSDimitry Andric                                    std::optional<StringRef> Source,
595bdd1243dSDimitry Andric                                    uint16_t DwarfVersion, unsigned FileNumber) {
5960b57cec5SDimitry Andric   if (Directory == CompilationDir)
5970b57cec5SDimitry Andric     Directory = "";
5980b57cec5SDimitry Andric   if (FileName.empty()) {
5990b57cec5SDimitry Andric     FileName = "<stdin>";
6000b57cec5SDimitry Andric     Directory = "";
6010b57cec5SDimitry Andric   }
6020b57cec5SDimitry Andric   assert(!FileName.empty());
6030b57cec5SDimitry Andric   // Keep track of whether any or all files have an MD5 checksum.
6040b57cec5SDimitry Andric   // If any files have embedded source, they all must.
6050b57cec5SDimitry Andric   if (MCDwarfFiles.empty()) {
60681ad6265SDimitry Andric     trackMD5Usage(Checksum.has_value());
6075f757f3fSDimitry Andric     HasAnySource |= Source.has_value();
6080b57cec5SDimitry Andric   }
60904eeddc0SDimitry Andric   if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))
6100b57cec5SDimitry Andric     return 0;
6110b57cec5SDimitry Andric   if (FileNumber == 0) {
6120b57cec5SDimitry Andric     // File numbers start with 1 and/or after any file numbers
6130b57cec5SDimitry Andric     // allocated by inline-assembler .file directives.
6140b57cec5SDimitry Andric     FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
6150b57cec5SDimitry Andric     SmallString<256> Buffer;
6160b57cec5SDimitry Andric     auto IterBool = SourceIdMap.insert(
6170b57cec5SDimitry Andric         std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
6180b57cec5SDimitry Andric                        FileNumber));
6190b57cec5SDimitry Andric     if (!IterBool.second)
6200b57cec5SDimitry Andric       return IterBool.first->second;
6210b57cec5SDimitry Andric   }
6220b57cec5SDimitry Andric   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
6230b57cec5SDimitry Andric   if (FileNumber >= MCDwarfFiles.size())
6240b57cec5SDimitry Andric     MCDwarfFiles.resize(FileNumber + 1);
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   // Get the new MCDwarfFile slot for this FileNumber.
6270b57cec5SDimitry Andric   MCDwarfFile &File = MCDwarfFiles[FileNumber];
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   // It is an error to see the same number more than once.
6300b57cec5SDimitry Andric   if (!File.Name.empty())
6310b57cec5SDimitry Andric     return make_error<StringError>("file number already allocated",
6320b57cec5SDimitry Andric                                    inconvertibleErrorCode());
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   if (Directory.empty()) {
6350b57cec5SDimitry Andric     // Separate the directory part from the basename of the FileName.
6360b57cec5SDimitry Andric     StringRef tFileName = sys::path::filename(FileName);
6370b57cec5SDimitry Andric     if (!tFileName.empty()) {
6380b57cec5SDimitry Andric       Directory = sys::path::parent_path(FileName);
6390b57cec5SDimitry Andric       if (!Directory.empty())
6400b57cec5SDimitry Andric         FileName = tFileName;
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric   }
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   // Find or make an entry in the MCDwarfDirs vector for this Directory.
6450b57cec5SDimitry Andric   // Capture directory name.
6460b57cec5SDimitry Andric   unsigned DirIndex;
6470b57cec5SDimitry Andric   if (Directory.empty()) {
6480b57cec5SDimitry Andric     // For FileNames with no directories a DirIndex of 0 is used.
6490b57cec5SDimitry Andric     DirIndex = 0;
6500b57cec5SDimitry Andric   } else {
6510b57cec5SDimitry Andric     DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
6520b57cec5SDimitry Andric     if (DirIndex >= MCDwarfDirs.size())
6535ffd83dbSDimitry Andric       MCDwarfDirs.push_back(std::string(Directory));
6540b57cec5SDimitry Andric     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
6550b57cec5SDimitry Andric     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
6560b57cec5SDimitry Andric     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
6570b57cec5SDimitry Andric     // are stored at MCDwarfFiles[FileNumber].Name .
6580b57cec5SDimitry Andric     DirIndex++;
6590b57cec5SDimitry Andric   }
6600b57cec5SDimitry Andric 
6615ffd83dbSDimitry Andric   File.Name = std::string(FileName);
6620b57cec5SDimitry Andric   File.DirIndex = DirIndex;
6630b57cec5SDimitry Andric   File.Checksum = Checksum;
66481ad6265SDimitry Andric   trackMD5Usage(Checksum.has_value());
6650b57cec5SDimitry Andric   File.Source = Source;
6665f757f3fSDimitry Andric   if (Source.has_value())
6675f757f3fSDimitry Andric     HasAnySource = true;
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   // return the allocated FileNumber.
6700b57cec5SDimitry Andric   return FileNumber;
6710b57cec5SDimitry Andric }
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric /// Utility function to emit the encoding to a streamer.
Emit(MCStreamer * MCOS,MCDwarfLineTableParams Params,int64_t LineDelta,uint64_t AddrDelta)6740b57cec5SDimitry Andric void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
6750b57cec5SDimitry Andric                            int64_t LineDelta, uint64_t AddrDelta) {
6760b57cec5SDimitry Andric   MCContext &Context = MCOS->getContext();
6770b57cec5SDimitry Andric   SmallString<256> Tmp;
67806c3fb27SDimitry Andric   MCDwarfLineAddr::encode(Context, Params, LineDelta, AddrDelta, Tmp);
67906c3fb27SDimitry Andric   MCOS->emitBytes(Tmp);
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric /// Given a special op, return the address skip amount (in units of
6830b57cec5SDimitry Andric /// DWARF2_LINE_MIN_INSN_LENGTH).
SpecialAddr(MCDwarfLineTableParams Params,uint64_t op)6840b57cec5SDimitry Andric static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
6850b57cec5SDimitry Andric   return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
6860b57cec5SDimitry Andric }
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
encode(MCContext & Context,MCDwarfLineTableParams Params,int64_t LineDelta,uint64_t AddrDelta,SmallVectorImpl<char> & Out)68906c3fb27SDimitry Andric void MCDwarfLineAddr::encode(MCContext &Context, MCDwarfLineTableParams Params,
6900b57cec5SDimitry Andric                              int64_t LineDelta, uint64_t AddrDelta,
69106c3fb27SDimitry Andric                              SmallVectorImpl<char> &Out) {
69206c3fb27SDimitry Andric   uint8_t Buf[16];
6930b57cec5SDimitry Andric   uint64_t Temp, Opcode;
6940b57cec5SDimitry Andric   bool NeedCopy = false;
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   // The maximum address skip amount that can be encoded with a special op.
6970b57cec5SDimitry Andric   uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   // Scale the address delta by the minimum instruction length.
7000b57cec5SDimitry Andric   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   // A LineDelta of INT64_MAX is a signal that this is actually a
7030b57cec5SDimitry Andric   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
7040b57cec5SDimitry Andric   // end_sequence to emit the matrix entry.
7050b57cec5SDimitry Andric   if (LineDelta == INT64_MAX) {
7060b57cec5SDimitry Andric     if (AddrDelta == MaxSpecialAddrDelta)
70706c3fb27SDimitry Andric       Out.push_back(dwarf::DW_LNS_const_add_pc);
7080b57cec5SDimitry Andric     else if (AddrDelta) {
70906c3fb27SDimitry Andric       Out.push_back(dwarf::DW_LNS_advance_pc);
71006c3fb27SDimitry Andric       Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));
7110b57cec5SDimitry Andric     }
71206c3fb27SDimitry Andric     Out.push_back(dwarf::DW_LNS_extended_op);
71306c3fb27SDimitry Andric     Out.push_back(1);
71406c3fb27SDimitry Andric     Out.push_back(dwarf::DW_LNE_end_sequence);
7150b57cec5SDimitry Andric     return;
7160b57cec5SDimitry Andric   }
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   // Bias the line delta by the base.
7190b57cec5SDimitry Andric   Temp = LineDelta - Params.DWARF2LineBase;
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   // If the line increment is out of range of a special opcode, we must encode
7220b57cec5SDimitry Andric   // it with DW_LNS_advance_line.
7230b57cec5SDimitry Andric   if (Temp >= Params.DWARF2LineRange ||
7240b57cec5SDimitry Andric       Temp + Params.DWARF2LineOpcodeBase > 255) {
72506c3fb27SDimitry Andric     Out.push_back(dwarf::DW_LNS_advance_line);
72606c3fb27SDimitry Andric     Out.append(Buf, Buf + encodeSLEB128(LineDelta, Buf));
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric     LineDelta = 0;
7290b57cec5SDimitry Andric     Temp = 0 - Params.DWARF2LineBase;
7300b57cec5SDimitry Andric     NeedCopy = true;
7310b57cec5SDimitry Andric   }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
7340b57cec5SDimitry Andric   if (LineDelta == 0 && AddrDelta == 0) {
73506c3fb27SDimitry Andric     Out.push_back(dwarf::DW_LNS_copy);
7360b57cec5SDimitry Andric     return;
7370b57cec5SDimitry Andric   }
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   // Bias the opcode by the special opcode base.
7400b57cec5SDimitry Andric   Temp += Params.DWARF2LineOpcodeBase;
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   // Avoid overflow when addr_delta is large.
7430b57cec5SDimitry Andric   if (AddrDelta < 256 + MaxSpecialAddrDelta) {
7440b57cec5SDimitry Andric     // Try using a special opcode.
7450b57cec5SDimitry Andric     Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
7460b57cec5SDimitry Andric     if (Opcode <= 255) {
74706c3fb27SDimitry Andric       Out.push_back(Opcode);
7480b57cec5SDimitry Andric       return;
7490b57cec5SDimitry Andric     }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric     // Try using DW_LNS_const_add_pc followed by special op.
7520b57cec5SDimitry Andric     Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
7530b57cec5SDimitry Andric     if (Opcode <= 255) {
75406c3fb27SDimitry Andric       Out.push_back(dwarf::DW_LNS_const_add_pc);
75506c3fb27SDimitry Andric       Out.push_back(Opcode);
7560b57cec5SDimitry Andric       return;
7570b57cec5SDimitry Andric     }
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   // Otherwise use DW_LNS_advance_pc.
76106c3fb27SDimitry Andric   Out.push_back(dwarf::DW_LNS_advance_pc);
76206c3fb27SDimitry Andric   Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   if (NeedCopy)
76506c3fb27SDimitry Andric     Out.push_back(dwarf::DW_LNS_copy);
7660b57cec5SDimitry Andric   else {
7670b57cec5SDimitry Andric     assert(Temp <= 255 && "Buggy special opcode encoding.");
76806c3fb27SDimitry Andric     Out.push_back(Temp);
7690b57cec5SDimitry Andric   }
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric // Utility function to write a tuple for .debug_abbrev.
EmitAbbrev(MCStreamer * MCOS,uint64_t Name,uint64_t Form)7730b57cec5SDimitry Andric static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
7745ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(Name);
7755ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(Form);
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric // When generating dwarf for assembly source files this emits
7790b57cec5SDimitry Andric // the data for .debug_abbrev section which contains three DIEs.
EmitGenDwarfAbbrev(MCStreamer * MCOS)7800b57cec5SDimitry Andric static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
7810b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
78281ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   // DW_TAG_compile_unit DIE abbrev (1).
7855ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(1);
7865ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
7875ffd83dbSDimitry Andric   MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
7885ffd83dbSDimitry Andric   dwarf::Form SecOffsetForm =
7895ffd83dbSDimitry Andric       context.getDwarfVersion() >= 4
7900b57cec5SDimitry Andric           ? dwarf::DW_FORM_sec_offset
7915ffd83dbSDimitry Andric           : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
7920b57cec5SDimitry Andric                                                         : dwarf::DW_FORM_data4);
7935ffd83dbSDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
7940b57cec5SDimitry Andric   if (context.getGenDwarfSectionSyms().size() > 1 &&
7950b57cec5SDimitry Andric       context.getDwarfVersion() >= 3) {
7965ffd83dbSDimitry Andric     EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
7970b57cec5SDimitry Andric   } else {
7980b57cec5SDimitry Andric     EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
7990b57cec5SDimitry Andric     EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
8020b57cec5SDimitry Andric   if (!context.getCompilationDir().empty())
8030b57cec5SDimitry Andric     EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
8040b57cec5SDimitry Andric   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
8050b57cec5SDimitry Andric   if (!DwarfDebugFlags.empty())
8060b57cec5SDimitry Andric     EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
8070b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
8080b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
8090b57cec5SDimitry Andric   EmitAbbrev(MCOS, 0, 0);
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   // DW_TAG_label DIE abbrev (2).
8125ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(2);
8135ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
8145ffd83dbSDimitry Andric   MCOS->emitInt8(dwarf::DW_CHILDREN_no);
8150b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
8160b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
8170b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
8180b57cec5SDimitry Andric   EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
8190b57cec5SDimitry Andric   EmitAbbrev(MCOS, 0, 0);
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric   // Terminate the abbreviations for this compilation unit.
8225ffd83dbSDimitry Andric   MCOS->emitInt8(0);
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric // When generating dwarf for assembly source files this emits the data for
8260b57cec5SDimitry Andric // .debug_aranges section. This section contains a header and a table of pairs
8270b57cec5SDimitry Andric // of PointerSize'ed values for the address and size of section(s) with line
8280b57cec5SDimitry Andric // table entries.
EmitGenDwarfAranges(MCStreamer * MCOS,const MCSymbol * InfoSectionSymbol)8290b57cec5SDimitry Andric static void EmitGenDwarfAranges(MCStreamer *MCOS,
8300b57cec5SDimitry Andric                                 const MCSymbol *InfoSectionSymbol) {
8310b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   auto &Sections = context.getGenDwarfSectionSyms();
8340b57cec5SDimitry Andric 
83581ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
8360b57cec5SDimitry Andric 
8375ffd83dbSDimitry Andric   unsigned UnitLengthBytes =
8385ffd83dbSDimitry Andric       dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
8395ffd83dbSDimitry Andric   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
8405ffd83dbSDimitry Andric 
8410b57cec5SDimitry Andric   // This will be the length of the .debug_aranges section, first account for
8420b57cec5SDimitry Andric   // the size of each item in the header (see below where we emit these items).
8435ffd83dbSDimitry Andric   int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   // Figure the padding after the header before the table of address and size
8460b57cec5SDimitry Andric   // pairs who's values are PointerSize'ed.
8470b57cec5SDimitry Andric   const MCAsmInfo *asmInfo = context.getAsmInfo();
8480b57cec5SDimitry Andric   int AddrSize = asmInfo->getCodePointerSize();
8490b57cec5SDimitry Andric   int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
8500b57cec5SDimitry Andric   if (Pad == 2 * AddrSize)
8510b57cec5SDimitry Andric     Pad = 0;
8520b57cec5SDimitry Andric   Length += Pad;
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   // Add the size of the pair of PointerSize'ed values for the address and size
8550b57cec5SDimitry Andric   // of each section we have in the table.
8560b57cec5SDimitry Andric   Length += 2 * AddrSize * Sections.size();
8570b57cec5SDimitry Andric   // And the pair of terminating zeros.
8580b57cec5SDimitry Andric   Length += 2 * AddrSize;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   // Emit the header for this section.
8615ffd83dbSDimitry Andric   if (context.getDwarfFormat() == dwarf::DWARF64)
8625ffd83dbSDimitry Andric     // The DWARF64 mark.
8635ffd83dbSDimitry Andric     MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
8645ffd83dbSDimitry Andric   // The 4 (8 for DWARF64) byte length not including the length of the unit
8655ffd83dbSDimitry Andric   // length field itself.
8665ffd83dbSDimitry Andric   MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
8670b57cec5SDimitry Andric   // The 2 byte version, which is 2.
8685ffd83dbSDimitry Andric   MCOS->emitInt16(2);
8695ffd83dbSDimitry Andric   // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
8705ffd83dbSDimitry Andric   // from the start of the .debug_info.
8710b57cec5SDimitry Andric   if (InfoSectionSymbol)
8725ffd83dbSDimitry Andric     MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
8730b57cec5SDimitry Andric                           asmInfo->needsDwarfSectionOffsetDirective());
8740b57cec5SDimitry Andric   else
8755ffd83dbSDimitry Andric     MCOS->emitIntValue(0, OffsetSize);
8760b57cec5SDimitry Andric   // The 1 byte size of an address.
8775ffd83dbSDimitry Andric   MCOS->emitInt8(AddrSize);
8780b57cec5SDimitry Andric   // The 1 byte size of a segment descriptor, we use a value of zero.
8795ffd83dbSDimitry Andric   MCOS->emitInt8(0);
8800b57cec5SDimitry Andric   // Align the header with the padding if needed, before we put out the table.
8810b57cec5SDimitry Andric   for(int i = 0; i < Pad; i++)
8825ffd83dbSDimitry Andric     MCOS->emitInt8(0);
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   // Now emit the table of pairs of PointerSize'ed values for the section
8850b57cec5SDimitry Andric   // addresses and sizes.
8860b57cec5SDimitry Andric   for (MCSection *Sec : Sections) {
8870b57cec5SDimitry Andric     const MCSymbol *StartSymbol = Sec->getBeginSymbol();
8880b57cec5SDimitry Andric     MCSymbol *EndSymbol = Sec->getEndSymbol(context);
8890b57cec5SDimitry Andric     assert(StartSymbol && "StartSymbol must not be NULL");
8900b57cec5SDimitry Andric     assert(EndSymbol && "EndSymbol must not be NULL");
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric     const MCExpr *Addr = MCSymbolRefExpr::create(
8930b57cec5SDimitry Andric       StartSymbol, MCSymbolRefExpr::VK_None, context);
8945ffd83dbSDimitry Andric     const MCExpr *Size =
8955ffd83dbSDimitry Andric         makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
8965ffd83dbSDimitry Andric     MCOS->emitValue(Addr, AddrSize);
8970b57cec5SDimitry Andric     emitAbsValue(*MCOS, Size, AddrSize);
8980b57cec5SDimitry Andric   }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric   // And finally the pair of terminating zeros.
9015ffd83dbSDimitry Andric   MCOS->emitIntValue(0, AddrSize);
9025ffd83dbSDimitry Andric   MCOS->emitIntValue(0, AddrSize);
9030b57cec5SDimitry Andric }
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric // When generating dwarf for assembly source files this emits the data for
9060b57cec5SDimitry Andric // .debug_info section which contains three parts.  The header, the compile_unit
9070b57cec5SDimitry Andric // DIE and a list of label DIEs.
EmitGenDwarfInfo(MCStreamer * MCOS,const MCSymbol * AbbrevSectionSymbol,const MCSymbol * LineSectionSymbol,const MCSymbol * RangesSymbol)9080b57cec5SDimitry Andric static void EmitGenDwarfInfo(MCStreamer *MCOS,
9090b57cec5SDimitry Andric                              const MCSymbol *AbbrevSectionSymbol,
9100b57cec5SDimitry Andric                              const MCSymbol *LineSectionSymbol,
9115ffd83dbSDimitry Andric                              const MCSymbol *RangesSymbol) {
9120b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
9130b57cec5SDimitry Andric 
91481ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   // Create a symbol at the start and end of this section used in here for the
9170b57cec5SDimitry Andric   // expression to calculate the length in the header.
9180b57cec5SDimitry Andric   MCSymbol *InfoStart = context.createTempSymbol();
9195ffd83dbSDimitry Andric   MCOS->emitLabel(InfoStart);
9200b57cec5SDimitry Andric   MCSymbol *InfoEnd = context.createTempSymbol();
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   // First part: the header.
9230b57cec5SDimitry Andric 
9245ffd83dbSDimitry Andric   unsigned UnitLengthBytes =
9255ffd83dbSDimitry Andric       dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
9265ffd83dbSDimitry Andric   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
9275ffd83dbSDimitry Andric 
9285ffd83dbSDimitry Andric   if (context.getDwarfFormat() == dwarf::DWARF64)
9295ffd83dbSDimitry Andric     // Emit DWARF64 mark.
9305ffd83dbSDimitry Andric     MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
9315ffd83dbSDimitry Andric 
9325ffd83dbSDimitry Andric   // The 4 (8 for DWARF64) byte total length of the information for this
9335ffd83dbSDimitry Andric   // compilation unit, not including the unit length field itself.
9345ffd83dbSDimitry Andric   const MCExpr *Length =
9355ffd83dbSDimitry Andric       makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
9365ffd83dbSDimitry Andric   emitAbsValue(*MCOS, Length, OffsetSize);
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   // The 2 byte DWARF version.
9395ffd83dbSDimitry Andric   MCOS->emitInt16(context.getDwarfVersion());
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   // The DWARF v5 header has unit type, address size, abbrev offset.
9420b57cec5SDimitry Andric   // Earlier versions have abbrev offset, address size.
9430b57cec5SDimitry Andric   const MCAsmInfo &AsmInfo = *context.getAsmInfo();
9440b57cec5SDimitry Andric   int AddrSize = AsmInfo.getCodePointerSize();
9450b57cec5SDimitry Andric   if (context.getDwarfVersion() >= 5) {
9465ffd83dbSDimitry Andric     MCOS->emitInt8(dwarf::DW_UT_compile);
9475ffd83dbSDimitry Andric     MCOS->emitInt8(AddrSize);
9480b57cec5SDimitry Andric   }
9495ffd83dbSDimitry Andric   // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
9505ffd83dbSDimitry Andric   // the .debug_abbrev.
9515ffd83dbSDimitry Andric   if (AbbrevSectionSymbol)
9525ffd83dbSDimitry Andric     MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
9530b57cec5SDimitry Andric                           AsmInfo.needsDwarfSectionOffsetDirective());
9545ffd83dbSDimitry Andric   else
9555ffd83dbSDimitry Andric     // Since the abbrevs are at the start of the section, the offset is zero.
9565ffd83dbSDimitry Andric     MCOS->emitIntValue(0, OffsetSize);
9570b57cec5SDimitry Andric   if (context.getDwarfVersion() <= 4)
9585ffd83dbSDimitry Andric     MCOS->emitInt8(AddrSize);
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   // Second part: the compile_unit DIE.
9610b57cec5SDimitry Andric 
9620b57cec5SDimitry Andric   // The DW_TAG_compile_unit DIE abbrev (1).
9635ffd83dbSDimitry Andric   MCOS->emitULEB128IntValue(1);
9640b57cec5SDimitry Andric 
9655ffd83dbSDimitry Andric   // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
9665ffd83dbSDimitry Andric   // .debug_line section.
9670b57cec5SDimitry Andric   if (LineSectionSymbol)
9685ffd83dbSDimitry Andric     MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
9690b57cec5SDimitry Andric                           AsmInfo.needsDwarfSectionOffsetDirective());
9700b57cec5SDimitry Andric   else
9715ffd83dbSDimitry Andric     // The line table is at the start of the section, so the offset is zero.
9725ffd83dbSDimitry Andric     MCOS->emitIntValue(0, OffsetSize);
9730b57cec5SDimitry Andric 
9745ffd83dbSDimitry Andric   if (RangesSymbol) {
9755ffd83dbSDimitry Andric     // There are multiple sections containing code, so we must use
9765ffd83dbSDimitry Andric     // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
9775ffd83dbSDimitry Andric     // start of the .debug_ranges/.debug_rnglists.
9785ffd83dbSDimitry Andric     MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
9790b57cec5SDimitry Andric   } else {
9800b57cec5SDimitry Andric     // If we only have one non-empty code section, we can use the simpler
9810b57cec5SDimitry Andric     // AT_low_pc and AT_high_pc attributes.
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     // Find the first (and only) non-empty text section
9840b57cec5SDimitry Andric     auto &Sections = context.getGenDwarfSectionSyms();
9850b57cec5SDimitry Andric     const auto TextSection = Sections.begin();
9860b57cec5SDimitry Andric     assert(TextSection != Sections.end() && "No text section found");
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric     MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
9890b57cec5SDimitry Andric     MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
9900b57cec5SDimitry Andric     assert(StartSymbol && "StartSymbol must not be NULL");
9910b57cec5SDimitry Andric     assert(EndSymbol && "EndSymbol must not be NULL");
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     // AT_low_pc, the first address of the default .text section.
9940b57cec5SDimitry Andric     const MCExpr *Start = MCSymbolRefExpr::create(
9950b57cec5SDimitry Andric         StartSymbol, MCSymbolRefExpr::VK_None, context);
9965ffd83dbSDimitry Andric     MCOS->emitValue(Start, AddrSize);
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric     // AT_high_pc, the last address of the default .text section.
9990b57cec5SDimitry Andric     const MCExpr *End = MCSymbolRefExpr::create(
10000b57cec5SDimitry Andric       EndSymbol, MCSymbolRefExpr::VK_None, context);
10015ffd83dbSDimitry Andric     MCOS->emitValue(End, AddrSize);
10020b57cec5SDimitry Andric   }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // AT_name, the name of the source file.  Reconstruct from the first directory
10050b57cec5SDimitry Andric   // and file table entries.
10060b57cec5SDimitry Andric   const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
10070b57cec5SDimitry Andric   if (MCDwarfDirs.size() > 0) {
10085ffd83dbSDimitry Andric     MCOS->emitBytes(MCDwarfDirs[0]);
10095ffd83dbSDimitry Andric     MCOS->emitBytes(sys::path::get_separator());
10100b57cec5SDimitry Andric   }
10110b57cec5SDimitry Andric   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
10120b57cec5SDimitry Andric   // MCDwarfFiles might be empty if we have an empty source file.
10130b57cec5SDimitry Andric   // If it's not empty, [0] is unused and [1] is the first actual file.
10140b57cec5SDimitry Andric   assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
10150b57cec5SDimitry Andric   const MCDwarfFile &RootFile =
10160b57cec5SDimitry Andric       MCDwarfFiles.empty()
10170b57cec5SDimitry Andric           ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
10180b57cec5SDimitry Andric           : MCDwarfFiles[1];
10195ffd83dbSDimitry Andric   MCOS->emitBytes(RootFile.Name);
10205ffd83dbSDimitry Andric   MCOS->emitInt8(0); // NULL byte to terminate the string.
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   // AT_comp_dir, the working directory the assembly was done in.
10230b57cec5SDimitry Andric   if (!context.getCompilationDir().empty()) {
10245ffd83dbSDimitry Andric     MCOS->emitBytes(context.getCompilationDir());
10255ffd83dbSDimitry Andric     MCOS->emitInt8(0); // NULL byte to terminate the string.
10260b57cec5SDimitry Andric   }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   // AT_APPLE_flags, the command line arguments of the assembler tool.
10290b57cec5SDimitry Andric   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
10300b57cec5SDimitry Andric   if (!DwarfDebugFlags.empty()){
10315ffd83dbSDimitry Andric     MCOS->emitBytes(DwarfDebugFlags);
10325ffd83dbSDimitry Andric     MCOS->emitInt8(0); // NULL byte to terminate the string.
10330b57cec5SDimitry Andric   }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   // AT_producer, the version of the assembler tool.
10360b57cec5SDimitry Andric   StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
10370b57cec5SDimitry Andric   if (!DwarfDebugProducer.empty())
10385ffd83dbSDimitry Andric     MCOS->emitBytes(DwarfDebugProducer);
10390b57cec5SDimitry Andric   else
10405ffd83dbSDimitry Andric     MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
10415ffd83dbSDimitry Andric   MCOS->emitInt8(0); // NULL byte to terminate the string.
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dwarf2
10440b57cec5SDimitry Andric   // draft has no standard code for assembler.
10455ffd83dbSDimitry Andric   MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric   // Third part: the list of label DIEs.
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric   // Loop on saved info for dwarf labels and create the DIEs for them.
10500b57cec5SDimitry Andric   const std::vector<MCGenDwarfLabelEntry> &Entries =
10510b57cec5SDimitry Andric       MCOS->getContext().getMCGenDwarfLabelEntries();
10520b57cec5SDimitry Andric   for (const auto &Entry : Entries) {
10530b57cec5SDimitry Andric     // The DW_TAG_label DIE abbrev (2).
10545ffd83dbSDimitry Andric     MCOS->emitULEB128IntValue(2);
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric     // AT_name, of the label without any leading underbar.
10575ffd83dbSDimitry Andric     MCOS->emitBytes(Entry.getName());
10585ffd83dbSDimitry Andric     MCOS->emitInt8(0); // NULL byte to terminate the string.
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric     // AT_decl_file, index into the file table.
10615ffd83dbSDimitry Andric     MCOS->emitInt32(Entry.getFileNumber());
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric     // AT_decl_line, source line number.
10645ffd83dbSDimitry Andric     MCOS->emitInt32(Entry.getLineNumber());
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric     // AT_low_pc, start address of the label.
10670b57cec5SDimitry Andric     const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
10680b57cec5SDimitry Andric                                              MCSymbolRefExpr::VK_None, context);
10695ffd83dbSDimitry Andric     MCOS->emitValue(AT_low_pc, AddrSize);
10700b57cec5SDimitry Andric   }
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric   // Add the NULL DIE terminating the Compile Unit DIE's.
10735ffd83dbSDimitry Andric   MCOS->emitInt8(0);
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   // Now set the value of the symbol at the end of the info section.
10765ffd83dbSDimitry Andric   MCOS->emitLabel(InfoEnd);
10770b57cec5SDimitry Andric }
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric // When generating dwarf for assembly source files this emits the data for
10800b57cec5SDimitry Andric // .debug_ranges section. We only emit one range list, which spans all of the
10810b57cec5SDimitry Andric // executable sections of this file.
emitGenDwarfRanges(MCStreamer * MCOS)10825ffd83dbSDimitry Andric static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
10830b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
10840b57cec5SDimitry Andric   auto &Sections = context.getGenDwarfSectionSyms();
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   const MCAsmInfo *AsmInfo = context.getAsmInfo();
10870b57cec5SDimitry Andric   int AddrSize = AsmInfo->getCodePointerSize();
10885ffd83dbSDimitry Andric   MCSymbol *RangesSymbol;
10890b57cec5SDimitry Andric 
10905ffd83dbSDimitry Andric   if (MCOS->getContext().getDwarfVersion() >= 5) {
109181ad6265SDimitry Andric     MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
10925ffd83dbSDimitry Andric     MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
10935ffd83dbSDimitry Andric     MCOS->AddComment("Offset entry count");
10945ffd83dbSDimitry Andric     MCOS->emitInt32(0);
1095e8d8bef9SDimitry Andric     RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
10965ffd83dbSDimitry Andric     MCOS->emitLabel(RangesSymbol);
10970b57cec5SDimitry Andric     for (MCSection *Sec : Sections) {
10980b57cec5SDimitry Andric       const MCSymbol *StartSymbol = Sec->getBeginSymbol();
10995ffd83dbSDimitry Andric       const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
11005ffd83dbSDimitry Andric       const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
11015ffd83dbSDimitry Andric           StartSymbol, MCSymbolRefExpr::VK_None, context);
11025ffd83dbSDimitry Andric       const MCExpr *SectionSize =
11035ffd83dbSDimitry Andric           makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
11045ffd83dbSDimitry Andric       MCOS->emitInt8(dwarf::DW_RLE_start_length);
11055ffd83dbSDimitry Andric       MCOS->emitValue(SectionStartAddr, AddrSize);
11065ffd83dbSDimitry Andric       MCOS->emitULEB128Value(SectionSize);
11075ffd83dbSDimitry Andric     }
11085ffd83dbSDimitry Andric     MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
11095ffd83dbSDimitry Andric     MCOS->emitLabel(EndSymbol);
11105ffd83dbSDimitry Andric   } else {
111181ad6265SDimitry Andric     MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection());
1112e8d8bef9SDimitry Andric     RangesSymbol = context.createTempSymbol("debug_ranges_start");
11135ffd83dbSDimitry Andric     MCOS->emitLabel(RangesSymbol);
11145ffd83dbSDimitry Andric     for (MCSection *Sec : Sections) {
11155ffd83dbSDimitry Andric       const MCSymbol *StartSymbol = Sec->getBeginSymbol();
11165ffd83dbSDimitry Andric       const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
11170b57cec5SDimitry Andric 
11185ffd83dbSDimitry Andric       // Emit a base address selection entry for the section start.
11190b57cec5SDimitry Andric       const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
11200b57cec5SDimitry Andric           StartSymbol, MCSymbolRefExpr::VK_None, context);
11210b57cec5SDimitry Andric       MCOS->emitFill(AddrSize, 0xFF);
11225ffd83dbSDimitry Andric       MCOS->emitValue(SectionStartAddr, AddrSize);
11230b57cec5SDimitry Andric 
11245ffd83dbSDimitry Andric       // Emit a range list entry spanning this section.
11255ffd83dbSDimitry Andric       const MCExpr *SectionSize =
11265ffd83dbSDimitry Andric           makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
11275ffd83dbSDimitry Andric       MCOS->emitIntValue(0, AddrSize);
11280b57cec5SDimitry Andric       emitAbsValue(*MCOS, SectionSize, AddrSize);
11290b57cec5SDimitry Andric     }
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric     // Emit end of list entry
11325ffd83dbSDimitry Andric     MCOS->emitIntValue(0, AddrSize);
11335ffd83dbSDimitry Andric     MCOS->emitIntValue(0, AddrSize);
11345ffd83dbSDimitry Andric   }
11355ffd83dbSDimitry Andric 
11365ffd83dbSDimitry Andric   return RangesSymbol;
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric //
11400b57cec5SDimitry Andric // When generating dwarf for assembly source files this emits the Dwarf
11410b57cec5SDimitry Andric // sections.
11420b57cec5SDimitry Andric //
Emit(MCStreamer * MCOS)11430b57cec5SDimitry Andric void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
11440b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric   // Create the dwarf sections in this order (.debug_line already created).
11470b57cec5SDimitry Andric   const MCAsmInfo *AsmInfo = context.getAsmInfo();
11480b57cec5SDimitry Andric   bool CreateDwarfSectionSymbols =
11490b57cec5SDimitry Andric       AsmInfo->doesDwarfUseRelocationsAcrossSections();
11500b57cec5SDimitry Andric   MCSymbol *LineSectionSymbol = nullptr;
11510b57cec5SDimitry Andric   if (CreateDwarfSectionSymbols)
11520b57cec5SDimitry Andric     LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
11530b57cec5SDimitry Andric   MCSymbol *AbbrevSectionSymbol = nullptr;
11540b57cec5SDimitry Andric   MCSymbol *InfoSectionSymbol = nullptr;
11555ffd83dbSDimitry Andric   MCSymbol *RangesSymbol = nullptr;
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric   // Create end symbols for each section, and remove empty sections
11580b57cec5SDimitry Andric   MCOS->getContext().finalizeDwarfSections(*MCOS);
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   // If there are no sections to generate debug info for, we don't need
11610b57cec5SDimitry Andric   // to do anything
11620b57cec5SDimitry Andric   if (MCOS->getContext().getGenDwarfSectionSyms().empty())
11630b57cec5SDimitry Andric     return;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric   // We only use the .debug_ranges section if we have multiple code sections,
11660b57cec5SDimitry Andric   // and we are emitting a DWARF version which supports it.
11670b57cec5SDimitry Andric   const bool UseRangesSection =
11680b57cec5SDimitry Andric       MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
11690b57cec5SDimitry Andric       MCOS->getContext().getDwarfVersion() >= 3;
11700b57cec5SDimitry Andric   CreateDwarfSectionSymbols |= UseRangesSection;
11710b57cec5SDimitry Andric 
117281ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
11730b57cec5SDimitry Andric   if (CreateDwarfSectionSymbols) {
11740b57cec5SDimitry Andric     InfoSectionSymbol = context.createTempSymbol();
11755ffd83dbSDimitry Andric     MCOS->emitLabel(InfoSectionSymbol);
11760b57cec5SDimitry Andric   }
117781ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
11780b57cec5SDimitry Andric   if (CreateDwarfSectionSymbols) {
11790b57cec5SDimitry Andric     AbbrevSectionSymbol = context.createTempSymbol();
11805ffd83dbSDimitry Andric     MCOS->emitLabel(AbbrevSectionSymbol);
11810b57cec5SDimitry Andric   }
11820b57cec5SDimitry Andric 
118381ad6265SDimitry Andric   MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   // Output the data for .debug_aranges section.
11860b57cec5SDimitry Andric   EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
11870b57cec5SDimitry Andric 
11885ffd83dbSDimitry Andric   if (UseRangesSection) {
11895ffd83dbSDimitry Andric     RangesSymbol = emitGenDwarfRanges(MCOS);
11905ffd83dbSDimitry Andric     assert(RangesSymbol);
11915ffd83dbSDimitry Andric   }
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric   // Output the data for .debug_abbrev section.
11940b57cec5SDimitry Andric   EmitGenDwarfAbbrev(MCOS);
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric   // Output the data for .debug_info section.
11975ffd83dbSDimitry Andric   EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric //
12010b57cec5SDimitry Andric // When generating dwarf for assembly source files this is called when symbol
12020b57cec5SDimitry Andric // for a label is created.  If this symbol is not a temporary and is in the
12030b57cec5SDimitry Andric // section that dwarf is being generated for, save the needed info to create
12040b57cec5SDimitry Andric // a dwarf label.
12050b57cec5SDimitry Andric //
Make(MCSymbol * Symbol,MCStreamer * MCOS,SourceMgr & SrcMgr,SMLoc & Loc)12060b57cec5SDimitry Andric void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
12070b57cec5SDimitry Andric                                      SourceMgr &SrcMgr, SMLoc &Loc) {
12080b57cec5SDimitry Andric   // We won't create dwarf labels for temporary symbols.
12090b57cec5SDimitry Andric   if (Symbol->isTemporary())
12100b57cec5SDimitry Andric     return;
12110b57cec5SDimitry Andric   MCContext &context = MCOS->getContext();
12120b57cec5SDimitry Andric   // We won't create dwarf labels for symbols in sections that we are not
12130b57cec5SDimitry Andric   // generating debug info for.
12140b57cec5SDimitry Andric   if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
12150b57cec5SDimitry Andric     return;
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   // The dwarf label's name does not have the symbol name's leading
12180b57cec5SDimitry Andric   // underbar if any.
12190b57cec5SDimitry Andric   StringRef Name = Symbol->getName();
12205f757f3fSDimitry Andric   if (Name.starts_with("_"))
12210b57cec5SDimitry Andric     Name = Name.substr(1, Name.size()-1);
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // Get the dwarf file number to be used for the dwarf label.
12240b57cec5SDimitry Andric   unsigned FileNumber = context.getGenDwarfFileNumber();
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric   // Finding the line number is the expensive part which is why we just don't
12270b57cec5SDimitry Andric   // pass it in as for some symbols we won't create a dwarf label.
12280b57cec5SDimitry Andric   unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
12290b57cec5SDimitry Andric   unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
12320b57cec5SDimitry Andric   // values so that they don't have things like an ARM thumb bit from the
12330b57cec5SDimitry Andric   // original symbol. So when used they won't get a low bit set after
12340b57cec5SDimitry Andric   // relocation.
12350b57cec5SDimitry Andric   MCSymbol *Label = context.createTempSymbol();
12365ffd83dbSDimitry Andric   MCOS->emitLabel(Label);
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   // Create and entry for the info and add it to the other entries.
12390b57cec5SDimitry Andric   MCOS->getContext().addMCGenDwarfLabelEntry(
12400b57cec5SDimitry Andric       MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
getDataAlignmentFactor(MCStreamer & streamer)12430b57cec5SDimitry Andric static int getDataAlignmentFactor(MCStreamer &streamer) {
12440b57cec5SDimitry Andric   MCContext &context = streamer.getContext();
12450b57cec5SDimitry Andric   const MCAsmInfo *asmInfo = context.getAsmInfo();
12460b57cec5SDimitry Andric   int size = asmInfo->getCalleeSaveStackSlotSize();
12470b57cec5SDimitry Andric   if (asmInfo->isStackGrowthDirectionUp())
12480b57cec5SDimitry Andric     return size;
12490b57cec5SDimitry Andric   else
12500b57cec5SDimitry Andric     return -size;
12510b57cec5SDimitry Andric }
12520b57cec5SDimitry Andric 
getSizeForEncoding(MCStreamer & streamer,unsigned symbolEncoding)12530b57cec5SDimitry Andric static unsigned getSizeForEncoding(MCStreamer &streamer,
12540b57cec5SDimitry Andric                                    unsigned symbolEncoding) {
12550b57cec5SDimitry Andric   MCContext &context = streamer.getContext();
12560b57cec5SDimitry Andric   unsigned format = symbolEncoding & 0x0f;
12570b57cec5SDimitry Andric   switch (format) {
12580b57cec5SDimitry Andric   default: llvm_unreachable("Unknown Encoding");
12590b57cec5SDimitry Andric   case dwarf::DW_EH_PE_absptr:
12600b57cec5SDimitry Andric   case dwarf::DW_EH_PE_signed:
12610b57cec5SDimitry Andric     return context.getAsmInfo()->getCodePointerSize();
12620b57cec5SDimitry Andric   case dwarf::DW_EH_PE_udata2:
12630b57cec5SDimitry Andric   case dwarf::DW_EH_PE_sdata2:
12640b57cec5SDimitry Andric     return 2;
12650b57cec5SDimitry Andric   case dwarf::DW_EH_PE_udata4:
12660b57cec5SDimitry Andric   case dwarf::DW_EH_PE_sdata4:
12670b57cec5SDimitry Andric     return 4;
12680b57cec5SDimitry Andric   case dwarf::DW_EH_PE_udata8:
12690b57cec5SDimitry Andric   case dwarf::DW_EH_PE_sdata8:
12700b57cec5SDimitry Andric     return 8;
12710b57cec5SDimitry Andric   }
12720b57cec5SDimitry Andric }
12730b57cec5SDimitry Andric 
emitFDESymbol(MCObjectStreamer & streamer,const MCSymbol & symbol,unsigned symbolEncoding,bool isEH)12740b57cec5SDimitry Andric static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
12750b57cec5SDimitry Andric                        unsigned symbolEncoding, bool isEH) {
12760b57cec5SDimitry Andric   MCContext &context = streamer.getContext();
12770b57cec5SDimitry Andric   const MCAsmInfo *asmInfo = context.getAsmInfo();
12780b57cec5SDimitry Andric   const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
12790b57cec5SDimitry Andric                                                  symbolEncoding,
12800b57cec5SDimitry Andric                                                  streamer);
12810b57cec5SDimitry Andric   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
12820b57cec5SDimitry Andric   if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
12830b57cec5SDimitry Andric     emitAbsValue(streamer, v, size);
12840b57cec5SDimitry Andric   else
12855ffd83dbSDimitry Andric     streamer.emitValue(v, size);
12860b57cec5SDimitry Andric }
12870b57cec5SDimitry Andric 
EmitPersonality(MCStreamer & streamer,const MCSymbol & symbol,unsigned symbolEncoding)12880b57cec5SDimitry Andric static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
12890b57cec5SDimitry Andric                             unsigned symbolEncoding) {
12900b57cec5SDimitry Andric   MCContext &context = streamer.getContext();
12910b57cec5SDimitry Andric   const MCAsmInfo *asmInfo = context.getAsmInfo();
12920b57cec5SDimitry Andric   const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
12930b57cec5SDimitry Andric                                                          symbolEncoding,
12940b57cec5SDimitry Andric                                                          streamer);
12950b57cec5SDimitry Andric   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
12965ffd83dbSDimitry Andric   streamer.emitValue(v, size);
12970b57cec5SDimitry Andric }
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric namespace {
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric class FrameEmitterImpl {
1302*36b606aeSDimitry Andric   int64_t CFAOffset = 0;
1303*36b606aeSDimitry Andric   int64_t InitialCFAOffset = 0;
13040b57cec5SDimitry Andric   bool IsEH;
13050b57cec5SDimitry Andric   MCObjectStreamer &Streamer;
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric public:
FrameEmitterImpl(bool IsEH,MCObjectStreamer & Streamer)13080b57cec5SDimitry Andric   FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
13090b57cec5SDimitry Andric       : IsEH(IsEH), Streamer(Streamer) {}
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric   /// Emit the unwind information in a compact way.
13120b57cec5SDimitry Andric   void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric   const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
13150b57cec5SDimitry Andric   void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
13160b57cec5SDimitry Andric                bool LastInSection, const MCSymbol &SectionStart);
13175ffd83dbSDimitry Andric   void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
13180b57cec5SDimitry Andric                            MCSymbol *BaseLabel);
13195ffd83dbSDimitry Andric   void emitCFIInstruction(const MCCFIInstruction &Instr);
13200b57cec5SDimitry Andric };
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric } // end anonymous namespace
13230b57cec5SDimitry Andric 
emitEncodingByte(MCObjectStreamer & Streamer,unsigned Encoding)13240b57cec5SDimitry Andric static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
13255ffd83dbSDimitry Andric   Streamer.emitInt8(Encoding);
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
emitCFIInstruction(const MCCFIInstruction & Instr)13285ffd83dbSDimitry Andric void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
13290b57cec5SDimitry Andric   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
13300b57cec5SDimitry Andric   auto *MRI = Streamer.getContext().getRegisterInfo();
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric   switch (Instr.getOperation()) {
13330b57cec5SDimitry Andric   case MCCFIInstruction::OpRegister: {
13340b57cec5SDimitry Andric     unsigned Reg1 = Instr.getRegister();
13350b57cec5SDimitry Andric     unsigned Reg2 = Instr.getRegister2();
13360b57cec5SDimitry Andric     if (!IsEH) {
13370b57cec5SDimitry Andric       Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
13380b57cec5SDimitry Andric       Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
13390b57cec5SDimitry Andric     }
13405ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_register);
13415ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Reg1);
13425ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Reg2);
13430b57cec5SDimitry Andric     return;
13440b57cec5SDimitry Andric   }
13450b57cec5SDimitry Andric   case MCCFIInstruction::OpWindowSave:
13465ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
13470b57cec5SDimitry Andric     return;
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric   case MCCFIInstruction::OpNegateRAState:
13505ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
13510b57cec5SDimitry Andric     return;
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   case MCCFIInstruction::OpUndefined: {
13540b57cec5SDimitry Andric     unsigned Reg = Instr.getRegister();
13555ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_undefined);
13565ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Reg);
13570b57cec5SDimitry Andric     return;
13580b57cec5SDimitry Andric   }
13590b57cec5SDimitry Andric   case MCCFIInstruction::OpAdjustCfaOffset:
13600b57cec5SDimitry Andric   case MCCFIInstruction::OpDefCfaOffset: {
13610b57cec5SDimitry Andric     const bool IsRelative =
13620b57cec5SDimitry Andric       Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
13630b57cec5SDimitry Andric 
13645ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric     if (IsRelative)
13670b57cec5SDimitry Andric       CFAOffset += Instr.getOffset();
13680b57cec5SDimitry Andric     else
13695ffd83dbSDimitry Andric       CFAOffset = Instr.getOffset();
13700b57cec5SDimitry Andric 
13715ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(CFAOffset);
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric     return;
13740b57cec5SDimitry Andric   }
13750b57cec5SDimitry Andric   case MCCFIInstruction::OpDefCfa: {
13760b57cec5SDimitry Andric     unsigned Reg = Instr.getRegister();
13770b57cec5SDimitry Andric     if (!IsEH)
13780b57cec5SDimitry Andric       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
13795ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
13805ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Reg);
13815ffd83dbSDimitry Andric     CFAOffset = Instr.getOffset();
13825ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(CFAOffset);
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric     return;
13850b57cec5SDimitry Andric   }
13860b57cec5SDimitry Andric   case MCCFIInstruction::OpDefCfaRegister: {
13870b57cec5SDimitry Andric     unsigned Reg = Instr.getRegister();
13880b57cec5SDimitry Andric     if (!IsEH)
13890b57cec5SDimitry Andric       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
13905ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
13915ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Reg);
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric     return;
13940b57cec5SDimitry Andric   }
1395fe6060f1SDimitry Andric   // TODO: Implement `_sf` variants if/when they need to be emitted.
1396fe6060f1SDimitry Andric   case MCCFIInstruction::OpLLVMDefAspaceCfa: {
1397fe6060f1SDimitry Andric     unsigned Reg = Instr.getRegister();
1398fe6060f1SDimitry Andric     if (!IsEH)
1399fe6060f1SDimitry Andric       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1400fe6060f1SDimitry Andric     Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1);
1401fe6060f1SDimitry Andric     Streamer.emitULEB128IntValue(Reg);
1402fe6060f1SDimitry Andric     CFAOffset = Instr.getOffset();
1403fe6060f1SDimitry Andric     Streamer.emitULEB128IntValue(CFAOffset);
1404fe6060f1SDimitry Andric     Streamer.emitULEB128IntValue(Instr.getAddressSpace());
1405fe6060f1SDimitry Andric 
1406fe6060f1SDimitry Andric     return;
1407fe6060f1SDimitry Andric   }
14080b57cec5SDimitry Andric   case MCCFIInstruction::OpOffset:
14090b57cec5SDimitry Andric   case MCCFIInstruction::OpRelOffset: {
14100b57cec5SDimitry Andric     const bool IsRelative =
14110b57cec5SDimitry Andric       Instr.getOperation() == MCCFIInstruction::OpRelOffset;
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric     unsigned Reg = Instr.getRegister();
14140b57cec5SDimitry Andric     if (!IsEH)
14150b57cec5SDimitry Andric       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
14160b57cec5SDimitry Andric 
1417*36b606aeSDimitry Andric     int64_t Offset = Instr.getOffset();
14180b57cec5SDimitry Andric     if (IsRelative)
14190b57cec5SDimitry Andric       Offset -= CFAOffset;
14200b57cec5SDimitry Andric     Offset = Offset / dataAlignmentFactor;
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric     if (Offset < 0) {
14235ffd83dbSDimitry Andric       Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
14245ffd83dbSDimitry Andric       Streamer.emitULEB128IntValue(Reg);
14255ffd83dbSDimitry Andric       Streamer.emitSLEB128IntValue(Offset);
14260b57cec5SDimitry Andric     } else if (Reg < 64) {
14275ffd83dbSDimitry Andric       Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
14285ffd83dbSDimitry Andric       Streamer.emitULEB128IntValue(Offset);
14290b57cec5SDimitry Andric     } else {
14305ffd83dbSDimitry Andric       Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
14315ffd83dbSDimitry Andric       Streamer.emitULEB128IntValue(Reg);
14325ffd83dbSDimitry Andric       Streamer.emitULEB128IntValue(Offset);
14330b57cec5SDimitry Andric     }
14340b57cec5SDimitry Andric     return;
14350b57cec5SDimitry Andric   }
14360b57cec5SDimitry Andric   case MCCFIInstruction::OpRememberState:
14375ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_remember_state);
14380b57cec5SDimitry Andric     return;
14390b57cec5SDimitry Andric   case MCCFIInstruction::OpRestoreState:
14405ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_restore_state);
14410b57cec5SDimitry Andric     return;
14420b57cec5SDimitry Andric   case MCCFIInstruction::OpSameValue: {
14430b57cec5SDimitry Andric     unsigned Reg = Instr.getRegister();
14445ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_same_value);
14455ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Reg);
14460b57cec5SDimitry Andric     return;
14470b57cec5SDimitry Andric   }
14480b57cec5SDimitry Andric   case MCCFIInstruction::OpRestore: {
14490b57cec5SDimitry Andric     unsigned Reg = Instr.getRegister();
14500b57cec5SDimitry Andric     if (!IsEH)
14510b57cec5SDimitry Andric       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
14520b57cec5SDimitry Andric     if (Reg < 64) {
14535ffd83dbSDimitry Andric       Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
14540b57cec5SDimitry Andric     } else {
14555ffd83dbSDimitry Andric       Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
14565ffd83dbSDimitry Andric       Streamer.emitULEB128IntValue(Reg);
14570b57cec5SDimitry Andric     }
14580b57cec5SDimitry Andric     return;
14590b57cec5SDimitry Andric   }
14600b57cec5SDimitry Andric   case MCCFIInstruction::OpGnuArgsSize:
14615ffd83dbSDimitry Andric     Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
14625ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(Instr.getOffset());
14630b57cec5SDimitry Andric     return;
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   case MCCFIInstruction::OpEscape:
14665ffd83dbSDimitry Andric     Streamer.emitBytes(Instr.getValues());
14670b57cec5SDimitry Andric     return;
14680fca6ea1SDimitry Andric   case MCCFIInstruction::OpLabel:
14690fca6ea1SDimitry Andric     Streamer.emitLabel(Instr.getCfiLabel(), Instr.getLoc());
14700fca6ea1SDimitry Andric     return;
14710b57cec5SDimitry Andric   }
14720b57cec5SDimitry Andric   llvm_unreachable("Unhandled case in switch");
14730b57cec5SDimitry Andric }
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric /// Emit frame instructions to describe the layout of the frame.
emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,MCSymbol * BaseLabel)14765ffd83dbSDimitry Andric void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
14770b57cec5SDimitry Andric                                            MCSymbol *BaseLabel) {
14780b57cec5SDimitry Andric   for (const MCCFIInstruction &Instr : Instrs) {
14790b57cec5SDimitry Andric     MCSymbol *Label = Instr.getLabel();
14800b57cec5SDimitry Andric     // Throw out move if the label is invalid.
14810b57cec5SDimitry Andric     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric     // Advance row if new location.
14840b57cec5SDimitry Andric     if (BaseLabel && Label) {
14850b57cec5SDimitry Andric       MCSymbol *ThisSym = Label;
14860b57cec5SDimitry Andric       if (ThisSym != BaseLabel) {
148706c3fb27SDimitry Andric         Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym, Instr.getLoc());
14880b57cec5SDimitry Andric         BaseLabel = ThisSym;
14890b57cec5SDimitry Andric       }
14900b57cec5SDimitry Andric     }
14910b57cec5SDimitry Andric 
14925ffd83dbSDimitry Andric     emitCFIInstruction(Instr);
14930b57cec5SDimitry Andric   }
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric /// Emit the unwind information in a compact way.
EmitCompactUnwind(const MCDwarfFrameInfo & Frame)14970b57cec5SDimitry Andric void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
14980b57cec5SDimitry Andric   MCContext &Context = Streamer.getContext();
14990b57cec5SDimitry Andric   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   // range-start range-length  compact-unwind-enc personality-func   lsda
15020b57cec5SDimitry Andric   //  _foo       LfooEnd-_foo  0x00000023          0                 0
15030b57cec5SDimitry Andric   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
15040b57cec5SDimitry Andric   //
15050b57cec5SDimitry Andric   //   .section __LD,__compact_unwind,regular,debug
15060b57cec5SDimitry Andric   //
15070b57cec5SDimitry Andric   //   # compact unwind for _foo
15080b57cec5SDimitry Andric   //   .quad _foo
15090b57cec5SDimitry Andric   //   .set L1,LfooEnd-_foo
15100b57cec5SDimitry Andric   //   .long L1
15110b57cec5SDimitry Andric   //   .long 0x01010001
15120b57cec5SDimitry Andric   //   .quad 0
15130b57cec5SDimitry Andric   //   .quad 0
15140b57cec5SDimitry Andric   //
15150b57cec5SDimitry Andric   //   # compact unwind for _bar
15160b57cec5SDimitry Andric   //   .quad _bar
15170b57cec5SDimitry Andric   //   .set L2,LbarEnd-_bar
15180b57cec5SDimitry Andric   //   .long L2
15190b57cec5SDimitry Andric   //   .long 0x01020011
15200b57cec5SDimitry Andric   //   .quad __gxx_personality
15210b57cec5SDimitry Andric   //   .quad except_tab1
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   uint32_t Encoding = Frame.CompactUnwindEncoding;
15240b57cec5SDimitry Andric   if (!Encoding) return;
15250b57cec5SDimitry Andric   bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric   // The encoding needs to know we have an LSDA.
15280b57cec5SDimitry Andric   if (!DwarfEHFrameOnly && Frame.Lsda)
15290b57cec5SDimitry Andric     Encoding |= 0x40000000;
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric   // Range Start
15320b57cec5SDimitry Andric   unsigned FDEEncoding = MOFI->getFDEEncoding();
15330b57cec5SDimitry Andric   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
15345ffd83dbSDimitry Andric   Streamer.emitSymbolValue(Frame.Begin, Size);
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   // Range Length
15375ffd83dbSDimitry Andric   const MCExpr *Range =
15385ffd83dbSDimitry Andric       makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
15390b57cec5SDimitry Andric   emitAbsValue(Streamer, Range, 4);
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric   // Compact Encoding
15420b57cec5SDimitry Andric   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
15435ffd83dbSDimitry Andric   Streamer.emitIntValue(Encoding, Size);
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric   // Personality Function
15460b57cec5SDimitry Andric   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
15470b57cec5SDimitry Andric   if (!DwarfEHFrameOnly && Frame.Personality)
15485ffd83dbSDimitry Andric     Streamer.emitSymbolValue(Frame.Personality, Size);
15490b57cec5SDimitry Andric   else
15505ffd83dbSDimitry Andric     Streamer.emitIntValue(0, Size); // No personality fn
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric   // LSDA
15530b57cec5SDimitry Andric   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
15540b57cec5SDimitry Andric   if (!DwarfEHFrameOnly && Frame.Lsda)
15555ffd83dbSDimitry Andric     Streamer.emitSymbolValue(Frame.Lsda, Size);
15560b57cec5SDimitry Andric   else
15575ffd83dbSDimitry Andric     Streamer.emitIntValue(0, Size); // No LSDA
15580b57cec5SDimitry Andric }
15590b57cec5SDimitry Andric 
getCIEVersion(bool IsEH,unsigned DwarfVersion)15600b57cec5SDimitry Andric static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
15610b57cec5SDimitry Andric   if (IsEH)
15620b57cec5SDimitry Andric     return 1;
15630b57cec5SDimitry Andric   switch (DwarfVersion) {
15640b57cec5SDimitry Andric   case 2:
15650b57cec5SDimitry Andric     return 1;
15660b57cec5SDimitry Andric   case 3:
15670b57cec5SDimitry Andric     return 3;
15680b57cec5SDimitry Andric   case 4:
15690b57cec5SDimitry Andric   case 5:
15700b57cec5SDimitry Andric     return 4;
15710b57cec5SDimitry Andric   }
15720b57cec5SDimitry Andric   llvm_unreachable("Unknown version");
15730b57cec5SDimitry Andric }
15740b57cec5SDimitry Andric 
EmitCIE(const MCDwarfFrameInfo & Frame)15750b57cec5SDimitry Andric const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
15760b57cec5SDimitry Andric   MCContext &context = Streamer.getContext();
15770b57cec5SDimitry Andric   const MCRegisterInfo *MRI = context.getRegisterInfo();
15780b57cec5SDimitry Andric   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric   MCSymbol *sectionStart = context.createTempSymbol();
15815ffd83dbSDimitry Andric   Streamer.emitLabel(sectionStart);
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   MCSymbol *sectionEnd = context.createTempSymbol();
15840b57cec5SDimitry Andric 
15855ffd83dbSDimitry Andric   dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
15865ffd83dbSDimitry Andric   unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
15875ffd83dbSDimitry Andric   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
15885ffd83dbSDimitry Andric   bool IsDwarf64 = Format == dwarf::DWARF64;
15895ffd83dbSDimitry Andric 
15905ffd83dbSDimitry Andric   if (IsDwarf64)
15915ffd83dbSDimitry Andric     // DWARF64 mark
15925ffd83dbSDimitry Andric     Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
15935ffd83dbSDimitry Andric 
15940b57cec5SDimitry Andric   // Length
15955ffd83dbSDimitry Andric   const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
15965ffd83dbSDimitry Andric                                                *sectionEnd, UnitLengthBytes);
15975ffd83dbSDimitry Andric   emitAbsValue(Streamer, Length, OffsetSize);
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric   // CIE ID
16005ffd83dbSDimitry Andric   uint64_t CIE_ID =
16015ffd83dbSDimitry Andric       IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
16025ffd83dbSDimitry Andric   Streamer.emitIntValue(CIE_ID, OffsetSize);
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric   // Version
16050b57cec5SDimitry Andric   uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
16065ffd83dbSDimitry Andric   Streamer.emitInt8(CIEVersion);
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   if (IsEH) {
16090b57cec5SDimitry Andric     SmallString<8> Augmentation;
16100b57cec5SDimitry Andric     Augmentation += "z";
16110b57cec5SDimitry Andric     if (Frame.Personality)
16120b57cec5SDimitry Andric       Augmentation += "P";
16130b57cec5SDimitry Andric     if (Frame.Lsda)
16140b57cec5SDimitry Andric       Augmentation += "L";
16150b57cec5SDimitry Andric     Augmentation += "R";
16160b57cec5SDimitry Andric     if (Frame.IsSignalFrame)
16170b57cec5SDimitry Andric       Augmentation += "S";
16180b57cec5SDimitry Andric     if (Frame.IsBKeyFrame)
16190b57cec5SDimitry Andric       Augmentation += "B";
162081ad6265SDimitry Andric     if (Frame.IsMTETaggedFrame)
162181ad6265SDimitry Andric       Augmentation += "G";
16225ffd83dbSDimitry Andric     Streamer.emitBytes(Augmentation);
16230b57cec5SDimitry Andric   }
16245ffd83dbSDimitry Andric   Streamer.emitInt8(0);
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   if (CIEVersion >= 4) {
16270b57cec5SDimitry Andric     // Address Size
16285ffd83dbSDimitry Andric     Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric     // Segment Descriptor Size
16315ffd83dbSDimitry Andric     Streamer.emitInt8(0);
16320b57cec5SDimitry Andric   }
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric   // Code Alignment Factor
16355ffd83dbSDimitry Andric   Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   // Data Alignment Factor
16385ffd83dbSDimitry Andric   Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric   // Return Address Register
16410b57cec5SDimitry Andric   unsigned RAReg = Frame.RAReg;
16420b57cec5SDimitry Andric   if (RAReg == static_cast<unsigned>(INT_MAX))
16430b57cec5SDimitry Andric     RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric   if (CIEVersion == 1) {
16460b57cec5SDimitry Andric     assert(RAReg <= 255 &&
16470b57cec5SDimitry Andric            "DWARF 2 encodes return_address_register in one byte");
16485ffd83dbSDimitry Andric     Streamer.emitInt8(RAReg);
16490b57cec5SDimitry Andric   } else {
16505ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(RAReg);
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   // Augmentation Data Length (optional)
16540b57cec5SDimitry Andric   unsigned augmentationLength = 0;
16550b57cec5SDimitry Andric   if (IsEH) {
16560b57cec5SDimitry Andric     if (Frame.Personality) {
16570b57cec5SDimitry Andric       // Personality Encoding
16580b57cec5SDimitry Andric       augmentationLength += 1;
16590b57cec5SDimitry Andric       // Personality
16600b57cec5SDimitry Andric       augmentationLength +=
16610b57cec5SDimitry Andric           getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
16620b57cec5SDimitry Andric     }
16630b57cec5SDimitry Andric     if (Frame.Lsda)
16640b57cec5SDimitry Andric       augmentationLength += 1;
16650b57cec5SDimitry Andric     // Encoding of the FDE pointers
16660b57cec5SDimitry Andric     augmentationLength += 1;
16670b57cec5SDimitry Andric 
16685ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(augmentationLength);
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric     // Augmentation Data (optional)
16710b57cec5SDimitry Andric     if (Frame.Personality) {
16720b57cec5SDimitry Andric       // Personality Encoding
16730b57cec5SDimitry Andric       emitEncodingByte(Streamer, Frame.PersonalityEncoding);
16740b57cec5SDimitry Andric       // Personality
16750b57cec5SDimitry Andric       EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
16760b57cec5SDimitry Andric     }
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric     if (Frame.Lsda)
16790b57cec5SDimitry Andric       emitEncodingByte(Streamer, Frame.LsdaEncoding);
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric     // Encoding of the FDE pointers
16820b57cec5SDimitry Andric     emitEncodingByte(Streamer, MOFI->getFDEEncoding());
16830b57cec5SDimitry Andric   }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   // Initial Instructions
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric   const MCAsmInfo *MAI = context.getAsmInfo();
16880b57cec5SDimitry Andric   if (!Frame.IsSimple) {
16890b57cec5SDimitry Andric     const std::vector<MCCFIInstruction> &Instructions =
16900b57cec5SDimitry Andric         MAI->getInitialFrameState();
16915ffd83dbSDimitry Andric     emitCFIInstructions(Instructions, nullptr);
16920b57cec5SDimitry Andric   }
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   InitialCFAOffset = CFAOffset;
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   // Padding
1697bdd1243dSDimitry Andric   Streamer.emitValueToAlignment(Align(IsEH ? 4 : MAI->getCodePointerSize()));
16980b57cec5SDimitry Andric 
16995ffd83dbSDimitry Andric   Streamer.emitLabel(sectionEnd);
17000b57cec5SDimitry Andric   return *sectionStart;
17010b57cec5SDimitry Andric }
17020b57cec5SDimitry Andric 
EmitFDE(const MCSymbol & cieStart,const MCDwarfFrameInfo & frame,bool LastInSection,const MCSymbol & SectionStart)17030b57cec5SDimitry Andric void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
17040b57cec5SDimitry Andric                                const MCDwarfFrameInfo &frame,
17050b57cec5SDimitry Andric                                bool LastInSection,
17060b57cec5SDimitry Andric                                const MCSymbol &SectionStart) {
17070b57cec5SDimitry Andric   MCContext &context = Streamer.getContext();
17080b57cec5SDimitry Andric   MCSymbol *fdeStart = context.createTempSymbol();
17090b57cec5SDimitry Andric   MCSymbol *fdeEnd = context.createTempSymbol();
17100b57cec5SDimitry Andric   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   CFAOffset = InitialCFAOffset;
17130b57cec5SDimitry Andric 
17145ffd83dbSDimitry Andric   dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
17155ffd83dbSDimitry Andric   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
17160b57cec5SDimitry Andric 
17175ffd83dbSDimitry Andric   if (Format == dwarf::DWARF64)
17185ffd83dbSDimitry Andric     // DWARF64 mark
17195ffd83dbSDimitry Andric     Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
17205ffd83dbSDimitry Andric 
17215ffd83dbSDimitry Andric   // Length
17225ffd83dbSDimitry Andric   const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
17235ffd83dbSDimitry Andric   emitAbsValue(Streamer, Length, OffsetSize);
17245ffd83dbSDimitry Andric 
17255ffd83dbSDimitry Andric   Streamer.emitLabel(fdeStart);
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   // CIE Pointer
17280b57cec5SDimitry Andric   const MCAsmInfo *asmInfo = context.getAsmInfo();
17290b57cec5SDimitry Andric   if (IsEH) {
17300b57cec5SDimitry Andric     const MCExpr *offset =
17315ffd83dbSDimitry Andric         makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
17325ffd83dbSDimitry Andric     emitAbsValue(Streamer, offset, OffsetSize);
17330b57cec5SDimitry Andric   } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
17340b57cec5SDimitry Andric     const MCExpr *offset =
17355ffd83dbSDimitry Andric         makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
17365ffd83dbSDimitry Andric     emitAbsValue(Streamer, offset, OffsetSize);
17370b57cec5SDimitry Andric   } else {
17385ffd83dbSDimitry Andric     Streamer.emitSymbolValue(&cieStart, OffsetSize,
1739480093f4SDimitry Andric                              asmInfo->needsDwarfSectionOffsetDirective());
17400b57cec5SDimitry Andric   }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric   // PC Begin
17430b57cec5SDimitry Andric   unsigned PCEncoding =
17440b57cec5SDimitry Andric       IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
17450b57cec5SDimitry Andric   unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
17460b57cec5SDimitry Andric   emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric   // PC Range
17490b57cec5SDimitry Andric   const MCExpr *Range =
17505ffd83dbSDimitry Andric       makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
17510b57cec5SDimitry Andric   emitAbsValue(Streamer, Range, PCSize);
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   if (IsEH) {
17540b57cec5SDimitry Andric     // Augmentation Data Length
17550b57cec5SDimitry Andric     unsigned augmentationLength = 0;
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric     if (frame.Lsda)
17580b57cec5SDimitry Andric       augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
17590b57cec5SDimitry Andric 
17605ffd83dbSDimitry Andric     Streamer.emitULEB128IntValue(augmentationLength);
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric     // Augmentation Data
17630b57cec5SDimitry Andric     if (frame.Lsda)
17640b57cec5SDimitry Andric       emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
17650b57cec5SDimitry Andric   }
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   // Call Frame Instructions
17685ffd83dbSDimitry Andric   emitCFIInstructions(frame.Instructions, frame.Begin);
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   // Padding
17710b57cec5SDimitry Andric   // The size of a .eh_frame section has to be a multiple of the alignment
17720b57cec5SDimitry Andric   // since a null CIE is interpreted as the end. Old systems overaligned
17730b57cec5SDimitry Andric   // .eh_frame, so we do too and account for it in the last FDE.
1774bdd1243dSDimitry Andric   unsigned Alignment = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
1775bdd1243dSDimitry Andric   Streamer.emitValueToAlignment(Align(Alignment));
17760b57cec5SDimitry Andric 
17775ffd83dbSDimitry Andric   Streamer.emitLabel(fdeEnd);
17780b57cec5SDimitry Andric }
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric namespace {
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric struct CIEKey {
17830fca6ea1SDimitry Andric   CIEKey() = default;
17840b57cec5SDimitry Andric 
CIEKey__anon9ac4b6f30311::CIEKey17850b57cec5SDimitry Andric   explicit CIEKey(const MCDwarfFrameInfo &Frame)
17860b57cec5SDimitry Andric       : Personality(Frame.Personality),
17870b57cec5SDimitry Andric         PersonalityEncoding(Frame.PersonalityEncoding),
17880b57cec5SDimitry Andric         LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
17890b57cec5SDimitry Andric         IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
1790bdd1243dSDimitry Andric         IsBKeyFrame(Frame.IsBKeyFrame),
1791bdd1243dSDimitry Andric         IsMTETaggedFrame(Frame.IsMTETaggedFrame) {}
17920b57cec5SDimitry Andric 
PersonalityName__anon9ac4b6f30311::CIEKey17930b57cec5SDimitry Andric   StringRef PersonalityName() const {
17940b57cec5SDimitry Andric     if (!Personality)
17950b57cec5SDimitry Andric       return StringRef();
17960b57cec5SDimitry Andric     return Personality->getName();
17970b57cec5SDimitry Andric   }
17980b57cec5SDimitry Andric 
operator <__anon9ac4b6f30311::CIEKey17990b57cec5SDimitry Andric   bool operator<(const CIEKey &Other) const {
18000b57cec5SDimitry Andric     return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
1801bdd1243dSDimitry Andric                            IsSignalFrame, IsSimple, RAReg, IsBKeyFrame,
1802bdd1243dSDimitry Andric                            IsMTETaggedFrame) <
18030b57cec5SDimitry Andric            std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
18040b57cec5SDimitry Andric                            Other.LsdaEncoding, Other.IsSignalFrame,
1805bdd1243dSDimitry Andric                            Other.IsSimple, Other.RAReg, Other.IsBKeyFrame,
1806bdd1243dSDimitry Andric                            Other.IsMTETaggedFrame);
18070b57cec5SDimitry Andric   }
18080b57cec5SDimitry Andric 
operator ==__anon9ac4b6f30311::CIEKey18090fca6ea1SDimitry Andric   bool operator==(const CIEKey &Other) const {
18100fca6ea1SDimitry Andric     return Personality == Other.Personality &&
18110fca6ea1SDimitry Andric            PersonalityEncoding == Other.PersonalityEncoding &&
18120fca6ea1SDimitry Andric            LsdaEncoding == Other.LsdaEncoding &&
18130fca6ea1SDimitry Andric            IsSignalFrame == Other.IsSignalFrame && IsSimple == Other.IsSimple &&
18140fca6ea1SDimitry Andric            RAReg == Other.RAReg && IsBKeyFrame == Other.IsBKeyFrame &&
18150fca6ea1SDimitry Andric            IsMTETaggedFrame == Other.IsMTETaggedFrame;
18160fca6ea1SDimitry Andric   }
operator !=__anon9ac4b6f30311::CIEKey18170fca6ea1SDimitry Andric   bool operator!=(const CIEKey &Other) const { return !(*this == Other); }
18180fca6ea1SDimitry Andric 
18190fca6ea1SDimitry Andric   const MCSymbol *Personality = nullptr;
18200fca6ea1SDimitry Andric   unsigned PersonalityEncoding = 0;
18210fca6ea1SDimitry Andric   unsigned LsdaEncoding = -1;
18220fca6ea1SDimitry Andric   bool IsSignalFrame = false;
18230fca6ea1SDimitry Andric   bool IsSimple = false;
18240fca6ea1SDimitry Andric   unsigned RAReg = static_cast<unsigned>(UINT_MAX);
18250fca6ea1SDimitry Andric   bool IsBKeyFrame = false;
18260fca6ea1SDimitry Andric   bool IsMTETaggedFrame = false;
18270b57cec5SDimitry Andric };
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric } // end anonymous namespace
18300b57cec5SDimitry Andric 
Emit(MCObjectStreamer & Streamer,MCAsmBackend * MAB,bool IsEH)18310b57cec5SDimitry Andric void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
18320b57cec5SDimitry Andric                                bool IsEH) {
18330b57cec5SDimitry Andric   MCContext &Context = Streamer.getContext();
18340b57cec5SDimitry Andric   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
18350b57cec5SDimitry Andric   const MCAsmInfo *AsmInfo = Context.getAsmInfo();
18360b57cec5SDimitry Andric   FrameEmitterImpl Emitter(IsEH, Streamer);
18370b57cec5SDimitry Andric   ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   // Emit the compact unwind info if available.
18400b57cec5SDimitry Andric   bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
18410b57cec5SDimitry Andric   if (IsEH && MOFI->getCompactUnwindSection()) {
184281ad6265SDimitry Andric     Streamer.generateCompactUnwindEncodings(MAB);
18430b57cec5SDimitry Andric     bool SectionEmitted = false;
18440b57cec5SDimitry Andric     for (const MCDwarfFrameInfo &Frame : FrameArray) {
18450b57cec5SDimitry Andric       if (Frame.CompactUnwindEncoding == 0) continue;
18460b57cec5SDimitry Andric       if (!SectionEmitted) {
184781ad6265SDimitry Andric         Streamer.switchSection(MOFI->getCompactUnwindSection());
1848bdd1243dSDimitry Andric         Streamer.emitValueToAlignment(Align(AsmInfo->getCodePointerSize()));
18490b57cec5SDimitry Andric         SectionEmitted = true;
18500b57cec5SDimitry Andric       }
18510b57cec5SDimitry Andric       NeedsEHFrameSection |=
18520b57cec5SDimitry Andric         Frame.CompactUnwindEncoding ==
18530b57cec5SDimitry Andric           MOFI->getCompactUnwindDwarfEHFrameOnly();
18540b57cec5SDimitry Andric       Emitter.EmitCompactUnwind(Frame);
18550b57cec5SDimitry Andric     }
18560b57cec5SDimitry Andric   }
18570b57cec5SDimitry Andric 
185806c3fb27SDimitry Andric   // Compact unwind information can be emitted in the eh_frame section or the
185906c3fb27SDimitry Andric   // debug_frame section. Skip emitting FDEs and CIEs when the compact unwind
186006c3fb27SDimitry Andric   // doesn't need an eh_frame section and the emission location is the eh_frame
186106c3fb27SDimitry Andric   // section.
186206c3fb27SDimitry Andric   if (!NeedsEHFrameSection && IsEH) return;
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   MCSection &Section =
18650b57cec5SDimitry Andric       IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
18660b57cec5SDimitry Andric            : *MOFI->getDwarfFrameSection();
18670b57cec5SDimitry Andric 
186881ad6265SDimitry Andric   Streamer.switchSection(&Section);
18690b57cec5SDimitry Andric   MCSymbol *SectionStart = Context.createTempSymbol();
18705ffd83dbSDimitry Andric   Streamer.emitLabel(SectionStart);
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
18730b57cec5SDimitry Andric   // Sort the FDEs by their corresponding CIE before we emit them.
18740b57cec5SDimitry Andric   // This isn't technically necessary according to the DWARF standard,
18750b57cec5SDimitry Andric   // but the Android libunwindstack rejects eh_frame sections where
18760b57cec5SDimitry Andric   // an FDE refers to a CIE other than the closest previous CIE.
18770b57cec5SDimitry Andric   std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
18780b57cec5SDimitry Andric   llvm::stable_sort(FrameArrayX,
18790b57cec5SDimitry Andric                     [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
18800b57cec5SDimitry Andric                       return CIEKey(X) < CIEKey(Y);
18810b57cec5SDimitry Andric                     });
18820fca6ea1SDimitry Andric   CIEKey LastKey;
18830fca6ea1SDimitry Andric   const MCSymbol *LastCIEStart = nullptr;
18840b57cec5SDimitry Andric   for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
18850b57cec5SDimitry Andric     const MCDwarfFrameInfo &Frame = *I;
18860b57cec5SDimitry Andric     ++I;
18870b57cec5SDimitry Andric     if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
188806c3fb27SDimitry Andric           MOFI->getCompactUnwindDwarfEHFrameOnly() && IsEH)
188906c3fb27SDimitry Andric       // CIEs and FDEs can be emitted in either the eh_frame section or the
189006c3fb27SDimitry Andric       // debug_frame section, on some platforms (e.g. AArch64) the target object
189106c3fb27SDimitry Andric       // file supports emitting a compact_unwind section without an associated
189206c3fb27SDimitry Andric       // eh_frame section. If the eh_frame section is not needed, and the
189306c3fb27SDimitry Andric       // location where the CIEs and FDEs are to be emitted is the eh_frame
189406c3fb27SDimitry Andric       // section, do not emit anything.
18950b57cec5SDimitry Andric       continue;
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric     CIEKey Key(Frame);
18980fca6ea1SDimitry Andric     if (!LastCIEStart || (IsEH && Key != LastKey)) {
18990fca6ea1SDimitry Andric       LastKey = Key;
19000fca6ea1SDimitry Andric       LastCIEStart = &Emitter.EmitCIE(Frame);
19010fca6ea1SDimitry Andric     }
19020b57cec5SDimitry Andric 
19030fca6ea1SDimitry Andric     Emitter.EmitFDE(*LastCIEStart, Frame, I == E, *SectionStart);
19040b57cec5SDimitry Andric   }
19050b57cec5SDimitry Andric }
19060b57cec5SDimitry Andric 
encodeAdvanceLoc(MCContext & Context,uint64_t AddrDelta,SmallVectorImpl<char> & Out)190706c3fb27SDimitry Andric void MCDwarfFrameEmitter::encodeAdvanceLoc(MCContext &Context,
1908fe6060f1SDimitry Andric                                            uint64_t AddrDelta,
190906c3fb27SDimitry Andric                                            SmallVectorImpl<char> &Out) {
19100b57cec5SDimitry Andric   // Scale the address delta by the minimum instruction length.
19110b57cec5SDimitry Andric   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1912fe6060f1SDimitry Andric   if (AddrDelta == 0)
1913fe6060f1SDimitry Andric     return;
19140b57cec5SDimitry Andric 
19155f757f3fSDimitry Andric   llvm::endianness E = Context.getAsmInfo()->isLittleEndian()
19165f757f3fSDimitry Andric                            ? llvm::endianness::little
19175f757f3fSDimitry Andric                            : llvm::endianness::big;
1918fe6060f1SDimitry Andric 
1919fe6060f1SDimitry Andric   if (isUIntN(6, AddrDelta)) {
19200b57cec5SDimitry Andric     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
192106c3fb27SDimitry Andric     Out.push_back(Opcode);
19220b57cec5SDimitry Andric   } else if (isUInt<8>(AddrDelta)) {
192306c3fb27SDimitry Andric     Out.push_back(dwarf::DW_CFA_advance_loc1);
192406c3fb27SDimitry Andric     Out.push_back(AddrDelta);
19250b57cec5SDimitry Andric   } else if (isUInt<16>(AddrDelta)) {
192606c3fb27SDimitry Andric     Out.push_back(dwarf::DW_CFA_advance_loc2);
192706c3fb27SDimitry Andric     support::endian::write<uint16_t>(Out, AddrDelta, E);
19280b57cec5SDimitry Andric   } else {
19290b57cec5SDimitry Andric     assert(isUInt<32>(AddrDelta));
193006c3fb27SDimitry Andric     Out.push_back(dwarf::DW_CFA_advance_loc4);
193106c3fb27SDimitry Andric     support::endian::write<uint32_t>(Out, AddrDelta, E);
19320b57cec5SDimitry Andric   }
19330b57cec5SDimitry Andric }
1934