use js_compile::{OpFormat, Opcode};
#[derive(Clone, Copy, Debug)]
pub struct Insn {
pub op: Opcode,
pub fused: Fused,
pub a: u32,
pub b: u32,
pub imm: u32,
pub offset: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fused {
None,
AddImmLoc,
AddAtomLoc,
AddLocLoc,
AddArgLoc,
PostIncLoc,
StoreImm,
LtLocArgJump,
LtLocImmJump,
}
impl Insn {
pub fn width(&self) -> usize {
match self.fused {
Fused::None => 1,
Fused::AddImmLoc
| Fused::AddAtomLoc
| Fused::AddLocLoc
| Fused::AddArgLoc
| Fused::PostIncLoc
| Fused::LtLocArgJump
| Fused::LtLocImmJump => 4,
Fused::StoreImm => 2,
}
}
}
const UNMAPPED: u32 = u32::MAX;
pub fn predecode(code: &[u8]) -> Vec<Insn> {
let mut insns = Vec::with_capacity(code.len() / 2 + 1);
let mut offsets = Vec::with_capacity(code.len() + 1);
let mut pc = 0;
while pc < code.len() {
let Some((op, a, b, next)) = decode(code, pc) else {
break;
};
offsets.push(pc);
insns.push(Insn {
op,
fused: Fused::None,
imm: 0,
a,
b,
offset: pc as u32,
});
pc = next;
}
offsets.push(code.len());
let mut index_of = vec![UNMAPPED; code.len() + 1];
for (index, offset) in offsets.iter().enumerate() {
index_of[*offset] = index as u32;
}
for insn in &mut insns {
if let Some(value) = implicit_operand(insn.op) {
insn.a = value;
}
}
for insn in &mut insns {
let format = insn.op.info().format;
if !format.is_label() {
continue;
}
let target = match format {
OpFormat::AtomLabelU8 | OpFormat::AtomLabelU16 => &mut insn.b,
_ => &mut insn.a,
};
*target = resolve(&index_of, *target);
}
fuse(&mut insns);
insns
}
fn implicit_operand(op: Opcode) -> Option<u32> {
use Opcode::*;
Some(match op {
GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
| SetVarRef0 => 0,
GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
| SetVarRef1 => 1,
GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
| SetVarRef2 => 2,
GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
| SetVarRef3 => 3,
PushMinus1 => u32::MAX,
Push0 => 0,
Push1 => 1,
Push2 => 2,
Push3 => 3,
Push4 => 4,
Push5 => 5,
Push6 => 6,
Push7 => 7,
_ => return None,
})
}
fn pushed_int(op: Opcode, a: u32) -> Option<i32> {
use Opcode::*;
Some(match op {
PushMinus1 => -1,
Push0 => 0,
Push1 => 1,
Push2 => 2,
Push3 => 3,
Push4 => 4,
Push5 => 5,
Push6 => 6,
Push7 => 7,
PushI8 | PushI16 | PushI32 => a as i32,
_ => return None,
})
}
fn load_slot(op: Opcode, a: u32) -> Option<u32> {
use Opcode::*;
match op {
GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => Some(a),
_ => None,
}
}
fn store_slot(op: Opcode, a: u32) -> Option<u32> {
use Opcode::*;
match op {
PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => Some(a),
_ => None,
}
}
fn fuse(insns: &mut [Insn]) {
let mut index = 0;
while index < insns.len() {
let width = fused_at(&insns[index..]);
match width {
Some((fused, a, b, imm, span)) => {
let insn = &mut insns[index];
insn.fused = fused;
insn.a = a;
insn.b = b;
insn.imm = imm;
index += span;
}
None => index += 1,
}
}
}
fn arg_slot(op: Opcode, a: u32) -> Option<u32> {
use Opcode::*;
match op {
GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => Some(a),
_ => None,
}
}
fn false_branch_target(insn: &Insn) -> Option<u32> {
use Opcode::*;
match insn.op {
IfFalse | IfFalse8 => Some(insn.a),
_ => None,
}
}
fn fused_at(rest: &[Insn]) -> Option<(Fused, u32, u32, u32, usize)> {
if let Some(value) = pushed_int(rest[0].op, rest[0].a)
&& let Some(store) = rest.get(1)
&& let Some(slot) = store_slot(store.op, store.a)
{
return Some((Fused::StoreImm, slot, value as u32, 0, 2));
}
let slot = load_slot(rest[0].op, rest[0].a)?;
if let Some(value) = rest.get(1).and_then(|insn| pushed_int(insn.op, insn.a))
&& let (Some(add), Some(store)) = (rest.get(2), rest.get(3))
&& add.op == Opcode::Add
&& store_slot(store.op, store.a) == Some(slot)
{
return Some((Fused::AddImmLoc, slot, value as u32, 0, 4));
}
if let (Some(pushed), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
&& pushed.op == Opcode::PushAtomValue
&& add.op == Opcode::Add
&& store_slot(store.op, store.a) == Some(slot)
{
return Some((Fused::AddAtomLoc, slot, pushed.a, 0, 4));
}
if let (Some(second), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
&& let Some(source) = load_slot(second.op, second.a)
&& add.op == Opcode::Add
&& store_slot(store.op, store.a) == Some(slot)
&& slot < 0x10000
&& source < 0x10000
{
return Some((Fused::AddLocLoc, (slot << 16) | source, 0, 0, 4));
}
if let (Some(second), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
&& let Some(source) = arg_slot(second.op, second.a)
&& add.op == Opcode::Add
&& store_slot(store.op, store.a) == Some(slot)
&& slot < 0x10000
&& source < 0x10000
{
return Some((Fused::AddArgLoc, (slot << 16) | source, 0, 0, 4));
}
if let (Some(second), Some(cmp), Some(branch)) = (rest.get(1), rest.get(2), rest.get(3))
&& let Some(arg) = arg_slot(second.op, second.a)
&& cmp.op == Opcode::Lt
&& let Some(target) = false_branch_target(branch)
&& slot < 0x10000
&& arg < 0x10000
{
return Some((Fused::LtLocArgJump, (slot << 16) | arg, target, 0, 4));
}
if let (Some(bound), Some(cmp), Some(branch)) = (rest.get(1), rest.get(2), rest.get(3))
&& let Some(imm) = pushed_int(bound.op, bound.a)
&& cmp.op == Opcode::Lt
&& let Some(target) = false_branch_target(branch)
&& slot < 0x10000
{
return Some((Fused::LtLocImmJump, slot, target, imm as u32, 4));
}
if let (Some(inc), Some(store), Some(drop)) = (rest.get(1), rest.get(2), rest.get(3))
&& inc.op == Opcode::PostInc
&& store_slot(store.op, store.a) == Some(slot)
&& drop.op == Opcode::Drop
{
return Some((Fused::PostIncLoc, slot, 0, 0, 4));
}
None
}
fn resolve(index_of: &[u32], offset: u32) -> u32 {
match index_of.get(offset as usize) {
Some(&index) if index != UNMAPPED => index,
_ => index_of.last().copied().unwrap_or(0),
}
}
fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
let op = Opcode::from_u8(*code.get(pc)?)?;
let info = op.info();
let base = pc + 1;
let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
let read_u16 = |offset: usize| -> u32 {
let mut value = 0u32;
for index in 0..2 {
value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
}
value
};
let read_u32 = |offset: usize| -> u32 {
let mut value = 0u32;
for index in 0..4 {
value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
}
value
};
let jump = |offset: usize, width: usize| -> u32 {
let raw = match width {
1 => read_u8(offset) as u8 as i8 as i64,
2 => read_u16(offset) as u16 as i16 as i64,
_ => read_u32(offset) as i32 as i64,
};
(base as i64 + raw) as u32
};
let (a, b) = match info.format {
OpFormat::None
| OpFormat::NoneInt
| OpFormat::NoneLoc
| OpFormat::NoneArg
| OpFormat::NoneVarRef
| OpFormat::Npopx => (0, 0),
OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
OpFormat::Label8 => (jump(0, 1), 0),
OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
(read_u16(0), 0)
}
OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
OpFormat::Label16 => (jump(0, 2), 0),
OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
OpFormat::I32 | OpFormat::Label => (
if info.format == OpFormat::Label {
jump(0, 4)
} else {
read_u32(0) as i32 as u32
},
0,
),
OpFormat::AtomU8 => (read_u32(0), read_u8(4)),
OpFormat::AtomU16 | OpFormat::LabelU16 => (read_u32(0), read_u16(4)),
OpFormat::AtomLabelU8 => (read_u32(0), jump(4, 4)),
OpFormat::AtomLabelU16 => (read_u32(0), jump(4, 4)),
};
Some((op, a, b, pc + info.size as usize))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_jump_operand_becomes_an_index() {
let goto8 = Opcode::Goto8 as u8;
let push1 = Opcode::Push1 as u8;
let code = [goto8, 1, push1];
let insns = predecode(&code);
assert_eq!(insns.len(), 2);
assert_eq!(insns[0].op, Opcode::Goto8);
assert_eq!(insns[0].a, 1, "the jump target is the second instruction");
assert_eq!(insns[0].offset, 0);
assert_eq!(insns[1].op, Opcode::Push1);
assert_eq!(insns[1].offset, 2);
}
#[test]
fn a_jump_past_the_end_lands_on_the_end() {
let code = [Opcode::Goto8 as u8, 1];
let insns = predecode(&code);
assert_eq!(insns.len(), 1);
assert_eq!(insns[0].a as usize, insns.len());
}
#[test]
fn a_backward_jump_resolves() {
let code = [Opcode::Push1 as u8, Opcode::Goto8 as u8, 0xFE];
let insns = predecode(&code);
assert_eq!(insns.len(), 2);
assert_eq!(insns[1].op, Opcode::Goto8);
assert_eq!(insns[1].a, 0);
}
#[test]
fn a_plain_operand_is_untouched() {
let code = [Opcode::GetLoc8 as u8, 7, Opcode::Push1 as u8];
let insns = predecode(&code);
assert_eq!(insns[0].a, 7);
}
#[test]
fn an_unknown_opcode_ends_the_array() {
let code = [Opcode::Push1 as u8, 0xFF, Opcode::Push1 as u8];
let insns = predecode(&code);
assert_eq!(insns.len(), 1);
assert_eq!(insns[0].op, Opcode::Push1);
}
fn compiled(source: &str) -> Vec<Insn> {
let program = js_parse::parse_script(source).expect("parses");
let code = js_compile::compile_script(&program).expect("compiles");
let js_compile::bytecode::Constant::Function(first) = &code.cpool[0] else {
panic!("the script's first constant is the function");
};
predecode(&first.code)
}
#[test]
fn a_counting_loop_fuses_its_header_body_and_increment() {
let insns =
compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
let fused: Vec<Fused> = insns
.iter()
.filter(|insn| insn.fused != Fused::None)
.map(|insn| insn.fused)
.collect();
assert_eq!(
fused,
vec![
Fused::StoreImm,
Fused::StoreImm,
Fused::LtLocArgJump,
Fused::AddImmLoc,
Fused::PostIncLoc
],
"header, body and increment each collapse into one dispatch"
);
}
#[test]
fn a_loop_header_with_a_literal_bound_fuses() {
let insns = compiled(
"function f(){ var t = 0; for (var i = 0; i < 60000000; i++) t += 1; return t }",
);
let header = insns
.iter()
.find(|insn| insn.fused == Fused::LtLocImmJump)
.expect("`get_loc; push_i32; lt; if_false` fuses with a literal bound");
assert_eq!(header.a, 1, "the counter's slot");
assert_eq!(header.imm, 60_000_000, "the bound, kept in `imm`");
assert_eq!(header.width(), 4, "four dispatches become one");
}
#[test]
fn a_loop_header_with_a_small_literal_bound_fuses() {
let insns =
compiled("function f(){ var t = 0; for (var i = 0; i < 7; i++) t += 1; return t }");
let header = insns
.iter()
.find(|insn| insn.fused == Fused::LtLocImmJump)
.expect("`push_7` counts as an integer literal");
assert_eq!(header.imm, 7);
}
#[test]
fn a_store_keeps_its_slot_and_value() {
let insns = predecode(&[
Opcode::Push7 as u8,
Opcode::PutLoc0 as u8,
Opcode::Push1 as u8,
]);
let store = insns
.iter()
.find(|insn| insn.fused == Fused::StoreImm)
.expect("`push_7; put_loc0` fuses");
assert_eq!(insns.len(), 3, "the third instruction keeps its own record");
assert_eq!(store.a, 0, "slot of the local");
assert_eq!(store.b, 7, "the pushed integer");
assert_eq!(store.width(), 2);
}
#[test]
fn an_append_into_a_local_fuses() {
let atom = compiled(
r#"function f(n){ var t = ""; for (var i = 0; i < n; i++) t += "abc"; return t.length }"#,
);
let fused = atom
.iter()
.find(|insn| insn.fused == Fused::AddAtomLoc)
.expect("`get_loc; push_atom_value; add; put_loc` fuses");
assert_eq!(fused.a, 0, "the slot being appended to");
assert_eq!(fused.width(), 4);
let local = compiled(
"function f(n){ var t = '', c = 'x'; for (var i = 0; i < n; i++) t += c; return t.length }",
);
let fused = local
.iter()
.find(|insn| insn.fused == Fused::AddLocLoc)
.expect("`get_loc; get_loc; add; put_loc` fuses");
assert_eq!(fused.a >> 16, 0, "the slot being appended to");
let arg = compiled(
"function f(n, a){ var t = ''; for (var i = 0; i < n; i++) t += a; return t.length }",
);
let fused = arg
.iter()
.find(|insn| insn.fused == Fused::AddArgLoc)
.expect("`get_loc; get_arg; add; put_loc` fuses");
assert_eq!(fused.a >> 16, 0, "the slot being appended to");
assert_eq!(fused.a & 0xFFFF, 1, "`a` is the second argument");
}
#[test]
fn a_push_followed_by_a_read_does_not_fuse() {
let insns = compiled("function f(p, str){ return str.slice(0, p) }");
for insn in &insns {
assert_ne!(
insn.fused,
Fused::StoreImm,
"`push; get_loc` must not become a store"
);
}
assert!(
insns.iter().any(|insn| insn.op == Opcode::GetArg0),
"the read of `p` is still its own instruction"
);
}
#[test]
fn an_add_needs_the_same_slot_on_both_ends() {
let same = compiled("function f(n){ var t = 0; t += n; return t }");
assert!(
same.iter().all(|insn| insn.fused != Fused::AddImmLoc),
"`t += n` pushes an argument, not an immediate"
);
let different = compiled("function f(){ var t = 0, k = 0; t = k + 1; return t }");
assert!(
different.iter().all(|insn| insn.fused != Fused::AddImmLoc),
"`t = k + 1` reads `k` and writes `t`"
);
}
#[test]
fn a_loop_header_carries_a_resolved_target() {
let insns =
compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
let header = insns
.iter()
.find(|insn| insn.fused == Fused::LtLocArgJump)
.expect("the loop header fuses");
let local = header.a >> 16;
let arg = header.a & 0xFFFF;
assert_eq!(local, 1, "`i` is local slot 1");
assert_eq!(arg, 0, "`n` is argument slot 0");
let target = header.b as usize;
assert!(
target < insns.len(),
"the target is an index into this array"
);
assert_eq!(
insns[target].op,
Opcode::GetLoc0,
"the target is `return t`, the first instruction after the loop"
);
}
#[test]
fn fusion_keeps_offsets_and_count() {
let unfused: Vec<u32> =
compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }")
.iter()
.map(|insn| insn.offset)
.collect();
let insns =
compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
assert_eq!(
insns.iter().map(|insn| insn.offset).collect::<Vec<_>>(),
unfused,
"fusion must not renumber or drop records"
);
for pair in insns.windows(2) {
assert!(
pair[0].offset < pair[1].offset,
"offsets stay in byte order"
);
}
for (index, insn) in insns.iter().enumerate() {
assert!(
index + insn.width() <= insns.len(),
"a fused record's span stays inside the array"
);
}
}
#[test]
fn offsets_walk_the_encodings() {
let code = [Opcode::Push1 as u8, Opcode::Push2 as u8, Opcode::Drop as u8];
let insns = predecode(&code);
assert_eq!(
insns.iter().map(|insn| insn.offset).collect::<Vec<_>>(),
vec![0, 1, 2]
);
}
}