#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/MC/StringTableBuilder.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;
class llvm::MCDwarfLineStr {
MCSymbol *LineStrLabel = nullptr;
StringTableBuilder LineStrings{StringTableBuilder::DWARF};
bool UseRelocs = false;
public:
explicit MCDwarfLineStr(MCContext &Ctx) {
UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
if (UseRelocs)
LineStrLabel =
Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol();
}
void emitRef(MCStreamer *MCOS, StringRef Path);
void emitSection(MCStreamer *MCOS);
};
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;
}
void MCDwarfLineEntry::Make(MCObjectStreamer *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 *MakeStartMinusEndExpr(const MCStreamer &MCOS,
const MCSymbol &Start,
const MCSymbol &End,
int IntVal) {
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
const MCExpr *Res =
MCSymbolRefExpr::create(&End, Variant, MCOS.getContext());
const MCExpr *RHS =
MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext());
const MCExpr *Res1 =
MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
const MCExpr *Res2 =
MCConstantExpr::create(IntVal, MCOS.getContext());
const MCExpr *Res3 =
MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
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;
}
static inline void
EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section,
const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
unsigned FileNum = 1;
unsigned LastLine = 1;
unsigned Column = 0;
unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
unsigned Isa = 0;
unsigned Discriminator = 0;
MCSymbol *LastLabel = nullptr;
for (const MCDwarfLineEntry &LineEntry : LineEntries) {
int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
if (FileNum != LineEntry.getFileNum()) {
FileNum = LineEntry.getFileNum();
MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
MCOS->EmitULEB128IntValue(FileNum);
}
if (Column != LineEntry.getColumn()) {
Column = LineEntry.getColumn();
MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
MCOS->EmitULEB128IntValue(Column);
}
if (Discriminator != LineEntry.getDiscriminator() &&
MCOS->getContext().getDwarfVersion() >= 4) {
Discriminator = LineEntry.getDiscriminator();
unsigned Size = getULEB128Size(Discriminator);
MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
MCOS->EmitULEB128IntValue(Size + 1);
MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
MCOS->EmitULEB128IntValue(Discriminator);
}
if (Isa != LineEntry.getIsa()) {
Isa = LineEntry.getIsa();
MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
MCOS->EmitULEB128IntValue(Isa);
}
if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
Flags = LineEntry.getFlags();
MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
}
if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
MCSymbol *Label = LineEntry.getLabel();
const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
asmInfo->getCodePointerSize());
Discriminator = 0;
LastLine = LineEntry.getLine();
LastLabel = Label;
}
MCSymbol *SectionEnd = MCOS->endSection(Section);
MCContext &Ctx = MCOS->getContext();
MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
AsmInfo->getCodePointerSize());
}
void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS,
MCDwarfLineTableParams Params) {
MCContext &context = MCOS->getContext();
auto &LineTables = context.getMCDwarfLineTables();
if (LineTables.empty())
return;
Optional<MCDwarfLineStr> LineStr;
if (context.getDwarfVersion() >= 5)
LineStr = MCDwarfLineStr(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 (Header.MCDwarfFiles.empty())
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());
LineStrings.finalizeInOrder();
SmallString<0> Data;
Data.resize(LineStrings.getSize());
LineStrings.write((uint8_t *)Data.data());
MCOS->EmitBinaryData(Data.str());
}
void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
int RefSize = 4;
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->EmitIntValue(0, 1);
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->EmitIntValue(0, 1);
MCOS->EmitIntValue(0, 1);
}
MCOS->EmitIntValue(0, 1);
}
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) {
MD5::MD5Result *Cksum = DwarfFile.Checksum;
MCOS->EmitBinaryData(
StringRef(reinterpret_cast<const char *>(Cksum->Bytes.data()),
Cksum->Bytes.size()));
}
if (HasSource) {
if (LineStr)
LineStr->emitRef(MCOS, DwarfFile.Source.getValueOr(StringRef()));
else {
MCOS->EmitBytes(
DwarfFile.Source.getValueOr(StringRef()));
MCOS->EmitBytes(StringRef("\0", 1));
}
}
}
void MCDwarfLineTableHeader::emitV5FileDirTables(
MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr,
StringRef CtxCompilationDir) const {
MCOS->EmitIntValue(1, 1);
MCOS->EmitULEB128IntValue(dwarf::DW_LNCT_path);
MCOS->EmitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
: dwarf::DW_FORM_string);
MCOS->EmitULEB128IntValue(MCDwarfDirs.size() + 1);
const StringRef CompDir =
CompilationDir.empty() ? CtxCompilationDir : StringRef(CompilationDir);
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->EmitIntValue(Entries, 1);
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.size());
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->EmitLabel(LineStartSym);
MCSymbol *LineEndSym = context.createTempSymbol();
emitAbsValue(*MCOS,
MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
unsigned LineTableVersion = context.getDwarfVersion();
if (context.getObjectFileInfo()->getTargetTriple().isOSDarwin())
LineTableVersion = 2;
MCOS->EmitIntValue(LineTableVersion, 2);
unsigned PreHeaderLengthBytes = 4 + 2;
if (LineTableVersion >= 5) {
MCOS->EmitIntValue(context.getAsmInfo()->getCodePointerSize(), 1);
MCOS->EmitIntValue(0, 1);
PreHeaderLengthBytes += 2;
}
MCSymbol *ProEndSym = context.createTempSymbol();
emitAbsValue(*MCOS,
MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
(PreHeaderLengthBytes + 4)),
4);
MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
if (LineTableVersion >= 4)
MCOS->EmitIntValue(1, 1);
MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
MCOS->EmitIntValue(Params.DWARF2LineBase, 1);
MCOS->EmitIntValue(Params.DWARF2LineRange, 1);
MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
for (char Length : StandardOpcodeLengths)
MCOS->EmitIntValue(Length, 1);
if (LineTableVersion >= 5)
emitV5FileDirTables(MCOS, LineStr, context.getCompilationDir());
else
emitV2FileDirTables(MCOS);
MCOS->EmitLabel(ProEndSym);
return std::make_pair(LineStartSym, LineEndSym);
}
void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS,
MCDwarfLineTableParams Params,
Optional<MCDwarfLineStr> &LineStr) const {
MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
for (const auto &LineSec : MCLineSections.getMCLineEntries())
EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
MCOS->EmitLabel(LineEndSym);
}
Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory,
StringRef &FileName,
MD5::MD5Result *Checksum,
Optional<StringRef> Source,
unsigned FileNumber) {
return Header.tryGetFile(Directory, FileName, Checksum, Source, FileNumber);
}
Expected<unsigned>
MCDwarfLineTableHeader::tryGetFile(StringRef &Directory,
StringRef &FileName,
MD5::MD5Result *Checksum,
Optional<StringRef> &Source,
unsigned FileNumber) {
if (Directory == CompilationDir)
Directory = "";
if (FileName.empty()) {
FileName = "<stdin>";
Directory = "";
}
assert(!FileName.empty());
if (MCDwarfFiles.empty()) {
trackMD5Usage(Checksum);
HasSource = (Source != None);
}
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 = 0;
for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
if (Directory == MCDwarfDirs[DirIndex])
break;
}
if (DirIndex >= MCDwarfDirs.size())
MCDwarfDirs.push_back(Directory);
DirIndex++;
}
File.Name = FileName;
File.DirIndex = DirIndex;
File.Checksum = Checksum;
trackMD5Usage(Checksum);
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);
}
}
bool MCDwarfLineAddr::FixedEncode(MCContext &Context,
MCDwarfLineTableParams Params,
int64_t LineDelta, uint64_t AddrDelta,
raw_ostream &OS,
uint32_t *Offset, uint32_t *Size) {
if (LineDelta != INT64_MAX) {
OS << char(dwarf::DW_LNS_advance_line);
encodeSLEB128(LineDelta, OS);
}
bool SetDelta;
if (AddrDelta > 60000) {
const MCAsmInfo *asmInfo = Context.getAsmInfo();
unsigned AddrSize = asmInfo->getCodePointerSize();
OS << char(dwarf::DW_LNS_extended_op);
encodeULEB128(1 + AddrSize, OS);
OS << char(dwarf::DW_LNE_set_address);
*Offset = OS.tell();
*Size = AddrSize;
SetDelta = false;
std::vector<uint8_t> FillData;
FillData.insert(FillData.begin(), AddrSize, 0);
OS.write(reinterpret_cast<char *>(FillData.data()), AddrSize);
} else {
OS << char(dwarf::DW_LNS_fixed_advance_pc);
*Offset = OS.tell();
*Size = 2;
SetDelta = true;
OS << char(0);
OS << char(0);
}
if (LineDelta == INT64_MAX) {
OS << char(dwarf::DW_LNS_extended_op);
OS << char(1);
OS << char(dwarf::DW_LNE_end_sequence);
} else {
OS << char(dwarf::DW_LNS_copy);
}
return SetDelta;
}
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->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, context.getDwarfVersion() >= 4
? dwarf::DW_FORM_sec_offset
: dwarf::DW_FORM_data4);
if (context.getGenDwarfSectionSyms().size() > 1 &&
context.getDwarfVersion() >= 3) {
EmitAbbrev(MCOS, dwarf::DW_AT_ranges, context.getDwarfVersion() >= 4
? dwarf::DW_FORM_sec_offset
: dwarf::DW_FORM_data4);
} 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->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
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, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
EmitAbbrev(MCOS, 0, 0);
MCOS->EmitULEB128IntValue(3);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
EmitAbbrev(MCOS, 0, 0);
MCOS->EmitIntValue(0, 1);
}
static void EmitGenDwarfAranges(MCStreamer *MCOS,
const MCSymbol *InfoSectionSymbol) {
MCContext &context = MCOS->getContext();
auto &Sections = context.getGenDwarfSectionSyms();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
int Length = 4 + 2 + 4 + 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;
MCOS->EmitIntValue(Length - 4, 4);
MCOS->EmitIntValue(2, 2);
if (InfoSectionSymbol)
MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
asmInfo->needsDwarfSectionOffsetDirective());
else
MCOS->EmitIntValue(0, 4);
MCOS->EmitIntValue(AddrSize, 1);
MCOS->EmitIntValue(0, 1);
for(int i = 0; i < Pad; i++)
MCOS->EmitIntValue(0, 1);
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 = MakeStartMinusEndExpr(*MCOS,
*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 *RangesSectionSymbol) {
MCContext &context = MCOS->getContext();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
MCSymbol *InfoStart = context.createTempSymbol();
MCOS->EmitLabel(InfoStart);
MCSymbol *InfoEnd = context.createTempSymbol();
const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
emitAbsValue(*MCOS, Length, 4);
MCOS->EmitIntValue(context.getDwarfVersion(), 2);
const MCAsmInfo &AsmInfo = *context.getAsmInfo();
int AddrSize = AsmInfo.getCodePointerSize();
if (context.getDwarfVersion() >= 5) {
MCOS->EmitIntValue(dwarf::DW_UT_compile, 1);
MCOS->EmitIntValue(AddrSize, 1);
}
if (AbbrevSectionSymbol == nullptr)
MCOS->EmitIntValue(0, 4);
else
MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
AsmInfo.needsDwarfSectionOffsetDirective());
if (context.getDwarfVersion() <= 4)
MCOS->EmitIntValue(AddrSize, 1);
MCOS->EmitULEB128IntValue(1);
if (LineSectionSymbol)
MCOS->EmitSymbolValue(LineSectionSymbol, 4,
AsmInfo.needsDwarfSectionOffsetDirective());
else
MCOS->EmitIntValue(0, 4);
if (RangesSectionSymbol) {
MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
} 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 =
MCOS->getContext().getMCDwarfFiles();
MCOS->EmitBytes(MCDwarfFiles[1].Name);
MCOS->EmitIntValue(0, 1);
if (!context.getCompilationDir().empty()) {
MCOS->EmitBytes(context.getCompilationDir());
MCOS->EmitIntValue(0, 1);
}
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty()){
MCOS->EmitBytes(DwarfDebugFlags);
MCOS->EmitIntValue(0, 1);
}
StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
if (!DwarfDebugProducer.empty())
MCOS->EmitBytes(DwarfDebugProducer);
else
MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
MCOS->EmitIntValue(0, 1);
MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
const std::vector<MCGenDwarfLabelEntry> &Entries =
MCOS->getContext().getMCGenDwarfLabelEntries();
for (const auto &Entry : Entries) {
MCOS->EmitULEB128IntValue(2);
MCOS->EmitBytes(Entry.getName());
MCOS->EmitIntValue(0, 1);
MCOS->EmitIntValue(Entry.getFileNumber(), 4);
MCOS->EmitIntValue(Entry.getLineNumber(), 4);
const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
MCSymbolRefExpr::VK_None, context);
MCOS->EmitValue(AT_low_pc, AddrSize);
MCOS->EmitIntValue(0, 1);
MCOS->EmitULEB128IntValue(3);
MCOS->EmitIntValue(0, 1);
}
MCOS->EmitIntValue(0, 1);
MCOS->EmitLabel(InfoEnd);
}
static void EmitGenDwarfRanges(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
auto &Sections = context.getGenDwarfSectionSyms();
const MCAsmInfo *AsmInfo = context.getAsmInfo();
int AddrSize = AsmInfo->getCodePointerSize();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
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 *SectionStartAddr = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->emitFill(AddrSize, 0xFF);
MCOS->EmitValue(SectionStartAddr, AddrSize);
const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
*StartSymbol, *EndSymbol, 0);
MCOS->EmitIntValue(0, AddrSize);
emitAbsValue(*MCOS, SectionSize, AddrSize);
}
MCOS->EmitIntValue(0, AddrSize);
MCOS->EmitIntValue(0, AddrSize);
}
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 *RangesSectionSymbol = 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);
}
if (UseRangesSection) {
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
if (CreateDwarfSectionSymbols) {
RangesSectionSymbol = context.createTempSymbol();
MCOS->EmitLabel(RangesSectionSymbol);
}
}
assert((RangesSectionSymbol != nullptr) || !UseRangesSection);
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
if (UseRangesSection)
EmitGenDwarfRanges(MCOS);
EmitGenDwarfAbbrev(MCOS);
EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
RangesSectionSymbol);
}
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.EmitIntValue(Encoding, 1);
}
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.EmitIntValue(dwarf::DW_CFA_register, 1);
Streamer.EmitULEB128IntValue(Reg1);
Streamer.EmitULEB128IntValue(Reg2);
return;
}
case MCCFIInstruction::OpWindowSave:
Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
return;
case MCCFIInstruction::OpUndefined: {
unsigned Reg = Instr.getRegister();
Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
Streamer.EmitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpAdjustCfaOffset:
case MCCFIInstruction::OpDefCfaOffset: {
const bool IsRelative =
Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
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.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
Streamer.EmitULEB128IntValue(Reg);
CFAOffset = -Instr.getOffset();
Streamer.EmitULEB128IntValue(CFAOffset);
return;
}
case MCCFIInstruction::OpDefCfaRegister: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
Streamer.EmitULEB128IntValue(Reg);
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.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
Streamer.EmitULEB128IntValue(Reg);
Streamer.EmitSLEB128IntValue(Offset);
} else if (Reg < 64) {
Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
Streamer.EmitULEB128IntValue(Offset);
} else {
Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
Streamer.EmitULEB128IntValue(Reg);
Streamer.EmitULEB128IntValue(Offset);
}
return;
}
case MCCFIInstruction::OpRememberState:
Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
return;
case MCCFIInstruction::OpRestoreState:
Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
return;
case MCCFIInstruction::OpSameValue: {
unsigned Reg = Instr.getRegister();
Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
Streamer.EmitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpRestore: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
return;
}
case MCCFIInstruction::OpGnuArgsSize:
Streamer.EmitIntValue(dwarf::DW_CFA_GNU_args_size, 1);
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 = MakeStartMinusEndExpr(Streamer, *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();
const MCExpr *Length =
MakeStartMinusEndExpr(Streamer, *sectionStart, *sectionEnd, 4);
emitAbsValue(Streamer, Length, 4);
unsigned CIE_ID = IsEH ? 0 : -1;
Streamer.EmitIntValue(CIE_ID, 4);
uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
Streamer.EmitIntValue(CIEVersion, 1);
SmallString<8> Augmentation;
if (IsEH) {
Augmentation += "z";
if (Frame.Personality)
Augmentation += "P";
if (Frame.Lsda)
Augmentation += "L";
Augmentation += "R";
if (Frame.IsSignalFrame)
Augmentation += "S";
Streamer.EmitBytes(Augmentation);
}
Streamer.EmitIntValue(0, 1);
if (CIEVersion >= 4) {
Streamer.EmitIntValue(context.getAsmInfo()->getCodePointerSize(), 1);
Streamer.EmitIntValue(0, 1);
}
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.EmitIntValue(RAReg, 1);
} 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;
const MCExpr *Length = MakeStartMinusEndExpr(Streamer, *fdeStart, *fdeEnd, 0);
emitAbsValue(Streamer, Length, 4);
Streamer.EmitLabel(fdeStart);
const MCAsmInfo *asmInfo = context.getAsmInfo();
if (IsEH) {
const MCExpr *offset =
MakeStartMinusEndExpr(Streamer, cieStart, *fdeStart, 0);
emitAbsValue(Streamer, offset, 4);
} else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
const MCExpr *offset =
MakeStartMinusEndExpr(Streamer, SectionStart, cieStart, 0);
emitAbsValue(Streamer, offset, 4);
} else {
Streamer.EmitSymbolValue(&cieStart, 4);
}
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 =
MakeStartMinusEndExpr(Streamer, *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));
}
static const CIEKey getTombstoneKey() {
return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX));
}
CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
unsigned RAReg)
: Personality(Personality), PersonalityEncoding(PersonalityEncoding),
LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
IsSimple(IsSimple), RAReg(RAReg) {}
explicit CIEKey(const MCDwarfFrameInfo &Frame)
: Personality(Frame.Personality),
PersonalityEncoding(Frame.PersonalityEncoding),
LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
IsSimple(Frame.IsSimple), RAReg(Frame.RAReg) {}
const MCSymbol *Personality;
unsigned PersonalityEncoding;
unsigned LsdaEncoding;
bool IsSignalFrame;
bool IsSimple;
unsigned RAReg;
};
}
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));
}
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;
}
};
}
void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
bool IsEH) {
Streamer.generateCompactUnwindEncodings(MAB);
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()) {
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();
for (auto I = FrameArray.begin(), E = FrameArray.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);
support::endianness E =
Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
if (AddrDelta == 0) {
} else 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);
}
}