Skip to main content

quickjs/
insn.rs

1//! The instruction stream the interpreter actually runs.
2//!
3//! Bytecode is a compact variable-length encoding, and decoding it costs a table
4//! lookup, a width switch and a bounds check **per instruction**. At ten nanoseconds
5//! per instruction that was a visible share of the budget, and it is work that never
6//! changes its answer: a function's bytecode is immutable once compiled.
7//!
8//! So it is decoded once, into a fixed-width record. [`Insn`] is twenty bytes —
9//! opcode, three operands, and the byte offset it came from — which is small enough
10//! that a loop's whole body sits in a couple of cache lines, and it turns the
11//! interpreter's `pc` into an index. The third operand exists for exactly one fusion
12//! ([`Fused::LtLocImmJump`] needs a slot, a bound *and* a target); it is zero
13//! everywhere else. Everything the old `decode` computed per
14//! instruction is computed here instead:
15//!
16//! * operands are unpacked from their 1/2/4-byte big-endian fields;
17//! * jump operands are resolved from the encoded relative offset to an **index** into
18//!   this same array, so `goto` becomes an assignment rather than arithmetic;
19//! * the byte offset is kept, because that is what a stack trace reports and what the
20//!   line table is keyed by.
21//!
22//! This is not a peephole pass and not a superinstruction compiler: the instruction
23//! sequence is exactly the reference's, one record per bytecode instruction, and the
24//! 422-case disassembly diff still compares that bytecode byte for byte.
25
26use js_compile::{OpFormat, Opcode};
27
28/// One decoded instruction.
29///
30/// `a` and `b` are the two operands: a slot index, a constant-pool index, an atom, an
31/// immediate — or, for a jump, the index of the target instruction.
32#[derive(Clone, Copy, Debug)]
33pub struct Insn {
34    /// The opcode.
35    pub op: Opcode,
36    /// A fused form of this instruction **and the next few**, when they match a pattern
37    /// worth collapsing. [`Fused::None`] means "run `op` as it is".
38    ///
39    /// The fused form is a shorthand for a sequence the bytecode still contains: the
40    /// dispatcher runs one record and skips the rest, so the bytecode, the disassembly
41    /// and every jump target are unchanged. This is the one optimisation that reduces
42    /// the *number* of dispatches rather than their cost, which is why it is worth the
43    /// extra pass.
44    pub fused: Fused,
45    /// First operand, or a jump target as an instruction index.
46    pub a: u32,
47    /// Second operand.
48    pub b: u32,
49    /// Third operand, used only by fusions that need a slot, an immediate **and** a jump
50    /// target at once (currently [`Fused::LtLocImmJump`]).
51    pub imm: u32,
52    /// Where this instruction started in the bytecode, for stack traces and the line
53    /// table. (`pc` is an index, and no longer answers that question.)
54    pub offset: u32,
55}
56
57/// A fused instruction, and how many records it stands for.
58///
59/// Only shapes that cannot throw are fused, because `at` — the offset a stack trace
60/// reports — names the *first* instruction of the group. A fused `x += 1` that raised
61/// would blame the wrong column; a fused `x += 1` on integers cannot raise.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum Fused {
64    /// Not fused: run `Insn::op`.
65    None,
66    /// `x += k` for an integer `k`: `get_loc x; push k; add; put_loc x`.
67    ///
68    /// Four dispatches become one, and this is the most common four-instruction group
69    /// in JavaScript — `i += 1`, `total += n`, every accumulator in every loop.
70    AddImmLoc,
71    /// `x += "literal"`: `get_loc x; push_atom_value atom; add; put_loc x`.
72    ///
73    /// The same group with a string constant instead of an integer, and it exists for one
74    /// reason beyond dispatch: the reference's `OP_add_loc` hands the *variable's own*
75    /// string to `JS_ConcatStringInPlace`, so `text += "abc"` in a loop grows one buffer
76    /// instead of building a new string per iteration. Reproducing it needs the group
77    /// fused, because only then is the variable's one handle the only handle — through
78    /// `get_loc` alone it has already been cloned once.
79    AddAtomLoc,
80    /// `x += y`: `get_loc x; get_loc y; add; put_loc x`.
81    ///
82    /// The same, with the other operand also a local. `a` is `(x << 16) | y`, like
83    /// [`Fused::LtLocArgJump`].
84    AddLocLoc,
85    /// `x += y` where `y` is an argument: `get_loc x; get_arg y; add; put_loc x`.
86    ///
87    /// Separate from [`Fused::AddLocLoc`] rather than a flag bit, because the two read
88    /// different arrays and a bit would make every reader of the operand check it.
89    AddArgLoc,
90    /// `x++` and the value is dropped: `get_loc x; post_inc; put_loc x; drop`.
91    PostIncLoc,
92    /// `x = k`: `push k; put_loc x`.
93    StoreImm,
94    /// `if (!(x < arg)) goto target` — a loop's header: `get_loc x; get_arg arg; lt;
95    /// if_false target`.
96    ///
97    /// The condition is the one instruction group that runs on *every* iteration of
98    /// every loop, so collapsing it is worth the packed operands: `a` is
99    /// `(x << 16) | arg`, `b` is the target instruction index.
100    LtLocArgJump,
101    /// `if (!(x < k)) goto target` — a loop header whose bound is a **literal**:
102    /// `get_loc x; push k; lt; if_false target`.
103    ///
104    /// [`Fused::LtLocArgJump`] covers `for (var i = 0; i < n; i++)`, where the bound is a
105    /// parameter. This covers `for (var i = 0; i < 1000; i++)`, where it is an immediate —
106    /// measured as a 40% slowdown against the reference when it did not fuse at all, since
107    /// the header is four dispatches on every iteration. `a` is the slot, `b` is the
108    /// target instruction index, `imm` is the bound.
109    LtLocImmJump,
110}
111
112impl Insn {
113    /// How many bytecode instructions this record replaces.
114    pub fn width(&self) -> usize {
115        match self.fused {
116            Fused::None => 1,
117            Fused::AddImmLoc
118            | Fused::AddAtomLoc
119            | Fused::AddLocLoc
120            | Fused::AddArgLoc
121            | Fused::PostIncLoc
122            | Fused::LtLocArgJump
123            | Fused::LtLocImmJump => 4,
124            Fused::StoreImm => 2,
125        }
126    }
127}
128
129/// Sentinal for "no instruction starts at this byte offset".
130const UNMAPPED: u32 = u32::MAX;
131
132/// Decode `code` into an instruction array.
133///
134/// A byte that is not a valid opcode stops the walk, and the instructions up to that
135/// point are kept: running off the end of a function is a normal return, so the
136/// truncation can never be reached by a well-formed program and it keeps a corrupted
137/// blob from being a panic in the decoder.
138pub fn predecode(code: &[u8]) -> Vec<Insn> {
139    let mut insns = Vec::with_capacity(code.len() / 2 + 1);
140    let mut offsets = Vec::with_capacity(code.len() + 1);
141    let mut pc = 0;
142    while pc < code.len() {
143        let Some((op, a, b, next)) = decode(code, pc) else {
144            break;
145        };
146        offsets.push(pc);
147        insns.push(Insn {
148            op,
149            fused: Fused::None,
150            imm: 0,
151            a,
152            b,
153            offset: pc as u32,
154        });
155        pc = next;
156    }
157    // A label may point one past the last instruction — `break` at the end of a block
158    // lands there — so the table has an entry for the end of the code, answering
159    // `insns.len()`, which the interpreter reads as "past the end, return undefined".
160    offsets.push(code.len());
161
162    // Byte offset → instruction index, for resolving jumps.
163    let mut index_of = vec![UNMAPPED; code.len() + 1];
164    for (index, offset) in offsets.iter().enumerate() {
165        index_of[*offset] = index as u32;
166    }
167
168    // Implicit operands, filled in so that a handler is a plain operand read rather than
169    // a second `match` on the opcode. `get_loc0` means slot 0 whatever its operand byte
170    // says, and `push_3` means the integer 3.
171    for insn in &mut insns {
172        if let Some(value) = implicit_operand(insn.op) {
173            insn.a = value;
174        }
175    }
176
177    for insn in &mut insns {
178        let format = insn.op.info().format;
179        if !format.is_label() {
180            continue;
181        }
182        // Which operand holds the target depends on the encoding: the single-label
183        // formats carry it in `a`, and the two that pair an atom or a value with a
184        // label carry it after it.
185        let target = match format {
186            OpFormat::AtomLabelU8 | OpFormat::AtomLabelU16 => &mut insn.b,
187            _ => &mut insn.a,
188        };
189        *target = resolve(&index_of, *target);
190    }
191
192    // Fusion runs **last**, because it reads resolved jump targets: `if_false` holds a
193    // byte offset until the loop above turns it into an index, and a fusion that captured
194    // the offset would jump to an instruction number equal to a byte count. That is
195    // exactly the bug this ordering fixes — it made `dispatch:arith` answer `NaN`.
196    fuse(&mut insns);
197    insns
198}
199
200/// The operand an opcode encodes in its own number, or `None` if it has a real one.
201///
202/// `get_loc0`…`get_loc3`, `get_arg0`…`3`, `put_*`, `set_*`, `push_0`…`push_7` and
203/// `push_minus1` all carry their operand in the opcode. Writing it into `a` at decode
204/// time removes a `match` from the hot path of every local-variable access.
205fn implicit_operand(op: Opcode) -> Option<u32> {
206    use Opcode::*;
207    Some(match op {
208        GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
209        | SetVarRef0 => 0,
210        GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
211        | SetVarRef1 => 1,
212        GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
213        | SetVarRef2 => 2,
214        GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
215        | SetVarRef3 => 3,
216        PushMinus1 => u32::MAX,
217        Push0 => 0,
218        Push1 => 1,
219        Push2 => 2,
220        Push3 => 3,
221        Push4 => 4,
222        Push5 => 5,
223        Push6 => 6,
224        Push7 => 7,
225        _ => return None,
226    })
227}
228
229/// The integer a constant-pushing opcode pushes, for the fusions below.
230fn pushed_int(op: Opcode, a: u32) -> Option<i32> {
231    use Opcode::*;
232    Some(match op {
233        PushMinus1 => -1,
234        Push0 => 0,
235        Push1 => 1,
236        Push2 => 2,
237        Push3 => 3,
238        Push4 => 4,
239        Push5 => 5,
240        Push6 => 6,
241        Push7 => 7,
242        PushI8 | PushI16 | PushI32 => a as i32,
243        _ => return None,
244    })
245}
246
247/// The local slot an opcode **reads**, when it is one of the `get_loc` family.
248fn load_slot(op: Opcode, a: u32) -> Option<u32> {
249    use Opcode::*;
250    match op {
251        GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => Some(a),
252        _ => None,
253    }
254}
255
256/// The local slot an opcode **writes**, when it is one of the `put_loc` family.
257///
258/// Kept separate from [`load_slot`], and that separation is not cosmetic. A single
259/// "local slot" helper accepted `get_loc` where the pattern meant `put_loc`, so
260/// `push_0; get_loc0` fused into "store 0 into slot 0": it dropped the pushed argument
261/// *and* overwrote the local. `str.slice(0, p)` then called `p`, which is a **wrong
262/// answer** rather than a crash — and the compiler, the unit tests and the bytecode diff
263/// were all blind to it. Only the differential suite against the reference caught it.
264fn store_slot(op: Opcode, a: u32) -> Option<u32> {
265    use Opcode::*;
266    match op {
267        PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => Some(a),
268        _ => None,
269    }
270}
271
272/// Collapse the hot instruction groups.
273///
274/// Each pattern is matched over consecutive records, the *same* slot on both ends, and
275/// only where nothing in the group can throw. The jump-target resolution above is done
276/// before this runs, and the jump-target *resolution table* is untouched: a fused
277/// record still starts at its first instruction's offset, so a jump into the middle of
278/// a group is impossible — the compiler never emits one, and if it did, the record is
279/// consumed from its start either way.
280fn fuse(insns: &mut [Insn]) {
281    let mut index = 0;
282    while index < insns.len() {
283        let width = fused_at(&insns[index..]);
284        match width {
285            Some((fused, a, b, imm, span)) => {
286                let insn = &mut insns[index];
287                insn.fused = fused;
288                insn.a = a;
289                insn.b = b;
290                insn.imm = imm;
291                index += span;
292            }
293            None => index += 1,
294        }
295    }
296}
297
298/// The argument slot an opcode reads, when it is one of the `get_arg` family.
299fn arg_slot(op: Opcode, a: u32) -> Option<u32> {
300    use Opcode::*;
301    match op {
302        GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => Some(a),
303        _ => None,
304    }
305}
306
307/// The target of an `if_false`, when that is what `insn` is.
308///
309/// Its operand is already an instruction index — the label-resolution pass above ran
310/// first — so this is a read, not a conversion.
311fn false_branch_target(insn: &Insn) -> Option<u32> {
312    use Opcode::*;
313    match insn.op {
314        IfFalse | IfFalse8 => Some(insn.a),
315        _ => None,
316    }
317}
318
319/// The fusion starting at `rest[0]`, as `(kind, operand a, operand b, span)`.
320fn fused_at(rest: &[Insn]) -> Option<(Fused, u32, u32, u32, usize)> {
321    // `x = k`: `push k; put_loc x`.
322    if let Some(value) = pushed_int(rest[0].op, rest[0].a)
323        && let Some(store) = rest.get(1)
324        && let Some(slot) = store_slot(store.op, store.a)
325    {
326        return Some((Fused::StoreImm, slot, value as u32, 0, 2));
327    }
328    // The rest start from a read of the same local they write.
329    let slot = load_slot(rest[0].op, rest[0].a)?;
330    // `x += k`: `get_loc x; push k; add; put_loc x`.
331    if let Some(value) = rest.get(1).and_then(|insn| pushed_int(insn.op, insn.a))
332        && let (Some(add), Some(store)) = (rest.get(2), rest.get(3))
333        && add.op == Opcode::Add
334        && store_slot(store.op, store.a) == Some(slot)
335    {
336        return Some((Fused::AddImmLoc, slot, value as u32, 0, 4));
337    }
338    // `x += "literal"`: `get_loc x; push_atom_value atom; add; put_loc x`.
339    if let (Some(pushed), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
340        && pushed.op == Opcode::PushAtomValue
341        && add.op == Opcode::Add
342        && store_slot(store.op, store.a) == Some(slot)
343    {
344        return Some((Fused::AddAtomLoc, slot, pushed.a, 0, 4));
345    }
346    // `x += y`: `get_loc x; get_loc y; add; put_loc x`.
347    if let (Some(second), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
348        && let Some(source) = load_slot(second.op, second.a)
349        && add.op == Opcode::Add
350        && store_slot(store.op, store.a) == Some(slot)
351        && slot < 0x10000
352        && source < 0x10000
353    {
354        return Some((Fused::AddLocLoc, (slot << 16) | source, 0, 0, 4));
355    }
356    // `x += y` where `y` is an argument: `get_loc x; get_arg y; add; put_loc x`.
357    if let (Some(second), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
358        && let Some(source) = arg_slot(second.op, second.a)
359        && add.op == Opcode::Add
360        && store_slot(store.op, store.a) == Some(slot)
361        && slot < 0x10000
362        && source < 0x10000
363    {
364        return Some((Fused::AddArgLoc, (slot << 16) | source, 0, 0, 4));
365    }
366    // A loop header: `get_loc x; get_arg arg; lt; if_false target`. Both slots have to
367    // fit in 16 bits, which the `Loc`/`Arg` encodings guarantee — and a slot beyond that
368    // simply does not fuse.
369    if let (Some(second), Some(cmp), Some(branch)) = (rest.get(1), rest.get(2), rest.get(3))
370        && let Some(arg) = arg_slot(second.op, second.a)
371        && cmp.op == Opcode::Lt
372        && let Some(target) = false_branch_target(branch)
373        && slot < 0x10000
374        && arg < 0x10000
375    {
376        return Some((Fused::LtLocArgJump, (slot << 16) | arg, target, 0, 4));
377    }
378    // A loop header whose bound is an integer literal: `get_loc x; push k; lt;
379    // if_false target`. Same shape as `LtLocArgJump`, but the second operand is a
380    // constant instead of an argument, so the bound goes in `imm` and `a` carries only
381    // the slot.
382    if let (Some(bound), Some(cmp), Some(branch)) = (rest.get(1), rest.get(2), rest.get(3))
383        && let Some(imm) = pushed_int(bound.op, bound.a)
384        && cmp.op == Opcode::Lt
385        && let Some(target) = false_branch_target(branch)
386        && slot < 0x10000
387    {
388        return Some((Fused::LtLocImmJump, slot, target, imm as u32, 4));
389    }
390    // `x++` as a statement: `get_loc x; post_inc; put_loc x; drop`.
391    if let (Some(inc), Some(store), Some(drop)) = (rest.get(1), rest.get(2), rest.get(3))
392        && inc.op == Opcode::PostInc
393        && store_slot(store.op, store.a) == Some(slot)
394        && drop.op == Opcode::Drop
395    {
396        return Some((Fused::PostIncLoc, slot, 0, 0, 4));
397    }
398    None
399}
400
401/// Map a byte offset to an instruction index.
402///
403/// An offset with no instruction at it keeps its old meaning — "past the end of the
404/// code" — as the index of the end. Anything else would be a jump into the middle of
405/// an instruction, which the compiler cannot emit; it is treated as the end so that a
406/// corrupted stream stops rather than reading nonsense, and `pc >= insns.len()` then
407/// reports a normal return.
408fn resolve(index_of: &[u32], offset: u32) -> u32 {
409    match index_of.get(offset as usize) {
410        Some(&index) if index != UNMAPPED => index,
411        // The last entry is the end-of-code marker, so this is `insns.len()`.
412        _ => index_of.last().copied().unwrap_or(0),
413    }
414}
415
416/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
417///
418/// Jump operands are resolved to absolute byte offsets here, because the encoding
419/// stores them relative to the byte after the opcode and every use site would
420/// otherwise repeat that arithmetic.
421///
422/// Only [`predecode`] calls this now; the interpreter works from [`Insn`] and never
423/// looks at the bytes.
424fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
425    let op = Opcode::from_u8(*code.get(pc)?)?;
426    let info = op.info();
427    let base = pc + 1;
428    let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
429    let read_u16 = |offset: usize| -> u32 {
430        let mut value = 0u32;
431        for index in 0..2 {
432            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
433        }
434        value
435    };
436    let read_u32 = |offset: usize| -> u32 {
437        let mut value = 0u32;
438        for index in 0..4 {
439            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
440        }
441        value
442    };
443    let jump = |offset: usize, width: usize| -> u32 {
444        let raw = match width {
445            1 => read_u8(offset) as u8 as i8 as i64,
446            2 => read_u16(offset) as u16 as i16 as i64,
447            _ => read_u32(offset) as i32 as i64,
448        };
449        (base as i64 + raw) as u32
450    };
451    let (a, b) = match info.format {
452        OpFormat::None
453        | OpFormat::NoneInt
454        | OpFormat::NoneLoc
455        | OpFormat::NoneArg
456        | OpFormat::NoneVarRef
457        | OpFormat::Npopx => (0, 0),
458        OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
459        OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
460        OpFormat::Label8 => (jump(0, 1), 0),
461        OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
462            (read_u16(0), 0)
463        }
464        OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
465        OpFormat::Label16 => (jump(0, 2), 0),
466        OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
467        OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
468        OpFormat::I32 | OpFormat::Label => (
469            if info.format == OpFormat::Label {
470                jump(0, 4)
471            } else {
472                read_u32(0) as i32 as u32
473            },
474            0,
475        ),
476        // `atom_u8` / `atom_u16` pair an atom with a small value, and the two
477        // `atom_label` formats pair an atom with a **label** — the layout is atom, then
478        // label, then the value (see the reference's `OP_FMT_atom_label_u8`). The old
479        // decoder read the label's first bytes as if they were the value, which was
480        // unobservable only because no opcode with these formats is implemented yet:
481        // they are `with_get_var` and friends, plus `scope_make_ref`.
482        OpFormat::AtomU8 => (read_u32(0), read_u8(4)),
483        OpFormat::AtomU16 | OpFormat::LabelU16 => (read_u32(0), read_u16(4)),
484        OpFormat::AtomLabelU8 => (read_u32(0), jump(4, 4)),
485        OpFormat::AtomLabelU16 => (read_u32(0), jump(4, 4)),
486    };
487    Some((op, a, b, pc + info.size as usize))
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493
494    /// A hand-assembled `goto8` over a `push_1`.
495    ///
496    /// `goto8 <label>` is two bytes; the label is relative to the byte after the
497    /// instruction. `push_1` is one byte. So jumping to the instruction after
498    /// `push_1` from offset 0 means an offset of 1.
499    #[test]
500    fn a_jump_operand_becomes_an_index() {
501        let goto8 = Opcode::Goto8 as u8;
502        let push1 = Opcode::Push1 as u8;
503        let code = [goto8, 1, push1];
504        let insns = predecode(&code);
505        assert_eq!(insns.len(), 2);
506        assert_eq!(insns[0].op, Opcode::Goto8);
507        assert_eq!(insns[0].a, 1, "the jump target is the second instruction");
508        assert_eq!(insns[0].offset, 0);
509        assert_eq!(insns[1].op, Opcode::Push1);
510        assert_eq!(insns[1].offset, 2);
511    }
512
513    /// A jump past the last instruction lands on the end index, which the interpreter
514    /// reads as "return undefined" — that is what `break` at the end of a block emits.
515    ///
516    /// `goto8` at offset 0 is two bytes long and its offset is relative to the byte
517    /// after it, so `1` names byte 2, which is the end of the code.
518    #[test]
519    fn a_jump_past_the_end_lands_on_the_end() {
520        let code = [Opcode::Goto8 as u8, 1];
521        let insns = predecode(&code);
522        assert_eq!(insns.len(), 1);
523        assert_eq!(insns[0].a as usize, insns.len());
524    }
525
526    /// A backward jump resolves to the instruction it names, which is how a loop closes.
527    #[test]
528    fn a_backward_jump_resolves() {
529        // `push_1` then `goto8 -2`: the instruction starts at byte 1, its offset is
530        // relative to byte 2, so `-2` names byte 0.
531        let code = [Opcode::Push1 as u8, Opcode::Goto8 as u8, 0xFE];
532        let insns = predecode(&code);
533        assert_eq!(insns.len(), 2);
534        assert_eq!(insns[1].op, Opcode::Goto8);
535        assert_eq!(insns[1].a, 0);
536    }
537
538    /// An operand that is not a jump keeps its value, so a slot index is not mistaken
539    /// for a target.
540    #[test]
541    fn a_plain_operand_is_untouched() {
542        let code = [Opcode::GetLoc8 as u8, 7, Opcode::Push1 as u8];
543        let insns = predecode(&code);
544        assert_eq!(insns[0].a, 7);
545    }
546
547    /// Truncated or corrupt bytecode stops the walk instead of panicking.
548    #[test]
549    fn an_unknown_opcode_ends_the_array() {
550        let code = [Opcode::Push1 as u8, 0xFF, Opcode::Push1 as u8];
551        let insns = predecode(&code);
552        assert_eq!(insns.len(), 1);
553        assert_eq!(insns[0].op, Opcode::Push1);
554    }
555
556    /// Decode the first function in `source` and hand back its records.
557    ///
558    /// Compiling rather than hand-assembling means the patterns under test are the ones
559    /// the real compiler emits, not the ones this file imagines it emits.
560    fn compiled(source: &str) -> Vec<Insn> {
561        let program = js_parse::parse_script(source).expect("parses");
562        let code = js_compile::compile_script(&program).expect("compiles");
563        let js_compile::bytecode::Constant::Function(first) = &code.cpool[0] else {
564            panic!("the script's first constant is the function");
565        };
566        predecode(&first.code)
567    }
568
569    /// The three fusions a counting loop is made of, all at once.
570    #[test]
571    fn a_counting_loop_fuses_its_header_body_and_increment() {
572        let insns =
573            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
574        let fused: Vec<Fused> = insns
575            .iter()
576            .filter(|insn| insn.fused != Fused::None)
577            .map(|insn| insn.fused)
578            .collect();
579        assert_eq!(
580            fused,
581            vec![
582                Fused::StoreImm,
583                Fused::StoreImm,
584                Fused::LtLocArgJump,
585                Fused::AddImmLoc,
586                Fused::PostIncLoc
587            ],
588            "header, body and increment each collapse into one dispatch"
589        );
590    }
591
592    /// A counting loop whose bound is a **literal** fuses its header too.
593    ///
594    /// This is the shape `for (var i = 0; i < 60000000; i++)` compiles to, and it used to
595    /// fuse nothing at the header: `LtLocArgJump` only matches a bound that is an
596    /// argument. Measured on `huge.js`, that difference alone was 2.72 s against 1.16 s.
597    #[test]
598    fn a_loop_header_with_a_literal_bound_fuses() {
599        let insns = compiled(
600            "function f(){ var t = 0; for (var i = 0; i < 60000000; i++) t += 1; return t }",
601        );
602        let header = insns
603            .iter()
604            .find(|insn| insn.fused == Fused::LtLocImmJump)
605            .expect("`get_loc; push_i32; lt; if_false` fuses with a literal bound");
606        assert_eq!(header.a, 1, "the counter's slot");
607        assert_eq!(header.imm, 60_000_000, "the bound, kept in `imm`");
608        assert_eq!(header.width(), 4, "four dispatches become one");
609    }
610
611    /// A small literal bound fuses the same way, and `imm` still carries it.
612    #[test]
613    fn a_loop_header_with_a_small_literal_bound_fuses() {
614        let insns =
615            compiled("function f(){ var t = 0; for (var i = 0; i < 7; i++) t += 1; return t }");
616        let header = insns
617            .iter()
618            .find(|insn| insn.fused == Fused::LtLocImmJump)
619            .expect("`push_7` counts as an integer literal");
620        assert_eq!(header.imm, 7);
621    }
622
623    /// A store fusion must name the slot the `put_loc` named, and the value the `push`
624    /// pushed.
625    #[test]
626    fn a_store_keeps_its_slot_and_value() {
627        // Hand-assembled so the operand is unambiguous: `push_7; put_loc0` is two bytes,
628        // and the trailing `push_1` proves the fusion stopped where the pattern ended.
629        let insns = predecode(&[
630            Opcode::Push7 as u8,
631            Opcode::PutLoc0 as u8,
632            Opcode::Push1 as u8,
633        ]);
634        let store = insns
635            .iter()
636            .find(|insn| insn.fused == Fused::StoreImm)
637            .expect("`push_7; put_loc0` fuses");
638        assert_eq!(insns.len(), 3, "the third instruction keeps its own record");
639        assert_eq!(store.a, 0, "slot of the local");
640        assert_eq!(store.b, 7, "the pushed integer");
641        assert_eq!(store.width(), 2);
642    }
643
644    /// `t += "abc"` and `s += t` fuse, and carry the operands the append needs.
645    #[test]
646    fn an_append_into_a_local_fuses() {
647        let atom = compiled(
648            r#"function f(n){ var t = ""; for (var i = 0; i < n; i++) t += "abc"; return t.length }"#,
649        );
650        let fused = atom
651            .iter()
652            .find(|insn| insn.fused == Fused::AddAtomLoc)
653            .expect("`get_loc; push_atom_value; add; put_loc` fuses");
654        assert_eq!(fused.a, 0, "the slot being appended to");
655        assert_eq!(fused.width(), 4);
656
657        let local = compiled(
658            "function f(n){ var t = '', c = 'x'; for (var i = 0; i < n; i++) t += c; return t.length }",
659        );
660        let fused = local
661            .iter()
662            .find(|insn| insn.fused == Fused::AddLocLoc)
663            .expect("`get_loc; get_loc; add; put_loc` fuses");
664        assert_eq!(fused.a >> 16, 0, "the slot being appended to");
665
666        // An argument on the right is a different read and a different fusion: `t += a`
667        // appears in every `join`-style loop and reads `args`, not `locals`.
668        let arg = compiled(
669            "function f(n, a){ var t = ''; for (var i = 0; i < n; i++) t += a; return t.length }",
670        );
671        let fused = arg
672            .iter()
673            .find(|insn| insn.fused == Fused::AddArgLoc)
674            .expect("`get_loc; get_arg; add; put_loc` fuses");
675        assert_eq!(fused.a >> 16, 0, "the slot being appended to");
676        assert_eq!(fused.a & 0xFFFF, 1, "`a` is the second argument");
677    }
678
679    /// `push k; get_loc x` is **not** a store.
680    ///
681    /// An earlier version asked one helper for "the local slot" without saying whether it
682    /// was being read or written, so this sequence — a pushed argument followed by a read,
683    /// as in `str.slice(0, p)` — fused into "store 0 into slot 0". The pushed argument was
684    /// dropped and the local was clobbered: a wrong answer, invisible to the compiler, the
685    /// unit tests and the bytecode diff. Only the differential suite caught it.
686    #[test]
687    fn a_push_followed_by_a_read_does_not_fuse() {
688        let insns = compiled("function f(p, str){ return str.slice(0, p) }");
689        for insn in &insns {
690            assert_ne!(
691                insn.fused,
692                Fused::StoreImm,
693                "`push; get_loc` must not become a store"
694            );
695        }
696        assert!(
697            insns.iter().any(|insn| insn.op == Opcode::GetArg0),
698            "the read of `p` is still its own instruction"
699        );
700    }
701
702    /// `x += 1` fuses only when the read and the write name the same local.
703    #[test]
704    fn an_add_needs_the_same_slot_on_both_ends() {
705        let same = compiled("function f(n){ var t = 0; t += n; return t }");
706        assert!(
707            same.iter().all(|insn| insn.fused != Fused::AddImmLoc),
708            "`t += n` pushes an argument, not an immediate"
709        );
710        let different = compiled("function f(){ var t = 0, k = 0; t = k + 1; return t }");
711        assert!(
712            different.iter().all(|insn| insn.fused != Fused::AddImmLoc),
713            "`t = k + 1` reads `k` and writes `t`"
714        );
715    }
716
717    /// A loop header's packed operands survive: the local, the argument, and the target
718    /// as an instruction index — not as the byte offset the encoding stores.
719    #[test]
720    fn a_loop_header_carries_a_resolved_target() {
721        let insns =
722            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
723        let header = insns
724            .iter()
725            .find(|insn| insn.fused == Fused::LtLocArgJump)
726            .expect("the loop header fuses");
727        let local = header.a >> 16;
728        let arg = header.a & 0xFFFF;
729        assert_eq!(local, 1, "`i` is local slot 1");
730        assert_eq!(arg, 0, "`n` is argument slot 0");
731        let target = header.b as usize;
732        assert!(
733            target < insns.len(),
734            "the target is an index into this array"
735        );
736        assert_eq!(
737            insns[target].op,
738            Opcode::GetLoc0,
739            "the target is `return t`, the first instruction after the loop"
740        );
741    }
742
743    /// Fusion leaves the record array alone: same length, same offsets, and each fused
744    /// record still names the byte its first instruction came from. That is what keeps a
745    /// stack trace and the line table pointing at the right place.
746    #[test]
747    fn fusion_keeps_offsets_and_count() {
748        let unfused: Vec<u32> =
749            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }")
750                .iter()
751                .map(|insn| insn.offset)
752                .collect();
753        let insns =
754            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
755        assert_eq!(
756            insns.iter().map(|insn| insn.offset).collect::<Vec<_>>(),
757            unfused,
758            "fusion must not renumber or drop records"
759        );
760        for pair in insns.windows(2) {
761            assert!(
762                pair[0].offset < pair[1].offset,
763                "offsets stay in byte order"
764            );
765        }
766        for (index, insn) in insns.iter().enumerate() {
767            assert!(
768                index + insn.width() <= insns.len(),
769                "a fused record's span stays inside the array"
770            );
771        }
772    }
773
774    /// Every opcode's record says where its bytes started, which is what a stack trace
775    /// and the line table read.
776    #[test]
777    fn offsets_walk_the_encodings() {
778        let code = [Opcode::Push1 as u8, Opcode::Push2 as u8, Opcode::Drop as u8];
779        let insns = predecode(&code);
780        assert_eq!(
781            insns.iter().map(|insn| insn.offset).collect::<Vec<_>>(),
782            vec![0, 1, 2]
783        );
784    }
785}