#include "llvm/MC/MCDwarf.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/Config/config.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectStreamer.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");
MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");
auto DwarfFormat = S.getContext().getDwarfFormat();
if (DwarfFormat == dwarf::DWARF64) {
S.AddComment("DWARF64 mark");
S.emitInt32(dwarf::DW_LENGTH_DWARF64);
}
S.AddComment("Length");
S.emitAbsoluteSymbolDiff(End, Start,
dwarf::getDwarfOffsetByteSize(DwarfFormat));
S.emitLabel(Start);
S.AddComment("Version");
S.emitInt16(S.getContext().getDwarfVersion());
S.AddComment("Address size");
S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
S.AddComment("Segment selector size");
S.emitInt8(0);
return End;
}
static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
if (MinInsnLength == 1)
return AddrDelta;
if (AddrDelta % MinInsnLength != 0) {
;
}
return AddrDelta / MinInsnLength;
}
MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {
UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
if (UseRelocs)
LineStrLabel =
Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol();
}
void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {
if (!MCOS->getContext().getDwarfLocSeen())
return;
MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
MCOS->emitLabel(LineSym);
const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
MCOS->getContext().clearDwarfLocSeen();
MCOS->getContext()
.getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
.getMCLineSections()
.addLineEntry(LineEntry, Section);
}
static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
const MCSymbol &Start,
const MCSymbol &End,
int IntVal) {
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
return Res3;
}
static inline const MCExpr *
makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
return Res;
}
void MCLineSection::addEndEntry(MCSymbol *EndLabel) {
auto *Sec = &EndLabel->getSection();
auto I = MCLineDivisions.find(Sec);
if (I != MCLineDivisions.end()) {
auto &Entries = I->second;
auto EndEntry = Entries.back();
EndEntry.setEndLabel(EndLabel);
Entries.push_back(EndEntry);
}
}
void MCDwarfLineTable::emitOne(
MCStreamer *MCOS, MCSection *Section,
const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;
MCSymbol *LastLabel;
auto init = [&]() {
FileNum = 1;
LastLine = 1;
Column = 0;
Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Isa = 0;
Discriminator = 0;
LastLabel = nullptr;
};
init();
bool EndEntryEmitted = false;
for (const MCDwarfLineEntry &LineEntry : LineEntries) {
MCSymbol *Label = LineEntry.getLabel();
const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
if (LineEntry.IsEndEntry) {
MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label,
asmInfo->getCodePointerSize());
init();
EndEntryEmitted = true;
continue;
}
int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
if (FileNum != LineEntry.getFileNum()) {
FileNum = LineEntry.getFileNum();
MCOS->emitInt8(dwarf::DW_LNS_set_file);
MCOS->emitULEB128IntValue(FileNum);
}
if (Column != LineEntry.getColumn()) {
Column = LineEntry.getColumn();
MCOS->emitInt8(dwarf::DW_LNS_set_column);
MCOS->emitULEB128IntValue(Column);
}
if (Discriminator != LineEntry.getDiscriminator() &&
MCOS->getContext().getDwarfVersion() >= 4) {
Discriminator = LineEntry.getDiscriminator();
unsigned Size = getULEB128Size(Discriminator);
MCOS->emitInt8(dwarf::DW_LNS_extended_op);
MCOS->emitULEB128IntValue(Size + 1);
MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
MCOS->emitULEB128IntValue(Discriminator);
}
if (Isa != LineEntry.getIsa()) {
Isa = LineEntry.getIsa();
MCOS->emitInt8(dwarf::DW_LNS_set_isa);
MCOS->emitULEB128IntValue(Isa);
}
if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
Flags = LineEntry.getFlags();
MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
}
if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
asmInfo->getCodePointerSize());
Discriminator = 0;
LastLine = LineEntry.getLine();
LastLabel = Label;
}
if (!EndEntryEmitted)
MCOS->emitDwarfLineEndEntry(Section, LastLabel);
}
void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {
MCContext &context = MCOS->getContext();
auto &LineTables = context.getMCDwarfLineTables();
if (LineTables.empty())
return;
Optional<MCDwarfLineStr> LineStr;
if (context.getDwarfVersion() >= 5)
LineStr.emplace(context);
MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection());
for (const auto &CUIDTablePair : LineTables) {
CUIDTablePair.second.emitCU(MCOS, Params, LineStr);
}
if (LineStr)
LineStr->emitSection(MCOS);
}
void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
MCSection *Section) const {
if (!HasSplitLineTable)
return;
Optional<MCDwarfLineStr> NoLineStr(None);
MCOS.switchSection(Section);
MCOS.emitLabel(Header.Emit(&MCOS, Params, None, NoLineStr).second);
}
std::pair<MCSymbol *, MCSymbol *>
MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
Optional<MCDwarfLineStr> &LineStr) const {
static const char StandardOpcodeLengths[] = {
0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 };
assert(array_lengthof(StandardOpcodeLengths) >=
(Params.DWARF2LineOpcodeBase - 1U));
return Emit(
MCOS, Params,
makeArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
LineStr);
}
static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
MCContext &Context = OS.getContext();
assert(!isa<MCSymbolRefExpr>(Expr));
if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
return Expr;
MCSymbol *ABS = Context.createTempSymbol();
OS.emitAssignment(ABS, Expr);
return MCSymbolRefExpr::create(ABS, Context);
}
static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
const MCExpr *ABS = forceExpAbs(OS, Value);
OS.emitValue(ABS, Size);
}
void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
MCOS->switchSection(
MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
SmallString<0> Data = getFinalizedData();
MCOS->emitBinaryData(Data.str());
}
SmallString<0> MCDwarfLineStr::getFinalizedData() {
if (!LineStrings.isFinalized())
LineStrings.finalizeInOrder();
SmallString<0> Data;
Data.resize(LineStrings.getSize());
LineStrings.write((uint8_t *)Data.data());
return Data;
}
void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
int RefSize =
dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
size_t Offset = LineStrings.add(Path);
if (UseRelocs) {
MCContext &Ctx = MCOS->getContext();
MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize);
} else
MCOS->emitIntValue(Offset, RefSize);
}
void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
for (auto &Dir : MCDwarfDirs) {
MCOS->emitBytes(Dir); MCOS->emitBytes(StringRef("\0", 1)); }
MCOS->emitInt8(0);
for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
assert(!MCDwarfFiles[i].Name.empty());
MCOS->emitBytes(MCDwarfFiles[i].Name); MCOS->emitBytes(StringRef("\0", 1)); MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); MCOS->emitInt8(0); MCOS->emitInt8(0); }
MCOS->emitInt8(0); }
static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
bool EmitMD5, bool HasSource,
Optional<MCDwarfLineStr> &LineStr) {
assert(!DwarfFile.Name.empty());
if (LineStr)
LineStr->emitRef(MCOS, DwarfFile.Name);
else {
MCOS->emitBytes(DwarfFile.Name); MCOS->emitBytes(StringRef("\0", 1)); }
MCOS->emitULEB128IntValue(DwarfFile.DirIndex); if (EmitMD5) {
const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
MCOS->emitBinaryData(
StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size()));
}
if (HasSource) {
if (LineStr)
LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef()));
else {
MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); MCOS->emitBytes(StringRef("\0", 1)); }
}
}
void MCDwarfLineTableHeader::emitV5FileDirTables(
MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr) const {
MCOS->emitInt8(1);
MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
: dwarf::DW_FORM_string);
MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
SmallString<256> Dir;
StringRef CompDir = MCOS->getContext().getCompilationDir();
if (!CompilationDir.empty()) {
Dir = CompilationDir;
MCOS->getContext().remapDebugPath(Dir);
CompDir = Dir.str();
if (LineStr)
CompDir = LineStr->getSaver().save(CompDir);
}
if (LineStr) {
LineStr->emitRef(MCOS, CompDir);
for (const auto &Dir : MCDwarfDirs)
LineStr->emitRef(MCOS, Dir);
} else {
MCOS->emitBytes(CompDir);
MCOS->emitBytes(StringRef("\0", 1));
for (const auto &Dir : MCDwarfDirs) {
MCOS->emitBytes(Dir); MCOS->emitBytes(StringRef("\0", 1)); }
}
uint64_t Entries = 2;
if (HasAllMD5)
Entries += 1;
if (HasSource)
Entries += 1;
MCOS->emitInt8(Entries);
MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
: dwarf::DW_FORM_string);
MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
if (HasAllMD5) {
MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
}
if (HasSource) {
MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
: dwarf::DW_FORM_string);
}
MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
"No root file and no .file directives");
emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
HasAllMD5, HasSource, LineStr);
for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr);
}
std::pair<MCSymbol *, MCSymbol *>
MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
ArrayRef<char> StandardOpcodeLengths,
Optional<MCDwarfLineStr> &LineStr) const {
MCContext &context = MCOS->getContext();
MCSymbol *LineStartSym = Label;
if (!LineStartSym)
LineStartSym = context.createTempSymbol();
MCOS->emitDwarfLineStartLabel(LineStartSym);
unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");
unsigned LineTableVersion = context.getDwarfVersion();
MCOS->emitInt16(LineTableVersion);
if (LineTableVersion >= 5) {
MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
MCOS->emitInt8(0); }
MCSymbol *ProStartSym = context.createTempSymbol("prologue_start");
MCSymbol *ProEndSym = context.createTempSymbol("prologue_end");
MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);
MCOS->emitLabel(ProStartSym);
MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
if (LineTableVersion >= 4)
MCOS->emitInt8(1);
MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
MCOS->emitInt8(Params.DWARF2LineBase);
MCOS->emitInt8(Params.DWARF2LineRange);
MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
for (char Length : StandardOpcodeLengths)
MCOS->emitInt8(Length);
if (LineTableVersion >= 5)
emitV5FileDirTables(MCOS, LineStr);
else
emitV2FileDirTables(MCOS);
MCOS->emitLabel(ProEndSym);
return std::make_pair(LineStartSym, LineEndSym);
}
void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
Optional<MCDwarfLineStr> &LineStr) const {
MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
for (const auto &LineSec : MCLineSections.getMCLineEntries())
emitOne(MCOS, LineSec.first, LineSec.second);
MCOS->emitLabel(LineEndSym);
}
Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory,
StringRef &FileName,
Optional<MD5::MD5Result> Checksum,
Optional<StringRef> Source,
uint16_t DwarfVersion,
unsigned FileNumber) {
return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
FileNumber);
}
static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
StringRef &FileName, Optional<MD5::MD5Result> Checksum) {
if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
return false;
return RootFile.Checksum == Checksum;
}
Expected<unsigned>
MCDwarfLineTableHeader::tryGetFile(StringRef &Directory,
StringRef &FileName,
Optional<MD5::MD5Result> Checksum,
Optional<StringRef> Source,
uint16_t DwarfVersion,
unsigned FileNumber) {
if (Directory == CompilationDir)
Directory = "";
if (FileName.empty()) {
FileName = "<stdin>";
Directory = "";
}
assert(!FileName.empty());
if (MCDwarfFiles.empty()) {
trackMD5Usage(Checksum.has_value());
HasSource = (Source != None);
}
if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))
return 0;
if (FileNumber == 0) {
FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
SmallString<256> Buffer;
auto IterBool = SourceIdMap.insert(
std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
FileNumber));
if (!IterBool.second)
return IterBool.first->second;
}
if (FileNumber >= MCDwarfFiles.size())
MCDwarfFiles.resize(FileNumber + 1);
MCDwarfFile &File = MCDwarfFiles[FileNumber];
if (!File.Name.empty())
return make_error<StringError>("file number already allocated",
inconvertibleErrorCode());
if (HasSource != (Source != None))
return make_error<StringError>("inconsistent use of embedded source",
inconvertibleErrorCode());
if (Directory.empty()) {
StringRef tFileName = sys::path::filename(FileName);
if (!tFileName.empty()) {
Directory = sys::path::parent_path(FileName);
if (!Directory.empty())
FileName = tFileName;
}
}
unsigned DirIndex;
if (Directory.empty()) {
DirIndex = 0;
} else {
DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
if (DirIndex >= MCDwarfDirs.size())
MCDwarfDirs.push_back(std::string(Directory));
DirIndex++;
}
File.Name = std::string(FileName);
File.DirIndex = DirIndex;
File.Checksum = Checksum;
trackMD5Usage(Checksum.has_value());
File.Source = Source;
if (Source)
HasSource = true;
return FileNumber;
}
void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
int64_t LineDelta, uint64_t AddrDelta) {
MCContext &Context = MCOS->getContext();
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
MCOS->emitBytes(OS.str());
}
static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
}
void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
int64_t LineDelta, uint64_t AddrDelta,
raw_ostream &OS) {
uint64_t Temp, Opcode;
bool NeedCopy = false;
uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
AddrDelta = ScaleAddrDelta(Context, AddrDelta);
if (LineDelta == INT64_MAX) {
if (AddrDelta == MaxSpecialAddrDelta)
OS << char(dwarf::DW_LNS_const_add_pc);
else if (AddrDelta) {
OS << char(dwarf::DW_LNS_advance_pc);
encodeULEB128(AddrDelta, OS);
}
OS << char(dwarf::DW_LNS_extended_op);
OS << char(1);
OS << char(dwarf::DW_LNE_end_sequence);
return;
}
Temp = LineDelta - Params.DWARF2LineBase;
if (Temp >= Params.DWARF2LineRange ||
Temp + Params.DWARF2LineOpcodeBase > 255) {
OS << char(dwarf::DW_LNS_advance_line);
encodeSLEB128(LineDelta, OS);
LineDelta = 0;
Temp = 0 - Params.DWARF2LineBase;
NeedCopy = true;
}
if (LineDelta == 0 && AddrDelta == 0) {
OS << char(dwarf::DW_LNS_copy);
return;
}
Temp += Params.DWARF2LineOpcodeBase;
if (AddrDelta < 256 + MaxSpecialAddrDelta) {
Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
if (Opcode <= 255) {
OS << char(Opcode);
return;
}
Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
if (Opcode <= 255) {
OS << char(dwarf::DW_LNS_const_add_pc);
OS << char(Opcode);
return;
}
}
OS << char(dwarf::DW_LNS_advance_pc);
encodeULEB128(AddrDelta, OS);
if (NeedCopy)
OS << char(dwarf::DW_LNS_copy);
else {
assert(Temp <= 255 && "Buggy special opcode encoding.");
OS << char(Temp);
}
}
static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
MCOS->emitULEB128IntValue(Name);
MCOS->emitULEB128IntValue(Form);
}
static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
MCOS->emitULEB128IntValue(1);
MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
dwarf::Form SecOffsetForm =
context.getDwarfVersion() >= 4
? dwarf::DW_FORM_sec_offset
: (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
: dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
if (context.getGenDwarfSectionSyms().size() > 1 &&
context.getDwarfVersion() >= 3) {
EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
} else {
EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
}
EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
if (!context.getCompilationDir().empty())
EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty())
EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
EmitAbbrev(MCOS, 0, 0);
MCOS->emitULEB128IntValue(2);
MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
MCOS->emitInt8(dwarf::DW_CHILDREN_no);
EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, 0, 0);
MCOS->emitInt8(0);
}
static void EmitGenDwarfAranges(MCStreamer *MCOS,
const MCSymbol *InfoSectionSymbol) {
MCContext &context = MCOS->getContext();
auto &Sections = context.getGenDwarfSectionSyms();
MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
unsigned UnitLengthBytes =
dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
const MCAsmInfo *asmInfo = context.getAsmInfo();
int AddrSize = asmInfo->getCodePointerSize();
int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
if (Pad == 2 * AddrSize)
Pad = 0;
Length += Pad;
Length += 2 * AddrSize * Sections.size();
Length += 2 * AddrSize;
if (context.getDwarfFormat() == dwarf::DWARF64)
MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
MCOS->emitInt16(2);
if (InfoSectionSymbol)
MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
asmInfo->needsDwarfSectionOffsetDirective());
else
MCOS->emitIntValue(0, OffsetSize);
MCOS->emitInt8(AddrSize);
MCOS->emitInt8(0);
for(int i = 0; i < Pad; i++)
MCOS->emitInt8(0);
for (MCSection *Sec : Sections) {
const MCSymbol *StartSymbol = Sec->getBeginSymbol();
MCSymbol *EndSymbol = Sec->getEndSymbol(context);
assert(StartSymbol && "StartSymbol must not be NULL");
assert(EndSymbol && "EndSymbol must not be NULL");
const MCExpr *Addr = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
const MCExpr *Size =
makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
MCOS->emitValue(Addr, AddrSize);
emitAbsValue(*MCOS, Size, AddrSize);
}
MCOS->emitIntValue(0, AddrSize);
MCOS->emitIntValue(0, AddrSize);
}
static void EmitGenDwarfInfo(MCStreamer *MCOS,
const MCSymbol *AbbrevSectionSymbol,
const MCSymbol *LineSectionSymbol,
const MCSymbol *RangesSymbol) {
MCContext &context = MCOS->getContext();
MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
MCSymbol *InfoStart = context.createTempSymbol();
MCOS->emitLabel(InfoStart);
MCSymbol *InfoEnd = context.createTempSymbol();
unsigned UnitLengthBytes =
dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
if (context.getDwarfFormat() == dwarf::DWARF64)
MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
const MCExpr *Length =
makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
emitAbsValue(*MCOS, Length, OffsetSize);
MCOS->emitInt16(context.getDwarfVersion());
const MCAsmInfo &AsmInfo = *context.getAsmInfo();
int AddrSize = AsmInfo.getCodePointerSize();
if (context.getDwarfVersion() >= 5) {
MCOS->emitInt8(dwarf::DW_UT_compile);
MCOS->emitInt8(AddrSize);
}
if (AbbrevSectionSymbol)
MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
AsmInfo.needsDwarfSectionOffsetDirective());
else
MCOS->emitIntValue(0, OffsetSize);
if (context.getDwarfVersion() <= 4)
MCOS->emitInt8(AddrSize);
MCOS->emitULEB128IntValue(1);
if (LineSectionSymbol)
MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
AsmInfo.needsDwarfSectionOffsetDirective());
else
MCOS->emitIntValue(0, OffsetSize);
if (RangesSymbol) {
MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
} else {
auto &Sections = context.getGenDwarfSectionSyms();
const auto TextSection = Sections.begin();
assert(TextSection != Sections.end() && "No text section found");
MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
assert(StartSymbol && "StartSymbol must not be NULL");
assert(EndSymbol && "EndSymbol must not be NULL");
const MCExpr *Start = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->emitValue(Start, AddrSize);
const MCExpr *End = MCSymbolRefExpr::create(
EndSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->emitValue(End, AddrSize);
}
const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
if (MCDwarfDirs.size() > 0) {
MCOS->emitBytes(MCDwarfDirs[0]);
MCOS->emitBytes(sys::path::get_separator());
}
const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
const MCDwarfFile &RootFile =
MCDwarfFiles.empty()
? context.getMCDwarfLineTable(0).getRootFile()
: MCDwarfFiles[1];
MCOS->emitBytes(RootFile.Name);
MCOS->emitInt8(0);
if (!context.getCompilationDir().empty()) {
MCOS->emitBytes(context.getCompilationDir());
MCOS->emitInt8(0); }
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty()){
MCOS->emitBytes(DwarfDebugFlags);
MCOS->emitInt8(0); }
StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
if (!DwarfDebugProducer.empty())
MCOS->emitBytes(DwarfDebugProducer);
else
MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
MCOS->emitInt8(0);
MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
const std::vector<MCGenDwarfLabelEntry> &Entries =
MCOS->getContext().getMCGenDwarfLabelEntries();
for (const auto &Entry : Entries) {
MCOS->emitULEB128IntValue(2);
MCOS->emitBytes(Entry.getName());
MCOS->emitInt8(0);
MCOS->emitInt32(Entry.getFileNumber());
MCOS->emitInt32(Entry.getLineNumber());
const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
MCSymbolRefExpr::VK_None, context);
MCOS->emitValue(AT_low_pc, AddrSize);
}
MCOS->emitInt8(0);
MCOS->emitLabel(InfoEnd);
}
static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
auto &Sections = context.getGenDwarfSectionSyms();
const MCAsmInfo *AsmInfo = context.getAsmInfo();
int AddrSize = AsmInfo->getCodePointerSize();
MCSymbol *RangesSymbol;
if (MCOS->getContext().getDwarfVersion() >= 5) {
MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
MCOS->AddComment("Offset entry count");
MCOS->emitInt32(0);
RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
MCOS->emitLabel(RangesSymbol);
for (MCSection *Sec : Sections) {
const MCSymbol *StartSymbol = Sec->getBeginSymbol();
const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
const MCExpr *SectionSize =
makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
MCOS->emitInt8(dwarf::DW_RLE_start_length);
MCOS->emitValue(SectionStartAddr, AddrSize);
MCOS->emitULEB128Value(SectionSize);
}
MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
MCOS->emitLabel(EndSymbol);
} else {
MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection());
RangesSymbol = context.createTempSymbol("debug_ranges_start");
MCOS->emitLabel(RangesSymbol);
for (MCSection *Sec : Sections) {
const MCSymbol *StartSymbol = Sec->getBeginSymbol();
const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->emitFill(AddrSize, 0xFF);
MCOS->emitValue(SectionStartAddr, AddrSize);
const MCExpr *SectionSize =
makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
MCOS->emitIntValue(0, AddrSize);
emitAbsValue(*MCOS, SectionSize, AddrSize);
}
MCOS->emitIntValue(0, AddrSize);
MCOS->emitIntValue(0, AddrSize);
}
return RangesSymbol;
}
void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
const MCAsmInfo *AsmInfo = context.getAsmInfo();
bool CreateDwarfSectionSymbols =
AsmInfo->doesDwarfUseRelocationsAcrossSections();
MCSymbol *LineSectionSymbol = nullptr;
if (CreateDwarfSectionSymbols)
LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
MCSymbol *AbbrevSectionSymbol = nullptr;
MCSymbol *InfoSectionSymbol = nullptr;
MCSymbol *RangesSymbol = nullptr;
MCOS->getContext().finalizeDwarfSections(*MCOS);
if (MCOS->getContext().getGenDwarfSectionSyms().empty())
return;
const bool UseRangesSection =
MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
MCOS->getContext().getDwarfVersion() >= 3;
CreateDwarfSectionSymbols |= UseRangesSection;
MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
if (CreateDwarfSectionSymbols) {
InfoSectionSymbol = context.createTempSymbol();
MCOS->emitLabel(InfoSectionSymbol);
}
MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
if (CreateDwarfSectionSymbols) {
AbbrevSectionSymbol = context.createTempSymbol();
MCOS->emitLabel(AbbrevSectionSymbol);
}
MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
if (UseRangesSection) {
RangesSymbol = emitGenDwarfRanges(MCOS);
assert(RangesSymbol);
}
EmitGenDwarfAbbrev(MCOS);
EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
}
void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
SourceMgr &SrcMgr, SMLoc &Loc) {
if (Symbol->isTemporary())
return;
MCContext &context = MCOS->getContext();
if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
return;
StringRef Name = Symbol->getName();
if (Name.startswith("_"))
Name = Name.substr(1, Name.size()-1);
unsigned FileNumber = context.getGenDwarfFileNumber();
unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
MCSymbol *Label = context.createTempSymbol();
MCOS->emitLabel(Label);
MCOS->getContext().addMCGenDwarfLabelEntry(
MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
}
static int getDataAlignmentFactor(MCStreamer &streamer) {
MCContext &context = streamer.getContext();
const MCAsmInfo *asmInfo = context.getAsmInfo();
int size = asmInfo->getCalleeSaveStackSlotSize();
if (asmInfo->isStackGrowthDirectionUp())
return size;
else
return -size;
}
static unsigned getSizeForEncoding(MCStreamer &streamer,
unsigned symbolEncoding) {
MCContext &context = streamer.getContext();
unsigned format = symbolEncoding & 0x0f;
switch (format) {
default: llvm_unreachable("Unknown Encoding");
case dwarf::DW_EH_PE_absptr:
case dwarf::DW_EH_PE_signed:
return context.getAsmInfo()->getCodePointerSize();
case dwarf::DW_EH_PE_udata2:
case dwarf::DW_EH_PE_sdata2:
return 2;
case dwarf::DW_EH_PE_udata4:
case dwarf::DW_EH_PE_sdata4:
return 4;
case dwarf::DW_EH_PE_udata8:
case dwarf::DW_EH_PE_sdata8:
return 8;
}
}
static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
unsigned symbolEncoding, bool isEH) {
MCContext &context = streamer.getContext();
const MCAsmInfo *asmInfo = context.getAsmInfo();
const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
symbolEncoding,
streamer);
unsigned size = getSizeForEncoding(streamer, symbolEncoding);
if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
emitAbsValue(streamer, v, size);
else
streamer.emitValue(v, size);
}
static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
unsigned symbolEncoding) {
MCContext &context = streamer.getContext();
const MCAsmInfo *asmInfo = context.getAsmInfo();
const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
symbolEncoding,
streamer);
unsigned size = getSizeForEncoding(streamer, symbolEncoding);
streamer.emitValue(v, size);
}
namespace {
class FrameEmitterImpl {
int CFAOffset = 0;
int InitialCFAOffset = 0;
bool IsEH;
MCObjectStreamer &Streamer;
public:
FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
: IsEH(IsEH), Streamer(Streamer) {}
void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
bool LastInSection, const MCSymbol &SectionStart);
void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
MCSymbol *BaseLabel);
void emitCFIInstruction(const MCCFIInstruction &Instr);
};
}
static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
Streamer.emitInt8(Encoding);
}
void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
auto *MRI = Streamer.getContext().getRegisterInfo();
switch (Instr.getOperation()) {
case MCCFIInstruction::OpRegister: {
unsigned Reg1 = Instr.getRegister();
unsigned Reg2 = Instr.getRegister2();
if (!IsEH) {
Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
}
Streamer.emitInt8(dwarf::DW_CFA_register);
Streamer.emitULEB128IntValue(Reg1);
Streamer.emitULEB128IntValue(Reg2);
return;
}
case MCCFIInstruction::OpWindowSave:
Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
return;
case MCCFIInstruction::OpNegateRAState:
Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
return;
case MCCFIInstruction::OpUndefined: {
unsigned Reg = Instr.getRegister();
Streamer.emitInt8(dwarf::DW_CFA_undefined);
Streamer.emitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpAdjustCfaOffset:
case MCCFIInstruction::OpDefCfaOffset: {
const bool IsRelative =
Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
if (IsRelative)
CFAOffset += Instr.getOffset();
else
CFAOffset = Instr.getOffset();
Streamer.emitULEB128IntValue(CFAOffset);
return;
}
case MCCFIInstruction::OpDefCfa: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
Streamer.emitULEB128IntValue(Reg);
CFAOffset = Instr.getOffset();
Streamer.emitULEB128IntValue(CFAOffset);
return;
}
case MCCFIInstruction::OpDefCfaRegister: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
Streamer.emitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpLLVMDefAspaceCfa: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1);
Streamer.emitULEB128IntValue(Reg);
CFAOffset = Instr.getOffset();
Streamer.emitULEB128IntValue(CFAOffset);
Streamer.emitULEB128IntValue(Instr.getAddressSpace());
return;
}
case MCCFIInstruction::OpOffset:
case MCCFIInstruction::OpRelOffset: {
const bool IsRelative =
Instr.getOperation() == MCCFIInstruction::OpRelOffset;
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
int Offset = Instr.getOffset();
if (IsRelative)
Offset -= CFAOffset;
Offset = Offset / dataAlignmentFactor;
if (Offset < 0) {
Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
Streamer.emitULEB128IntValue(Reg);
Streamer.emitSLEB128IntValue(Offset);
} else if (Reg < 64) {
Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
Streamer.emitULEB128IntValue(Offset);
} else {
Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
Streamer.emitULEB128IntValue(Reg);
Streamer.emitULEB128IntValue(Offset);
}
return;
}
case MCCFIInstruction::OpRememberState:
Streamer.emitInt8(dwarf::DW_CFA_remember_state);
return;
case MCCFIInstruction::OpRestoreState:
Streamer.emitInt8(dwarf::DW_CFA_restore_state);
return;
case MCCFIInstruction::OpSameValue: {
unsigned Reg = Instr.getRegister();
Streamer.emitInt8(dwarf::DW_CFA_same_value);
Streamer.emitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpRestore: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
if (Reg < 64) {
Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
} else {
Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
Streamer.emitULEB128IntValue(Reg);
}
return;
}
case MCCFIInstruction::OpGnuArgsSize:
Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
Streamer.emitULEB128IntValue(Instr.getOffset());
return;
case MCCFIInstruction::OpEscape:
Streamer.emitBytes(Instr.getValues());
return;
}
llvm_unreachable("Unhandled case in switch");
}
void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
MCSymbol *BaseLabel) {
for (const MCCFIInstruction &Instr : Instrs) {
MCSymbol *Label = Instr.getLabel();
if (Label && !Label->isDefined()) continue;
if (BaseLabel && Label) {
MCSymbol *ThisSym = Label;
if (ThisSym != BaseLabel) {
Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
BaseLabel = ThisSym;
}
}
emitCFIInstruction(Instr);
}
}
void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
MCContext &Context = Streamer.getContext();
const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
uint32_t Encoding = Frame.CompactUnwindEncoding;
if (!Encoding) return;
bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
if (!DwarfEHFrameOnly && Frame.Lsda)
Encoding |= 0x40000000;
unsigned FDEEncoding = MOFI->getFDEEncoding();
unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
Streamer.emitSymbolValue(Frame.Begin, Size);
const MCExpr *Range =
makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
emitAbsValue(Streamer, Range, 4);
Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
Streamer.emitIntValue(Encoding, Size);
Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
if (!DwarfEHFrameOnly && Frame.Personality)
Streamer.emitSymbolValue(Frame.Personality, Size);
else
Streamer.emitIntValue(0, Size);
Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
if (!DwarfEHFrameOnly && Frame.Lsda)
Streamer.emitSymbolValue(Frame.Lsda, Size);
else
Streamer.emitIntValue(0, Size); }
static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
if (IsEH)
return 1;
switch (DwarfVersion) {
case 2:
return 1;
case 3:
return 3;
case 4:
case 5:
return 4;
}
llvm_unreachable("Unknown version");
}
const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
MCContext &context = Streamer.getContext();
const MCRegisterInfo *MRI = context.getRegisterInfo();
const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
MCSymbol *sectionStart = context.createTempSymbol();
Streamer.emitLabel(sectionStart);
MCSymbol *sectionEnd = context.createTempSymbol();
dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
bool IsDwarf64 = Format == dwarf::DWARF64;
if (IsDwarf64)
Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
*sectionEnd, UnitLengthBytes);
emitAbsValue(Streamer, Length, OffsetSize);
uint64_t CIE_ID =
IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
Streamer.emitIntValue(CIE_ID, OffsetSize);
uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
Streamer.emitInt8(CIEVersion);
if (IsEH) {
SmallString<8> Augmentation;
Augmentation += "z";
if (Frame.Personality)
Augmentation += "P";
if (Frame.Lsda)
Augmentation += "L";
Augmentation += "R";
if (Frame.IsSignalFrame)
Augmentation += "S";
if (Frame.IsBKeyFrame)
Augmentation += "B";
if (Frame.IsMTETaggedFrame)
Augmentation += "G";
Streamer.emitBytes(Augmentation);
}
Streamer.emitInt8(0);
if (CIEVersion >= 4) {
Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
Streamer.emitInt8(0);
}
Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
unsigned RAReg = Frame.RAReg;
if (RAReg == static_cast<unsigned>(INT_MAX))
RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
if (CIEVersion == 1) {
assert(RAReg <= 255 &&
"DWARF 2 encodes return_address_register in one byte");
Streamer.emitInt8(RAReg);
} else {
Streamer.emitULEB128IntValue(RAReg);
}
unsigned augmentationLength = 0;
if (IsEH) {
if (Frame.Personality) {
augmentationLength += 1;
augmentationLength +=
getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
}
if (Frame.Lsda)
augmentationLength += 1;
augmentationLength += 1;
Streamer.emitULEB128IntValue(augmentationLength);
if (Frame.Personality) {
emitEncodingByte(Streamer, Frame.PersonalityEncoding);
EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
}
if (Frame.Lsda)
emitEncodingByte(Streamer, Frame.LsdaEncoding);
emitEncodingByte(Streamer, MOFI->getFDEEncoding());
}
const MCAsmInfo *MAI = context.getAsmInfo();
if (!Frame.IsSimple) {
const std::vector<MCCFIInstruction> &Instructions =
MAI->getInitialFrameState();
emitCFIInstructions(Instructions, nullptr);
}
InitialCFAOffset = CFAOffset;
Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize());
Streamer.emitLabel(sectionEnd);
return *sectionStart;
}
void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
const MCDwarfFrameInfo &frame,
bool LastInSection,
const MCSymbol &SectionStart) {
MCContext &context = Streamer.getContext();
MCSymbol *fdeStart = context.createTempSymbol();
MCSymbol *fdeEnd = context.createTempSymbol();
const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
CFAOffset = InitialCFAOffset;
dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
if (Format == dwarf::DWARF64)
Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
emitAbsValue(Streamer, Length, OffsetSize);
Streamer.emitLabel(fdeStart);
const MCAsmInfo *asmInfo = context.getAsmInfo();
if (IsEH) {
const MCExpr *offset =
makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
emitAbsValue(Streamer, offset, OffsetSize);
} else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
const MCExpr *offset =
makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
emitAbsValue(Streamer, offset, OffsetSize);
} else {
Streamer.emitSymbolValue(&cieStart, OffsetSize,
asmInfo->needsDwarfSectionOffsetDirective());
}
unsigned PCEncoding =
IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
const MCExpr *Range =
makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
emitAbsValue(Streamer, Range, PCSize);
if (IsEH) {
unsigned augmentationLength = 0;
if (frame.Lsda)
augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
Streamer.emitULEB128IntValue(augmentationLength);
if (frame.Lsda)
emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
}
emitCFIInstructions(frame.Instructions, frame.Begin);
unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
Streamer.emitValueToAlignment(Align);
Streamer.emitLabel(fdeEnd);
}
namespace {
struct CIEKey {
static const CIEKey getEmptyKey() {
return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX),
false);
}
static const CIEKey getTombstoneKey() {
return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX),
false);
}
CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
unsigned RAReg, bool IsBKeyFrame)
: Personality(Personality), PersonalityEncoding(PersonalityEncoding),
LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {}
explicit CIEKey(const MCDwarfFrameInfo &Frame)
: Personality(Frame.Personality),
PersonalityEncoding(Frame.PersonalityEncoding),
LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
IsBKeyFrame(Frame.IsBKeyFrame) {}
StringRef PersonalityName() const {
if (!Personality)
return StringRef();
return Personality->getName();
}
bool operator<(const CIEKey &Other) const {
return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
IsSignalFrame, IsSimple, RAReg) <
std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
Other.LsdaEncoding, Other.IsSignalFrame,
Other.IsSimple, Other.RAReg);
}
const MCSymbol *Personality;
unsigned PersonalityEncoding;
unsigned LsdaEncoding;
bool IsSignalFrame;
bool IsSimple;
unsigned RAReg;
bool IsBKeyFrame;
};
}
namespace llvm {
template <> struct DenseMapInfo<CIEKey> {
static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
static unsigned getHashValue(const CIEKey &Key) {
return static_cast<unsigned>(hash_combine(
Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame));
}
static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
return LHS.Personality == RHS.Personality &&
LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
LHS.LsdaEncoding == RHS.LsdaEncoding &&
LHS.IsSignalFrame == RHS.IsSignalFrame &&
LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg &&
LHS.IsBKeyFrame == RHS.IsBKeyFrame;
}
};
}
void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
bool IsEH) {
MCContext &Context = Streamer.getContext();
const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
const MCAsmInfo *AsmInfo = Context.getAsmInfo();
FrameEmitterImpl Emitter(IsEH, Streamer);
ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
if (IsEH && MOFI->getCompactUnwindSection()) {
Streamer.generateCompactUnwindEncodings(MAB);
bool SectionEmitted = false;
for (const MCDwarfFrameInfo &Frame : FrameArray) {
if (Frame.CompactUnwindEncoding == 0) continue;
if (!SectionEmitted) {
Streamer.switchSection(MOFI->getCompactUnwindSection());
Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize());
SectionEmitted = true;
}
NeedsEHFrameSection |=
Frame.CompactUnwindEncoding ==
MOFI->getCompactUnwindDwarfEHFrameOnly();
Emitter.EmitCompactUnwind(Frame);
}
}
if (!NeedsEHFrameSection) return;
MCSection &Section =
IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
: *MOFI->getDwarfFrameSection();
Streamer.switchSection(&Section);
MCSymbol *SectionStart = Context.createTempSymbol();
Streamer.emitLabel(SectionStart);
DenseMap<CIEKey, const MCSymbol *> CIEStarts;
const MCSymbol *DummyDebugKey = nullptr;
bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
llvm::stable_sort(FrameArrayX,
[](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
return CIEKey(X) < CIEKey(Y);
});
for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
const MCDwarfFrameInfo &Frame = *I;
++I;
if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
MOFI->getCompactUnwindDwarfEHFrameOnly())
continue;
CIEKey Key(Frame);
const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
if (!CIEStart)
CIEStart = &Emitter.EmitCIE(Frame);
Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
}
}
void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
uint64_t AddrDelta) {
MCContext &Context = Streamer.getContext();
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
Streamer.emitBytes(OS.str());
}
void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
uint64_t AddrDelta,
raw_ostream &OS) {
AddrDelta = ScaleAddrDelta(Context, AddrDelta);
if (AddrDelta == 0)
return;
support::endianness E =
Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
if (isUIntN(6, AddrDelta)) {
uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
OS << Opcode;
} else if (isUInt<8>(AddrDelta)) {
OS << uint8_t(dwarf::DW_CFA_advance_loc1);
OS << uint8_t(AddrDelta);
} else if (isUInt<16>(AddrDelta)) {
OS << uint8_t(dwarf::DW_CFA_advance_loc2);
support::endian::write<uint16_t>(OS, AddrDelta, E);
} else {
assert(isUInt<32>(AddrDelta));
OS << uint8_t(dwarf::DW_CFA_advance_loc4);
support::endian::write<uint32_t>(OS, AddrDelta, E);
}
}