pub mod decode;
pub mod text;
use decode::{Alu, Atomic, Branch, FloatBinary, FloatCompare, Fused, Instruction, Op, Width};
use super::calls::bare;
use super::{Decoded, Machine};
use vlk_arch::arch::riscv64::{F0, GP, RA, slot};
use vlk_ir::ir::{
AtomicOp, BinOp, Cond, Expr, MachineInstruction, Operation, Ordering, RegRef, Rounding, Stmt,
};
use vlk_types::types::{CallKind, Convention, Precision};
const WORD: u64 = 0xffff_ffff;
const BOXED: u64 = 0xffff_ffff_0000_0000;
pub(super) struct Step {
instruction: Instruction,
far: Option<u64>,
}
pub(super) struct Lifter<'a> {
out: super::Emitter,
image: &'a vlk_loader::loader::Image,
}
fn sign_extend_word(value: Expr) -> Expr {
if let Expr::Const(value) = value {
return Expr::constant(value as u32 as i32 as i64 as u64);
}
Expr::SignExtend {
value: Box::new(value),
width: 4,
}
}
fn low_word(value: Expr) -> Expr {
Expr::bin(BinOp::And, value, Expr::constant(WORD))
}
fn choose(test: Expr, then: Expr, els: Expr) -> Expr {
Expr::Select {
cond: Cond::Ne,
lhs: Box::new(test),
rhs: Box::new(Expr::constant(0)),
then: Box::new(then),
els: Box::new(els),
}
}
fn float_extreme(p: Precision, larger: bool, a: Expr, b: Expr) -> Expr {
let nan = |value: &Expr| {
Expr::apply(
Operation::FloatUnordered(p),
vec![value.clone(), value.clone()],
)
};
let less =
|x: &Expr, y: &Expr| Expr::apply(Operation::FloatLess(p), vec![x.clone(), y.clone()]);
let canonical = Expr::constant(match p {
Precision::Single => 0x7fc0_0000,
Precision::Double => 0x7ff8_0000_0000_0000,
});
let equal = Expr::bin(
if larger { BinOp::And } else { BinOp::Or },
a.clone(),
b.clone(),
);
let (first, second) = if larger { (&b, &a) } else { (&a, &b) };
let ordered = choose(
less(&a, &b),
first.clone(),
choose(less(&b, &a), second.clone(), equal),
);
choose(
nan(&a),
choose(nan(&b), canonical, b.clone()),
choose(nan(&b), a.clone(), ordered),
)
}
fn float_class(p: Precision, value: Expr) -> Expr {
let (fraction_bits, exponent_ones) = match p {
Precision::Single => (23, 0xff),
Precision::Double => (52, 0x7ff),
};
let field = |shift: u64, mask: u64| {
Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shr, value.clone(), Expr::constant(shift)),
Expr::constant(mask),
)
};
let sign = field(
fraction_bits + if p == Precision::Single { 8 } else { 11 },
1,
);
let exponent = field(fraction_bits, exponent_ones);
let fraction = field(0, (1 << fraction_bits) - 1);
let quiet = field(fraction_bits - 1, 1);
let is = |field: &Expr, constant: u64| {
Expr::truth(Cond::Eq, field.clone(), Expr::constant(constant))
};
let signed = |negative: u64, positive: u64| {
choose(
sign.clone(),
Expr::constant(1 << negative),
Expr::constant(1 << positive),
)
};
choose(
is(&exponent, exponent_ones),
choose(
is(&fraction, 0),
signed(0, 7),
choose(quiet, Expr::constant(1 << 9), Expr::constant(1 << 8)),
),
choose(
is(&exponent, 0),
choose(is(&fraction, 0), signed(3, 4), signed(2, 5)),
signed(1, 6),
),
)
}
fn precision(precision: decode::Precision) -> Precision {
match precision {
decode::Precision::Single => Precision::Single,
decode::Precision::Double => Precision::Double,
}
}
fn rounding(mode: u8) -> Rounding {
match mode {
1 => Rounding::TowardZero,
2 => Rounding::Down,
3 => Rounding::Up,
4 => Rounding::NearestAway,
_ => Rounding::NearestEven,
}
}
fn rounds_to_nearest(mode: u8) -> bool {
matches!(mode, 0 | 7)
}
impl<'a> Lifter<'a> {
pub(super) fn new(image: &'a vlk_loader::loader::Image) -> Self {
Self {
out: super::Emitter::default(),
image,
}
}
fn read(&self, register: u8) -> Expr {
match slot(register) {
None => Expr::constant(0),
Some(GP) if let Some(address) = self.image.global_pointer => Expr::constant(address),
Some(index) => Expr::reg(index, 64),
}
}
fn write(&mut self, register: u8, value: Expr) {
let Some(index) = slot(register) else {
return;
};
self.out.stmts.push(Stmt::Assign {
dest: RegRef { index, width: 64 },
value,
at: None,
});
}
fn address(&self, base: u8, offset: i64) -> Expr {
Expr::bin(BinOp::Add, self.read(base), Expr::constant(offset as u64))
}
fn read_float(register: u8, precision: Precision) -> Expr {
let whole = Expr::reg(F0 + u16::from(register & 31), 64);
match precision {
Precision::Double => whole,
Precision::Single => low_word(whole),
}
}
fn write_float(&mut self, register: u8, precision: Precision, value: Expr) {
let value = match precision {
Precision::Double => value,
Precision::Single => Expr::bin(BinOp::Or, value, Expr::constant(BOXED)),
};
self.out.stmts.push(Stmt::Assign {
dest: RegRef {
index: F0 + u16::from(register & 31),
width: 64,
},
value,
at: None,
});
}
fn unsupported(&mut self, instruction: &Instruction, pc: u64, writes: Vec<u16>) {
self.out.stmts.push(Stmt::Unsupported {
at: None,
text: format!("{} at 0x{pc:x}", text::text(instruction, pc)),
writes: Some(writes),
});
}
fn hold(&mut self, value: Expr) -> Expr {
self.out.stmts.push(Stmt::Assign {
dest: RegRef {
index: vlk_ir::ir::EXCHANGE,
width: 64,
},
value,
at: None,
});
Expr::reg(vlk_ir::ir::EXCHANGE, 64)
}
fn alu(&self, op: Alu, word: bool, a: Expr, b: Expr) -> Expr {
if word {
let count = || Expr::bin(BinOp::And, b.clone(), Expr::constant(31));
let narrow = |op, a: Expr, b: Expr| sign_extend_word(Expr::bin(op, a, b));
return match op {
Alu::Add => narrow(BinOp::Add, a, b),
Alu::Sub => narrow(BinOp::Sub, a, b),
Alu::Multiply => narrow(BinOp::Mul, a, b),
Alu::ShiftLeft => narrow(BinOp::Shl, a, count()),
Alu::ShiftRight => narrow(BinOp::Shr, low_word(a), count()),
Alu::ShiftRightArithmetic => narrow(BinOp::Sar, sign_extend_word(a), count()),
Alu::Divide => narrow(BinOp::DivS, low_word(a), low_word(b)),
Alu::DivideUnsigned => narrow(BinOp::DivU, low_word(a), low_word(b)),
Alu::Remainder => narrow(BinOp::ModS, low_word(a), low_word(b)),
Alu::RemainderUnsigned => narrow(BinOp::ModU, low_word(a), low_word(b)),
_ => Expr::constant(0),
};
}
match op {
Alu::Add => Expr::bin(BinOp::Add, a, b),
Alu::Sub => Expr::bin(BinOp::Sub, a, b),
Alu::ShiftLeft => Expr::bin(BinOp::Shl, a, b),
Alu::Less => Expr::truth(Cond::Lt, a, b),
Alu::LessUnsigned => Expr::truth(Cond::Cc, a, b),
Alu::Xor => Expr::bin(BinOp::Xor, a, b),
Alu::ShiftRight => Expr::bin(BinOp::Shr, a, b),
Alu::ShiftRightArithmetic => Expr::bin(BinOp::Sar, a, b),
Alu::Or => Expr::bin(BinOp::Or, a, b),
Alu::And => Expr::bin(BinOp::And, a, b),
Alu::Multiply => Expr::bin(BinOp::Mul, a, b),
Alu::MultiplyHigh => Expr::bin(BinOp::MulHighS, a, b),
Alu::MultiplyHighUnsigned => Expr::bin(BinOp::MulHigh, a, b),
Alu::MultiplyHighSignedUnsigned => Expr::bin(
BinOp::Sub,
Expr::bin(BinOp::MulHigh, a.clone(), b.clone()),
Expr::bin(BinOp::And, Expr::bin(BinOp::Sar, a, Expr::constant(63)), b),
),
Alu::Divide => Expr::bin(BinOp::DivS, a, b),
Alu::DivideUnsigned => Expr::bin(BinOp::DivU, a, b),
Alu::Remainder => Expr::bin(BinOp::ModS, a, b),
Alu::RemainderUnsigned => Expr::bin(BinOp::ModU, a, b),
}
}
fn link(&mut self, register: u8, next: u64) {
self.write(register, Expr::constant(next));
}
fn call(&mut self, target: Option<u64>, through: Option<Expr>) {
match (target, through) {
(Some(target), _) => {
self.out
.stmts
.push(bare(CallKind::Invoke, self.image, Some(target)));
}
(None, Some(through)) => {
self.out.stmts.push(super::call_through_as(
CallKind::Invoke,
self.image,
through,
Convention::of(self.image.isa, self.image.format, self.image.go),
));
}
(None, None) => {}
}
}
fn float(&mut self, instruction: &Instruction, pc: u64) {
let Instruction {
op,
rd,
rs1,
rs2,
rs3,
imm,
rounding: mode,
..
} = *instruction;
let apply = Expr::apply;
match op {
Op::FloatLoad(p) => {
let p = precision(p);
let value = Expr::Load {
addr: Box::new(self.address(rs1, imm)),
width: p.bits() / 8,
signed: false,
};
self.write_float(rd, p, value);
}
Op::FloatStore(p) => {
let p = precision(p);
self.out.stmts.push(Stmt::Store {
addr: self.address(rs1, imm),
value: Self::read_float(rs2, p),
width: p.bits() / 8,
at: None,
});
}
Op::Fused { op, precision: p } if rounds_to_nearest(mode) => {
let p = precision(p);
let negate = |value: Expr| apply(Operation::FloatNegate(p), vec![value]);
let (a, b, c) = (
Self::read_float(rs1, p),
Self::read_float(rs2, p),
Self::read_float(rs3, p),
);
let (a, c) = match op {
Fused::MultiplyAdd => (a, c),
Fused::MultiplySub => (a, negate(c)),
Fused::NegatedMultiplySub => (negate(a), c),
Fused::NegatedMultiplyAdd => (negate(a), negate(c)),
};
self.write_float(rd, p, apply(Operation::FloatMulAdd(p), vec![a, b, c]));
}
Op::FloatBinary { op, precision: p } => {
let p = precision(p);
let (a, b) = (Self::read_float(rs1, p), Self::read_float(rs2, p));
let sign = Expr::constant(match p {
Precision::Single => 0x8000_0000,
Precision::Double => 0x8000_0000_0000_0000,
});
let magnitude = Expr::constant(match p {
Precision::Single => 0x7fff_ffff,
Precision::Double => 0x7fff_ffff_ffff_ffff,
});
let arithmetic = |operation| apply(operation, vec![a.clone(), b.clone()]);
let value = match op {
FloatBinary::Add if rounds_to_nearest(mode) => {
arithmetic(Operation::FloatAdd(p))
}
FloatBinary::Sub if rounds_to_nearest(mode) => {
arithmetic(Operation::FloatSub(p))
}
FloatBinary::Multiply if rounds_to_nearest(mode) => {
arithmetic(Operation::FloatMul(p))
}
FloatBinary::Divide if rounds_to_nearest(mode) => {
arithmetic(Operation::FloatDiv(p))
}
FloatBinary::Min => float_extreme(p, false, a, b),
FloatBinary::Max => float_extreme(p, true, a, b),
FloatBinary::Sign if rs1 == rs2 => a,
FloatBinary::SignNegated if rs1 == rs2 => {
apply(Operation::FloatNegate(p), vec![a])
}
FloatBinary::SignXor if rs1 == rs2 => apply(Operation::FloatAbs(p), vec![a]),
FloatBinary::Sign => Expr::bin(
BinOp::Or,
Expr::bin(BinOp::And, a, magnitude),
Expr::bin(BinOp::And, b, sign),
),
FloatBinary::SignNegated => Expr::bin(
BinOp::Or,
Expr::bin(BinOp::And, a, magnitude),
Expr::bin(BinOp::Xor, Expr::bin(BinOp::And, b, sign.clone()), sign),
),
FloatBinary::SignXor => {
Expr::bin(BinOp::Xor, a, Expr::bin(BinOp::And, b, sign))
}
_ => {
self.rounded(instruction, pc);
return;
}
};
self.write_float(rd, p, value);
}
Op::FloatSqrt(p) if rounds_to_nearest(mode) => {
let p = precision(p);
let value = apply(Operation::FloatSqrt(p), vec![Self::read_float(rs1, p)]);
self.write_float(rd, p, value);
}
Op::FloatCompare { op, precision: p } => {
let p = precision(p);
let operation = match op {
FloatCompare::Equal => Operation::FloatEqual(p),
FloatCompare::Less => Operation::FloatLess(p),
FloatCompare::LessEqual => Operation::FloatLessEqual(p),
};
let value = apply(
operation,
vec![Self::read_float(rs1, p), Self::read_float(rs2, p)],
);
self.write(rd, value);
}
Op::FloatConvert { to }
if to == decode::Precision::Double || rounds_to_nearest(mode) =>
{
let to = precision(to);
let from = match to {
Precision::Single => Precision::Double,
Precision::Double => Precision::Single,
};
let value = apply(
Operation::FloatConvert { from, to },
vec![Self::read_float(rs1, from)],
);
self.write_float(rd, to, value);
}
Op::FloatToInt { from, word, signed } => {
let from = precision(from);
let source = Self::read_float(rs1, from);
let bits = if word { 32 } else { 64 };
let converted = apply(
Operation::FloatToInt {
signed,
bits,
from,
saturating: true,
rounding: rounding(mode),
},
vec![source.clone()],
);
let highest = match (word, signed) {
(true, true) => 0x7fff_ffff,
(true, false) => WORD,
(false, true) => i64::MAX as u64,
(false, false) => u64::MAX,
};
let value = Expr::Select {
cond: Cond::Ne,
lhs: Box::new(apply(
Operation::FloatUnordered(from),
vec![source.clone(), source],
)),
rhs: Box::new(Expr::constant(0)),
then: Box::new(Expr::constant(highest)),
els: Box::new(converted),
};
let value = if word { sign_extend_word(value) } else { value };
self.write(rd, value);
}
Op::IntToFloat { to, word, signed }
if rounds_to_nearest(mode) || (word && to == decode::Precision::Double) =>
{
let to = precision(to);
let source = if word {
low_word(self.read(rs1))
} else {
self.read(rs1)
};
let value = apply(
Operation::IntToFloat {
signed,
bits: if word { 32 } else { 64 },
to,
},
vec![source],
);
self.write_float(rd, to, value);
}
Op::FloatBits(p) => {
let p = precision(p);
let value = match p {
Precision::Double => Self::read_float(rs1, p),
Precision::Single => sign_extend_word(Self::read_float(rs1, p)),
};
self.write(rd, value);
}
Op::BitsToFloat(p) => {
let p = precision(p);
let value = match p {
Precision::Double => self.read(rs1),
Precision::Single => low_word(self.read(rs1)),
};
self.write_float(rd, p, value);
}
Op::FloatClass(p) => {
let p = precision(p);
let value = float_class(p, Self::read_float(rs1, p));
self.write(rd, value);
}
_ => self.rounded(instruction, pc),
}
}
fn rounded(&mut self, instruction: &Instruction, pc: u64) {
let Instruction {
op,
rd,
rs1,
rs2,
rs3,
rounding: mode,
..
} = *instruction;
let suffixed = |single: &'static str, double: &'static str, p: decode::Precision| match p {
decode::Precision::Single => single,
decode::Precision::Double => double,
};
let float = |register: u8, p: decode::Precision| Self::read_float(register, precision(p));
let (mnemonic, inputs, result) = match op {
Op::FloatBinary { op, precision: p } => {
let mnemonic = match op {
FloatBinary::Add => suffixed("fadd.s", "fadd.d", p),
FloatBinary::Sub => suffixed("fsub.s", "fsub.d", p),
FloatBinary::Multiply => suffixed("fmul.s", "fmul.d", p),
FloatBinary::Divide => suffixed("fdiv.s", "fdiv.d", p),
_ => {
self.unsupported(instruction, pc, vec![F0 + u16::from(rd)]);
return;
}
};
(mnemonic, vec![float(rs1, p), float(rs2, p)], p)
}
Op::FloatSqrt(p) => (suffixed("fsqrt.s", "fsqrt.d", p), vec![float(rs1, p)], p),
Op::Fused { op, precision: p } => {
let mnemonic = match op {
Fused::MultiplyAdd => suffixed("fmadd.s", "fmadd.d", p),
Fused::MultiplySub => suffixed("fmsub.s", "fmsub.d", p),
Fused::NegatedMultiplySub => suffixed("fnmsub.s", "fnmsub.d", p),
Fused::NegatedMultiplyAdd => suffixed("fnmadd.s", "fnmadd.d", p),
};
(
mnemonic,
vec![float(rs1, p), float(rs2, p), float(rs3, p)],
p,
)
}
Op::FloatConvert {
to: decode::Precision::Single,
} => (
"fcvt.s.d",
vec![float(rs1, decode::Precision::Double)],
decode::Precision::Single,
),
Op::IntToFloat { to, word, signed } => {
let mnemonic = match (to, word, signed) {
(decode::Precision::Single, true, true) => "fcvt.s.w",
(decode::Precision::Single, true, false) => "fcvt.s.wu",
(decode::Precision::Single, false, true) => "fcvt.s.l",
(decode::Precision::Single, false, false) => "fcvt.s.lu",
(decode::Precision::Double, true, true) => "fcvt.d.w",
(decode::Precision::Double, true, false) => "fcvt.d.wu",
(decode::Precision::Double, false, true) => "fcvt.d.l",
(decode::Precision::Double, false, false) => "fcvt.d.lu",
};
(mnemonic, vec![self.read(rs1)], to)
}
_ => {
self.unsupported(instruction, pc, vec![F0 + u16::from(rd)]);
return;
}
};
let output = RegRef {
index: vlk_ir::ir::TEMP_BASE + 0x60,
width: 64,
};
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::RiscvRounded { mnemonic, mode },
inputs,
outputs: vec![output],
});
let result = precision(result);
let bits = match result {
Precision::Double => Expr::reg(output.index, 64),
Precision::Single => low_word(Expr::reg(output.index, 64)),
};
self.write_float(rd, result, bits);
}
fn atomic(&mut self, instruction: &Instruction) {
let Instruction {
op,
rd,
rs1,
rs2,
rounding: order,
..
} = *instruction;
let output = RegRef {
index: vlk_ir::ir::TEMP_BASE + 0x60,
width: 64,
};
let address = self.read(rs1);
let extend = |width: Width, value: Expr| match width {
Width::Word => sign_extend_word(value),
_ => value,
};
let operand = |width: Width, value: Expr| match width {
Width::Word => low_word(value),
_ => value,
};
match op {
Op::LoadReserved(width) => {
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::ArmExclusive {
load: true,
width: width.bytes(),
pair: false,
ordered: order != 0,
},
inputs: vec![address],
outputs: vec![output],
});
self.write(rd, extend(width, Expr::reg(output.index, 64)));
}
Op::StoreConditional(width) => {
let value = operand(width, self.read(rs2));
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::ArmExclusive {
load: false,
width: width.bytes(),
pair: false,
ordered: order != 0,
},
inputs: vec![address, value],
outputs: vec![output],
});
self.write(rd, Expr::reg(output.index, 64));
}
Op::Atomic { op, width } => {
let op = match op {
Atomic::Swap => AtomicOp::Exchange,
Atomic::Add => AtomicOp::Add,
Atomic::Xor => AtomicOp::Xor,
Atomic::And => AtomicOp::And,
Atomic::Or => AtomicOp::Or,
Atomic::Min => AtomicOp::Min,
Atomic::Max => AtomicOp::Max,
Atomic::MinUnsigned => AtomicOp::MinUnsigned,
Atomic::MaxUnsigned => AtomicOp::MaxUnsigned,
};
let ordering = match order & 3 {
0 => Ordering::Relaxed,
1 => Ordering::Release,
2 => Ordering::Acquire,
_ => Ordering::AcqRel,
};
let value = operand(width, self.read(rs2));
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::Atomic {
op,
width: width.bytes(),
ordering,
},
inputs: vec![address, value],
outputs: vec![RegRef {
index: output.index,
width: width.bytes() * 8,
}],
});
self.write(
rd,
extend(width, Expr::reg(output.index, width.bytes() * 8)),
);
}
_ => {}
}
}
fn instruction(&mut self, step: &Step, pc: u64) -> bool {
let instruction = &step.instruction;
let Instruction {
op,
rd,
rs1,
rs2,
imm,
length,
..
} = *instruction;
let next = pc.wrapping_add(u64::from(length));
match op {
Op::Lui => {
self.write(rd, Expr::constant(imm as u64));
}
Op::Auipc => {
let value = pc.wrapping_add(imm as u64);
self.write(rd, Expr::constant(value));
}
Op::Jal => {
let target = match self.image.relocations.get(&pc) {
Some(target) => *target,
None => pc.wrapping_add(imm as u64),
};
if rd == 0 {
if target == pc && self.image.relocatable {
self.out.stmts.extend([
bare(CallKind::Tail, self.image, None),
Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 64),
at: None,
},
]);
return true;
}
self.out.stmts.push(Stmt::Br {
target: Some(target),
at: None,
});
return true;
}
self.link(rd, next);
self.call(Some(target), None);
return false;
}
Op::Jalr => {
let outside = self
.image
.relocations
.get(&pc.wrapping_sub(4))
.copied()
.filter(|_| self.image.relocatable && step.far.is_some());
let known = outside.or(step.far);
if rd == 0 {
if slot(rs1) == Some(RA) && imm == 0 {
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 64),
at: None,
});
} else if let Some(target) = known {
self.out.stmts.push(Stmt::Br {
target: Some(target),
at: None,
});
} else {
self.out.stmts.push(Stmt::BrIndirect {
target: self.address(rs1, imm),
at: None,
});
}
return true;
}
if let Some(target) = known {
self.link(rd, next);
self.call(Some(target), None);
return false;
}
let through = self.address(rs1, imm);
let through = if rs1 == rd {
self.hold(through)
} else {
through
};
self.link(rd, next);
self.call(None, Some(through));
return false;
}
Op::Branch(branch) => {
let cond = match branch {
Branch::Equal => Cond::Eq,
Branch::NotEqual => Cond::Ne,
Branch::Less => Cond::Lt,
Branch::GreaterEqual => Cond::Ge,
Branch::LessUnsigned => Cond::Cc,
Branch::GreaterEqualUnsigned => Cond::Cs,
};
self.out.stmts.push(Stmt::Brif {
cond,
lhs: self.read(rs1),
rhs: self.read(rs2),
target: pc.wrapping_add(imm as u64),
at: None,
});
return true;
}
Op::Load { width, signed } => {
let value = Expr::Load {
addr: Box::new(self.address(rs1, imm)),
width: width.bytes(),
signed: signed && width != Width::Double,
};
self.write(rd, value);
}
Op::Store(width) => {
let value = match width {
Width::Double => self.read(rs2),
_ => low_word(self.read(rs2)),
};
self.out.stmts.push(Stmt::Store {
addr: self.address(rs1, imm),
value,
width: width.bytes(),
at: None,
});
}
Op::Immediate { op, word } => {
let value = if word && op == Alu::Add && imm == 0 {
sign_extend_word(self.read(rs1))
} else {
self.alu(op, word, self.read(rs1), Expr::constant(imm as u64))
};
self.write(rd, value);
}
Op::Register { op, word } => {
let value = self.alu(op, word, self.read(rs1), self.read(rs2));
self.write(rd, value);
}
Op::Fence | Op::FenceInstructions => {}
Op::Ecall => {
self.out.stmts.push(Stmt::Call {
kind: CallKind::Syscall,
target: None,
through: None,
convention: Convention::SyscallRiscv,
args: None,
floats_named: true,
abi: None,
clobbers: None,
outputs: vlk_ir::ir::fallback_call_outputs(Convention::SyscallRiscv, None),
via: None,
at: None,
});
}
Op::Ebreak => {
self.out.stmts.push(Stmt::Trap { at: None });
return true;
}
Op::Csr { op, immediate } => {
let change = match op {
decode::Csr::Write => 1,
decode::Csr::Set => 2,
decode::Csr::Clear => 3,
};
let reads_only = change != 1 && rs1 == 0;
let inputs = if reads_only {
Vec::new()
} else if immediate {
vec![Expr::constant(u64::from(rs1))]
} else {
vec![self.read(rs1)]
};
let output = RegRef {
index: vlk_ir::ir::TEMP_BASE + 0x60,
width: 64,
};
let outputs = if rd != 0 || reads_only {
vec![output]
} else {
Vec::new()
};
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::RiscvCsr {
register: imm as u16,
change,
},
inputs,
outputs,
});
self.write(rd, Expr::reg(output.index, 64));
}
Op::LoadReserved(_) | Op::StoreConditional(_) | Op::Atomic { .. } => {
self.atomic(instruction);
}
Op::FloatLoad(_)
| Op::FloatStore(_)
| Op::Fused { .. }
| Op::FloatBinary { .. }
| Op::FloatSqrt(_)
| Op::FloatCompare { .. }
| Op::FloatConvert { .. }
| Op::FloatToInt { .. }
| Op::IntToFloat { .. }
| Op::FloatBits(_)
| Op::BitsToFloat(_)
| Op::FloatClass(_) => self.float(instruction, pc),
}
false
}
}
fn branch_target(step: &Step, pc: u64) -> Option<u64> {
let instruction = &step.instruction;
match instruction.op {
Op::Jal if instruction.rd == 0 => Some(pc.wrapping_add(instruction.imm as u64)),
Op::Jalr if instruction.rd == 0 => step.far,
Op::Branch(_) => Some(pc.wrapping_add(instruction.imm as u64)),
_ => None,
}
}
pub(super) fn decode(bytes: &[u8], addr: u64) -> (Vec<Decoded<Step>>, Option<String>) {
let mut decoded = Vec::new();
let mut offset = 0;
let mut upper: Option<(u8, u64)> = None;
while offset < bytes.len() {
let pc = addr.wrapping_add(offset as u64);
let Some(instruction) = decode::decode(&bytes[offset..]) else {
return (
decoded,
Some(format!("undecodable instruction at 0x{pc:x}")),
);
};
let length = usize::from(instruction.length);
let Some(next) = pc.checked_add(length as u64) else {
return (
decoded,
Some(format!("instruction address overflows at 0x{pc:x}")),
);
};
let held = upper.take();
let mut far = None;
match instruction.op {
Op::Auipc => upper = Some((instruction.rd, pc.wrapping_add(instruction.imm as u64))),
Op::Lui => upper = Some((instruction.rd, instruction.imm as u64)),
Op::Jalr => {
if let Some((register, value)) = held
&& register == instruction.rs1
&& register != 0
{
far = Some(value.wrapping_add(instruction.imm as u64));
}
}
_ => {}
}
decoded.push(Decoded {
pc,
next,
instruction: Step { instruction, far },
});
offset += length;
}
(decoded, None)
}
impl Machine for Lifter<'_> {
type Instruction = Step;
fn out(&mut self) -> &mut super::Emitter {
&mut self.out
}
fn branch_target(&self, step: &Step, pc: u64) -> Option<u64> {
if let Some(target) = self.image.relocations.get(&pc)
&& matches!(step.instruction.op, Op::Jal if step.instruction.rd == 0)
{
return Some(*target);
}
branch_target(step, pc)
}
fn step(&mut self, instruction: &Step, pc: u64) -> bool {
self.instruction(instruction, pc)
}
}
mod starts;
pub(crate) use starts::{direct_transfers, function_starts, global_pointer_at_entry, opens};
#[cfg(test)]
mod tests;