pub mod decode;
mod formats;
mod starts;
mod steps;
mod tables;
pub mod text;
pub(super) use formats::count_format;
pub(crate) use formats::count_from_block_format;
pub(super) use formats::split_shared_calls;
pub(crate) use starts::{direct_transfers, function_starts};
pub(super) use steps::{decode, decode_big};
pub(crate) use tables::{fold_fixed_entries, fold_table_slots};
use decode::{Alu, Branch, FloatFormat, FloatOp, FloatTest, Instruction, Op, Rounding};
use super::Machine;
use super::calls::bare;
use super::constants::{Known, Rules};
use steps::written_register;
use vlk_arch::arch::mips32::{F0, FLAG0, FP, GP, HI, LO, RA, SP, THREAD, slot};
use vlk_ir::ir::{BinOp, Cond, Expr, MachineInstruction, Operation, RegRef, Stmt};
use vlk_types::types::{CallKind, Convention, Precision};
const WORD: u64 = 0xffff_ffff;
const HELD: [u16; 2] = [vlk_ir::ir::TEMP_BASE + 0x62, vlk_ir::ir::TEMP_BASE + 0x63];
const HALF_ADDRESS: u16 = vlk_ir::ir::TEMP_BASE + 0x64;
pub(super) struct Step {
instruction: Instruction,
slot: Option<Instruction>,
then: Option<u64>,
unaligned: bool,
shared_pairs: u16,
}
pub(super) struct Lifter<'a> {
out: super::Emitter,
image: &'a vlk_loader::loader::Image,
start: u64,
big: bool,
shared_pairs: u16,
control: Control,
ends: [Option<u8>; 32],
}
fn low(value: Expr) -> Expr {
Expr::bin(BinOp::And, value, Expr::constant(WORD))
}
fn apply(op: Operation, args: Vec<Expr>) -> Expr {
Expr::Apply { op, args }
}
fn precision(double: bool) -> Precision {
if double {
Precision::Double
} else {
Precision::Single
}
}
fn pair(register: i64) -> u16 {
F0 + (register & 31) as u16 / 2
}
fn read_float(register: i64, p: Precision) -> Expr {
let whole = Expr::reg(pair(register), 64);
match p {
Precision::Double => whole,
Precision::Single if register & 1 == 1 => Expr::bin(BinOp::Shr, whole, Expr::constant(32)),
Precision::Single => low(whole),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Control {
Unwritten,
Rounds(u8),
Unknown,
}
fn lowest_word(p: Precision, rounding: vlk_ir::ir::Rounding) -> (u64, bool) {
use vlk_ir::ir::Rounding::{Down, NearestAway, NearestEven, TowardZero, Up};
let least = -2_147_483_648.0_f64;
match p {
Precision::Single => (u64::from((least as f32).to_bits()), true),
Precision::Double => match rounding {
Down => (least.to_bits(), true),
NearestEven => ((least - 0.5).to_bits(), true),
NearestAway => ((least - 0.5).to_bits(), false),
TowardZero | Up => ((least - 1.0).to_bits(), false),
},
}
}
fn sign_extend(value: Expr) -> Expr {
Expr::SignExtend {
value: Box::new(value),
width: 4,
}
}
impl<'a> Lifter<'a> {
pub(super) fn new(image: &'a vlk_loader::loader::Image, start: u64) -> Self {
Self {
out: super::Emitter::default(),
image,
start,
big: image.byte_order() == Some(object::Endianness::Big),
shared_pairs: u16::MAX,
control: Control::Unwritten,
ends: [None; 32],
}
}
fn read(&self, register: u8) -> Expr {
match slot(register) {
None => Expr::constant(0),
Some(index @ (SP | FP)) => Expr::reg(index, 64),
Some(index) => Expr::reg(index, 32),
}
}
fn assign_slot(&mut self, index: u16, value: Expr) {
self.out.stmts.push(Stmt::Assign {
dest: RegRef { index, width: 64 },
value,
at: None,
});
}
fn write(&mut self, register: u8, value: Expr) {
self.ends[usize::from(register & 31)] = None;
let Some(index) = slot(register) else {
return;
};
let frame = matches!(index, SP | FP)
&& match &value {
Expr::Reg {
index: SP | FP,
width: 64,
} => true,
Expr::Bin { lhs, .. } => matches!(
lhs.as_ref(),
Expr::Reg {
index: SP | FP,
width: 64
}
),
_ => false,
};
let value = if frame { value } else { low(value) };
self.assign_slot(index, value);
}
fn address(&self, base: u8, offset: i64) -> Expr {
match slot(base) {
Some(SP | FP) => Expr::bin(BinOp::Add, self.read(base), Expr::constant(offset as u64)),
_ if offset < 0 => low(Expr::bin(
BinOp::Sub,
self.read(base),
Expr::constant(offset.unsigned_abs()),
)),
_ => low(Expr::bin(
BinOp::Add,
self.read(base),
Expr::constant(offset as u64),
)),
}
}
fn unsupported(&mut self, instruction: &Instruction, pc: u64, writes: Option<Vec<u16>>) {
self.out.stmts.push(Stmt::Unsupported {
at: None,
text: format!("{} at 0x{pc:x}", text::text(instruction, pc)),
writes,
});
}
fn ends(&self, register: u8) -> Option<u8> {
if register == 0 {
return Some(0);
}
self.ends[usize::from(register)]
}
fn forget(&mut self) {
self.control = Control::Unwritten;
self.ends = [None; 32];
}
fn alu(op: Alu, a: Expr, b: Expr) -> Expr {
match op {
Alu::Add => Expr::bin(BinOp::Add, a, b),
Alu::Sub => Expr::bin(BinOp::Sub, a, b),
Alu::And => Expr::bin(BinOp::And, a, b),
Alu::Or => Expr::bin(BinOp::Or, a, b),
Alu::Xor => Expr::bin(BinOp::Xor, a, b),
Alu::Nor => Expr::bin(BinOp::Xor, Expr::bin(BinOp::Or, a, b), Expr::constant(WORD)),
Alu::Less => Expr::truth(Cond::Lt, a, b),
Alu::LessUnsigned if a == Expr::constant(0) => Expr::truth(Cond::Ne, b, a),
Alu::LessUnsigned if b == Expr::constant(1) => {
Expr::truth(Cond::Eq, a, Expr::constant(0))
}
Alu::LessUnsigned => Expr::truth(Cond::Cc, a, b),
Alu::ShiftLeft => Expr::bin(BinOp::Shl, a, b),
Alu::ShiftRight => Expr::bin(BinOp::Shr, a, b),
Alu::ShiftRightArithmetic => Expr::bin(BinOp::Sar, a, b),
Alu::Rotate => super::rotate(a, b, 32, true),
}
}
fn product(&self, rs: u8, rt: u8, signed: bool) -> Expr {
let operand = |register: u8| {
let value = self.read(register);
if signed { sign_extend(value) } else { value }
};
Expr::bin(BinOp::Mul, operand(rs), operand(rt))
}
fn set_wide(&mut self, value: Expr) {
self.assign_slot(vlk_ir::ir::EXCHANGE, value);
let held = Expr::reg(vlk_ir::ir::EXCHANGE, 64);
self.assign_slot(LO, low(held.clone()));
self.assign_slot(HI, Expr::bin(BinOp::Shr, held, Expr::constant(32)));
}
fn wide(&self) -> Expr {
Expr::bin(
BinOp::Or,
Expr::bin(BinOp::Shl, Expr::reg(HI, 32), Expr::constant(32)),
Expr::reg(LO, 32),
)
}
fn call(&mut self, target: Option<u64>, through: Option<Expr>) {
self.forget();
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::O32,
));
}
(None, None) => {}
}
}
fn half_word(&mut self, op: Op, rs: u8, rt: u8, imm: i64) {
self.assign_slot(HALF_ADDRESS, self.address(rs, imm));
let address = Expr::reg(HALF_ADDRESS, 32);
let aligned = Expr::bin(BinOp::And, address.clone(), Expr::constant(WORD & !3));
let word = Expr::Load {
addr: Box::new(aligned.clone()),
width: 4,
signed: false,
};
let within = Expr::bin(BinOp::And, address, Expr::constant(3));
let within = if self.big {
Expr::bin(BinOp::Xor, within, Expr::constant(3))
} else {
within
};
let place = Expr::bin(BinOp::Shl, within, Expr::constant(3));
let rest = Expr::bin(BinOp::Sub, Expr::constant(24), place.clone());
let register = self.read(rt);
let shifted = |op: BinOp, value: Expr, by: Expr| low(Expr::bin(op, value, by));
let kept = |op: BinOp, by: Expr| {
Expr::bin(
BinOp::Xor,
shifted(op, Expr::constant(WORD), by),
Expr::constant(WORD),
)
};
let (kept, moved) = match op {
Op::LoadLeft => (
kept(BinOp::Shl, rest.clone()),
shifted(BinOp::Shl, word.clone(), rest),
),
Op::LoadRight => (
kept(BinOp::Shr, place.clone()),
shifted(BinOp::Shr, word.clone(), place),
),
Op::StoreLeft => (
kept(BinOp::Shr, rest.clone()),
shifted(BinOp::Shr, register.clone(), rest),
),
_ => (
kept(BinOp::Shl, place.clone()),
shifted(BinOp::Shl, register.clone(), place),
),
};
let old = if matches!(op, Op::LoadLeft | Op::LoadRight) {
register
} else {
word
};
let value = Expr::bin(BinOp::Or, Expr::bin(BinOp::And, old, kept), moved);
if matches!(op, Op::LoadLeft | Op::LoadRight) {
self.write(rt, value);
} else {
self.out.stmts.push(Stmt::Store {
addr: aligned,
value,
width: 4,
at: None,
});
}
}
fn plain(&mut self, instruction: &Instruction, pc: u64, unaligned: bool) {
let Instruction {
op,
rs,
rt,
rd,
imm,
..
} = *instruction;
match op {
Op::Register(alu) => {
let shift = matches!(
alu,
Alu::ShiftLeft | Alu::ShiftRight | Alu::ShiftRightArithmetic | Alu::Rotate
);
let value = if shift {
let count = Expr::bin(BinOp::And, self.read(rs), Expr::constant(31));
Self::alu(alu, self.read(rt), count)
} else {
Self::alu(alu, self.read(rs), self.read(rt))
};
self.write(rd, value);
if matches!(alu, Alu::Add | Alu::Or) && rt == 0 {
self.ends[usize::from(rd)] = self.ends(rs).filter(|_| rd != 0);
}
}
Op::Immediate(alu) => {
let ends = self.ends(rs);
let set = (imm & 3) as u8;
let ends = match alu {
Alu::Or if set == 3 => Some(3),
Alu::And if set == 0 => Some(0),
Alu::Or => ends.map(|ends| ends | set),
Alu::And => ends.map(|ends| ends & set),
Alu::Xor => ends.map(|ends| ends ^ set),
Alu::Add => ends.map(|ends| (ends + set) & 3),
_ => None,
}
.filter(|_| rt != 0);
let frame = matches!(slot(rs), Some(SP | FP)) && alu == Alu::Add;
let operand = if frame {
Expr::constant(imm as u64)
} else {
Expr::constant(u64::from(imm as u32))
};
let value = match alu {
_ if alu == Alu::Add && !frame && rs != 0 && imm < 0 => Expr::bin(
BinOp::Sub,
self.read(rs),
Expr::constant(imm.unsigned_abs()),
),
_ => Self::alu(alu, self.read(rs), operand),
};
self.write(rt, value);
self.ends[usize::from(rt)] = ends;
}
Op::Shift(alu) => {
let value = Self::alu(alu, self.read(rt), Expr::constant(imm as u64));
self.write(rd, value);
}
Op::Lui => {
self.write(rt, Expr::constant(imm as u64));
self.ends[usize::from(rt)] = (rt != 0).then_some(0);
}
Op::Multiply { signed } => {
let product = self.product(rs, rt, signed);
self.set_wide(product);
}
Op::MultiplyAdd { signed, subtract } => {
let product = self.product(rs, rt, signed);
let op = if subtract { BinOp::Sub } else { BinOp::Add };
let value = Expr::bin(op, self.wide(), product);
self.set_wide(value);
}
Op::Divide { signed } => {
let (quotient, remainder) = if signed {
(BinOp::DivS, BinOp::ModS)
} else {
(BinOp::DivU, BinOp::ModU)
};
let (a, b) = (self.read(rs), self.read(rt));
self.assign_slot(LO, low(Expr::bin(quotient, a.clone(), b.clone())));
self.assign_slot(HI, low(Expr::bin(remainder, a, b)));
}
Op::MultiplyLow => {
let value = Expr::bin(BinOp::Mul, self.read(rs), self.read(rt));
self.write(rd, value);
}
Op::MoveFromHi => self.write(rd, Expr::reg(HI, 32)),
Op::MoveFromLo => self.write(rd, Expr::reg(LO, 32)),
Op::MoveToHi => {
let value = self.read(rs);
self.assign_slot(HI, low(value));
}
Op::MoveToLo => {
let value = self.read(rs);
self.assign_slot(LO, low(value));
}
Op::MoveIfZero | Op::MoveIfNotZero => {
let cond = if op == Op::MoveIfZero {
Cond::Eq
} else {
Cond::Ne
};
let value = Expr::Select {
cond,
lhs: Box::new(self.read(rt)),
rhs: Box::new(Expr::constant(0)),
then: Box::new(self.read(rs)),
els: Box::new(self.read(rd)),
};
self.write(rd, value);
}
Op::CountLeadingZeros | Op::CountLeadingOnes => {
let value = if op == Op::CountLeadingOnes {
Expr::bin(BinOp::Xor, self.read(rs), Expr::constant(WORD))
} else {
self.read(rs)
};
self.write(
rd,
Expr::apply(Operation::CountLeadingZeros(32), vec![value]),
);
}
Op::Extract => {
let mask = (1u64 << (u32::from(rd) + 1)) - 1;
let value = Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shr, self.read(rs), Expr::constant(imm as u64)),
Expr::constant(mask),
);
self.write(rt, value);
}
Op::Insert => {
let size = u32::from(rd) + 1 - imm as u32;
let mask = ((1u64 << size) - 1) << imm;
let value = Expr::bin(
BinOp::Or,
Expr::bin(BinOp::And, self.read(rt), Expr::constant(WORD & !mask)),
Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shl, self.read(rs), Expr::constant(imm as u64)),
Expr::constant(mask),
),
);
self.write(rt, value);
}
Op::SignExtendByte | Op::SignExtendHalf => {
let value = Expr::SignExtend {
value: Box::new(self.read(rt)),
width: if op == Op::SignExtendByte { 1 } else { 2 },
};
self.write(rd, value);
}
Op::SwapBytesInHalves => {
let value = self.read(rt);
let swapped = Expr::bin(
BinOp::Or,
Expr::bin(
BinOp::Shl,
Expr::bin(BinOp::And, value.clone(), Expr::constant(0x00ff_00ff)),
Expr::constant(8),
),
Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shr, value, Expr::constant(8)),
Expr::constant(0x00ff_00ff),
),
);
self.write(rd, swapped);
}
Op::Load { bytes, signed } => {
let address = self.address(rs, imm);
self.write(
rt,
Expr::Load {
addr: Box::new(address),
width: bytes,
signed,
},
);
}
Op::Store { bytes } => {
let value = self.read(rt);
self.out.stmts.push(Stmt::Store {
addr: self.address(rs, imm),
value: match slot(rt) {
Some(index @ (SP | FP)) => Expr::reg(index, 32),
_ => value,
},
width: bytes,
at: None,
});
}
Op::LoadRight if unaligned => {
let value = Expr::Load {
addr: Box::new(self.address(rs, imm)),
width: 4,
signed: false,
};
self.write(rt, value);
}
Op::StoreRight if unaligned => {
self.out.stmts.push(Stmt::Store {
addr: self.address(rs, imm),
value: self.read(rt),
width: 4,
at: None,
});
}
Op::LoadLeft | Op::LoadRight | Op::StoreLeft | Op::StoreRight => {
self.half_word(op, rs, rt, imm);
}
Op::LoadLinked | Op::StoreConditional => {
let output = RegRef {
index: vlk_ir::ir::TEMP_BASE + 0x60,
width: 64,
};
let load = op == Op::LoadLinked;
let mut inputs = vec![self.address(rs, imm)];
if !load {
inputs.push(self.read(rt));
}
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::ArmExclusive {
load,
width: 4,
pair: false,
ordered: false,
},
inputs,
outputs: vec![output],
});
let value = if load {
Expr::reg(output.index, 64)
} else {
Expr::truth(Cond::Eq, Expr::reg(output.index, 64), Expr::constant(0))
};
self.write(rt, value);
}
Op::Syscall => {
self.forget();
self.out.stmts.push(Stmt::Call {
kind: CallKind::Syscall,
target: None,
through: None,
convention: Convention::SyscallMips,
args: None,
floats_named: true,
abi: None,
clobbers: None,
outputs: vlk_ir::ir::fallback_call_outputs(Convention::SyscallMips, None),
via: None,
at: None,
});
}
Op::ReadHardware => self.write(rt, Expr::reg(THREAD, 32)),
Op::Sync | Op::Trap { .. } => {}
Op::Other => self.unsupported(instruction, pc, None),
Op::Break
| Op::Jump { .. }
| Op::JumpRegister { .. }
| Op::Branch { .. }
| Op::FloatBranch { .. } => {}
_ => self.float(instruction, pc),
}
}
fn write_float(&mut self, register: i64, p: Precision, value: Expr) {
let whole = Expr::reg(pair(register), 64);
let alone = self.shared_pairs >> ((register & 31) / 2) & 1 == 0;
let value = match p {
Precision::Double => value,
Precision::Single if alone => value,
Precision::Single if register & 1 == 1 => Expr::bin(
BinOp::Or,
low(whole),
Expr::bin(BinOp::Shl, value, Expr::constant(32)),
),
Precision::Single => Expr::bin(
BinOp::Or,
Expr::bin(BinOp::And, whole, Expr::constant(!WORD)),
value,
),
};
self.assign_slot(pair(register), value);
}
fn flag(flag: u8) -> Expr {
Expr::reg(FLAG0 + u16::from(flag & 7), 64)
}
fn float(&mut self, instruction: &Instruction, pc: u64) {
let Instruction {
op,
rs,
rt,
rd,
imm,
..
} = *instruction;
let (ft, fs, fd) = (i64::from(rt), i64::from(rd), imm);
match op {
Op::FloatArithmetic { op, double } => {
let p = precision(double);
let a = read_float(fs, p);
let b = read_float(ft, p);
let value = match op {
FloatOp::Add => apply(Operation::FloatAdd(p), vec![a, b]),
FloatOp::Sub => apply(Operation::FloatSub(p), vec![a, b]),
FloatOp::Mul => apply(Operation::FloatMul(p), vec![a, b]),
FloatOp::Div => apply(Operation::FloatDiv(p), vec![a, b]),
FloatOp::Sqrt => apply(Operation::FloatSqrt(p), vec![a]),
FloatOp::Abs => apply(Operation::FloatAbs(p), vec![a]),
FloatOp::Negate => apply(Operation::FloatNegate(p), vec![a]),
FloatOp::Move => a,
};
self.write_float(fd, p, value);
}
Op::FloatMultiplyAdd {
subtract,
negate,
double,
} => {
let p = precision(double);
let product = apply(
Operation::FloatMul(p),
vec![read_float(fs, p), read_float(ft, p)],
);
let addend = read_float(i64::from(rs), p);
let sum = if subtract {
apply(Operation::FloatSub(p), vec![product, addend])
} else {
apply(Operation::FloatAdd(p), vec![product, addend])
};
let value = if negate {
apply(Operation::FloatNegate(p), vec![sum])
} else {
sum
};
self.write_float(fd, p, value);
}
Op::FloatConvert { from, double } => {
let to = precision(double);
let value = match from {
FloatFormat::Word => apply(
Operation::IntToFloat {
signed: true,
bits: 32,
to,
},
vec![read_float(fs, Precision::Single)],
),
FloatFormat::Single | FloatFormat::Double => {
let from = precision(from == FloatFormat::Double);
apply(
Operation::FloatConvert { from, to },
vec![read_float(fs, from)],
)
}
};
self.write_float(fd, to, value);
}
Op::FloatToWord {
rounding: Rounding::Current,
..
} if self.control == Control::Unknown => {
self.unsupported(instruction, pc, Some(vec![pair(fd)]));
}
Op::FloatToWord { rounding, double } => {
let from = precision(double);
let rounding = match (rounding, self.control) {
(Rounding::Zero, _) | (Rounding::Current, Control::Rounds(1)) => {
vlk_ir::ir::Rounding::TowardZero
}
(Rounding::Up, _) | (Rounding::Current, Control::Rounds(2)) => {
vlk_ir::ir::Rounding::Up
}
(Rounding::Down, _) | (Rounding::Current, Control::Rounds(3)) => {
vlk_ir::ir::Rounding::Down
}
(Rounding::Nearest | Rounding::Current, _) => vlk_ir::ir::Rounding::NearestEven,
};
let source = read_float(fs, from);
let converted = apply(
Operation::FloatToInt {
signed: true,
bits: 32,
from,
saturating: true,
rounding,
},
vec![source.clone()],
);
let (least, inclusive) = lowest_word(from, rounding);
let below = if inclusive {
apply(
Operation::FloatLess(from),
vec![source.clone(), Expr::constant(least)],
)
} else {
apply(
Operation::FloatLessEqual(from),
vec![source.clone(), Expr::constant(least)],
)
};
let invalid = Expr::bin(
BinOp::Or,
apply(
Operation::FloatUnordered(from),
vec![source.clone(), source],
),
below,
);
let value = Expr::Select {
cond: Cond::Ne,
lhs: Box::new(invalid),
rhs: Box::new(Expr::constant(0)),
then: Box::new(Expr::constant(0x7fff_ffff)),
els: Box::new(low(converted)),
};
self.write_float(fd, Precision::Single, value);
}
Op::FloatCompare {
condition,
double,
flag,
} => {
let p = precision(double);
let operands = || vec![read_float(fs, p), read_float(ft, p)];
let mut terms = Vec::new();
if condition & 6 == 6 {
terms.push(apply(Operation::FloatLessEqual(p), operands()));
} else if condition & 4 != 0 {
terms.push(apply(Operation::FloatLess(p), operands()));
} else if condition & 2 != 0 {
terms.push(apply(Operation::FloatEqual(p), operands()));
}
if condition & 1 != 0 {
terms.push(apply(Operation::FloatUnordered(p), operands()));
}
let value = terms
.into_iter()
.reduce(|a, b| Expr::bin(BinOp::Or, a, b))
.unwrap_or(Expr::constant(0));
self.assign_slot(FLAG0 + u16::from(flag & 7), value);
}
Op::FloatSelect { test, double } => {
let p = precision(double);
let (cond, lhs) = match test {
FloatTest::Zero => (Cond::Eq, self.read(rt)),
FloatTest::NotZero => (Cond::Ne, self.read(rt)),
FloatTest::Flag { set: true, flag } => (Cond::Ne, Self::flag(flag)),
FloatTest::Flag { set: false, flag } => (Cond::Eq, Self::flag(flag)),
};
let value = Expr::Select {
cond,
lhs: Box::new(lhs),
rhs: Box::new(Expr::constant(0)),
then: Box::new(read_float(fs, p)),
els: Box::new(read_float(fd, p)),
};
self.write_float(fd, p, value);
}
Op::SelectOnFlag { set, flag } => {
let value = Expr::Select {
cond: if set { Cond::Ne } else { Cond::Eq },
lhs: Box::new(Self::flag(flag)),
rhs: Box::new(Expr::constant(0)),
then: Box::new(self.read(rs)),
els: Box::new(self.read(rd)),
};
self.write(rd, value);
}
Op::FloatTransfer {
to_float: false,
high,
} => {
let value = read_float(fs | i64::from(high), Precision::Single);
self.write(rt, value);
}
Op::FloatTransfer {
to_float: true,
high,
} => {
let value = self.read(rt);
self.write_float(fs | i64::from(high), Precision::Single, value);
}
Op::FloatControl { write } => {
let output = RegRef {
index: vlk_ir::ir::TEMP_BASE + 0x60,
width: 64,
};
let (inputs, outputs) = if write {
self.control = match self.ends(rt) {
Some(ends) if rd == 31 => Control::Rounds(ends),
_ => Control::Unknown,
};
(vec![self.read(rt)], Vec::new())
} else {
(Vec::new(), vec![output])
};
self.out.stmts.push(Stmt::Machine {
at: None,
instruction: MachineInstruction::MipsFloatControl {
register: rd,
write,
},
inputs,
outputs,
});
if !write {
self.write(rt, Expr::reg(output.index, 64));
}
}
Op::FloatLoad { double } => {
let value = Expr::Load {
addr: Box::new(self.address(rs, imm)),
width: if double { 8 } else { 4 },
signed: false,
};
self.write_float(ft, precision(double), value);
}
Op::FloatStore { double } => {
self.out.stmts.push(Stmt::Store {
addr: self.address(rs, imm),
value: read_float(ft, precision(double)),
width: if double { 8 } else { 4 },
at: None,
});
}
Op::FloatLoadIndexed { double } => {
let addr = low(Expr::bin(BinOp::Add, self.read(rs), self.read(rt)));
let value = Expr::Load {
addr: Box::new(addr),
width: if double { 8 } else { 4 },
signed: false,
};
self.write_float(fd, precision(double), value);
}
Op::FloatStoreIndexed { double } => {
let addr = low(Expr::bin(BinOp::Add, self.read(rs), self.read(rt)));
self.out.stmts.push(Stmt::Store {
addr,
value: read_float(fs, precision(double)),
width: if double { 8 } else { 4 },
at: None,
});
}
_ => {}
}
}
fn held(
&mut self,
operands: [(u8, Expr); 2],
slot_instruction: Option<&Instruction>,
) -> [Expr; 2] {
let written = slot_instruction.map(written_register);
let mut index = 0;
operands.map(|(register, value)| {
let place = HELD[index];
index += 1;
if register != 0 && written == Some(Some(register)) {
self.assign_slot(place, low(value));
Expr::reg(place, 32)
} else {
value
}
})
}
fn delay_slot(&mut self, step: &Step, pc: u64) {
if let Some(slot_instruction) = &step.slot {
self.plain(slot_instruction, pc.wrapping_add(4), false);
}
}
fn tail_call(&mut self, through: Expr) {
self.out.stmts.push(super::call_through_as(
CallKind::Tail,
self.image,
through,
Convention::O32,
));
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 32),
at: None,
});
}
fn branch(&mut self, step: &Step, pc: u64) -> bool {
let instruction = &step.instruction;
let Op::Branch { test, likely, link } = instruction.op else {
unreachable!("a branch")
};
let Instruction { rs, rt, .. } = *instruction;
let Some(target) = text::target(instruction, pc) else {
return true;
};
let (cond, rhs) = match test {
Branch::Equal => (Cond::Eq, self.read(rt)),
Branch::NotEqual => (Cond::Ne, self.read(rt)),
Branch::LessEqualZero => (Cond::Le, Expr::constant(0)),
Branch::GreaterZero => (Cond::Gt, Expr::constant(0)),
Branch::LessZero => (Cond::Lt, Expr::constant(0)),
Branch::GreaterEqualZero => (Cond::Ge, Expr::constant(0)),
};
let compared = match test {
Branch::Equal | Branch::NotEqual => rt,
_ => 0,
};
let always =
matches!(test, Branch::Equal | Branch::GreaterEqualZero) && rs == 0 && compared == 0;
if link {
self.write(31, Expr::constant(pc.wrapping_add(8)));
}
if likely {
self.out.stmts.push(Stmt::Brif {
cond: cond.invert(),
lhs: self.read(rs),
rhs,
target: pc.wrapping_add(8),
at: None,
});
return true;
}
let [lhs, rhs] = self.held([(rs, self.read(rs)), (compared, rhs)], step.slot.as_ref());
self.delay_slot(step, pc);
if always && link {
self.call(Some(target), None);
return false;
}
self.out.stmts.push(if always {
Stmt::Br {
target: Some(target),
at: None,
}
} else {
Stmt::Brif {
cond,
lhs,
rhs,
target,
at: None,
}
});
true
}
fn float_branch(&mut self, step: &Step, pc: u64) {
let Op::FloatBranch { set, likely, flag } = step.instruction.op else {
unreachable!("a float branch")
};
let Some(target) = text::target(&step.instruction, pc) else {
return;
};
if likely {
self.out.stmts.push(Stmt::Brif {
cond: if set { Cond::Eq } else { Cond::Ne },
lhs: Self::flag(flag),
rhs: Expr::constant(0),
target: pc.wrapping_add(8),
at: None,
});
return;
}
let compares = step
.slot
.as_ref()
.is_some_and(|slot| matches!(slot.op, Op::FloatCompare { .. }));
let lhs = if compares {
self.assign_slot(HELD[0], Self::flag(flag));
Expr::reg(HELD[0], 64)
} else {
Self::flag(flag)
};
self.delay_slot(step, pc);
self.out.stmts.push(Stmt::Brif {
cond: if set { Cond::Ne } else { Cond::Eq },
lhs,
rhs: Expr::constant(0),
target,
at: None,
});
}
fn jump(&mut self, step: &Step, pc: u64, link: bool) -> bool {
let target = text::target(&step.instruction, pc);
if link {
self.write(31, Expr::constant(pc.wrapping_add(8)));
}
self.delay_slot(step, pc);
let outside = self.image.outside_calls.get(&pc).map(|slot| Expr::Load {
addr: Box::new(Expr::constant(*slot)),
width: 4,
signed: false,
});
match (link, outside) {
(true, Some(through)) => {
self.call(None, Some(through));
false
}
(true, None) => {
self.call(target, None);
false
}
(false, Some(through)) => {
self.tail_call(through);
true
}
(false, None) => {
self.out.stmts.push(Stmt::Br { target, at: None });
true
}
}
}
fn jump_register(&mut self, step: &Step, pc: u64, link: bool) -> bool {
let Instruction { rs, rd, .. } = step.instruction;
let returns = !link && slot(rs) == Some(RA);
let through = self.read(rs);
let [through, _] = self.held([(rs, through), (0, Expr::constant(0))], step.slot.as_ref());
if link {
self.write(rd, Expr::constant(pc.wrapping_add(8)));
}
self.delay_slot(step, pc);
if returns {
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 32),
at: None,
});
true
} else if link {
self.call(None, Some(through));
false
} else if rs == 25 {
self.tail_call(through);
true
} else {
self.out.stmts.push(Stmt::BrIndirect {
target: through,
at: None,
});
true
}
}
fn step(&mut self, step: &Step, pc: u64) -> bool {
self.shared_pairs = step.shared_pairs;
let ended = match step.instruction.op {
Op::Branch { .. } => self.branch(step, pc),
Op::FloatBranch { .. } => {
self.float_branch(step, pc);
true
}
Op::Jump { link } => self.jump(step, pc, link),
Op::JumpRegister { link } => self.jump_register(step, pc, link),
Op::Break => {
self.out.stmts.push(Stmt::Trap { at: None });
true
}
_ => {
self.plain(&step.instruction, pc, step.unaligned);
false
}
};
match step.then {
Some(target) if !ended => {
self.out.stmts.push(Stmt::Br {
target: Some(target),
at: None,
});
true
}
_ => ended,
}
}
}
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) = step.then {
return Some(target);
}
match step.instruction.op {
Op::Branch { likely: true, .. } | Op::FloatBranch { likely: true, .. } => {
Some(pc.wrapping_add(8))
}
Op::Branch { link: false, .. } | Op::FloatBranch { .. } | Op::Jump { link: false } => {
text::target(&step.instruction, pc)
}
_ => None,
}
}
fn step(&mut self, instruction: &Step, pc: u64) -> bool {
Lifter::step(self, instruction, pc)
}
fn rules(&self) -> Rules {
let mut at_entry = Known::new();
if let Some(t9) = slot(25) {
at_entry.insert(t9, self.start & WORD);
}
if let Some(address) = self.image.global_pointer {
at_entry.insert(GP, address);
}
Rules {
at_entry,
fixed: &[GP],
frame: &[SP, FP],
saved: &[16, 17, 18, 19, 20, 21, 22, 23, FP],
folds: true,
calls_through_registers: true,
}
}
fn enter_block(&mut self) {
self.forget();
}
}
#[cfg(test)]
mod tests;