oxilean_codegen/opt_peephole/types.rs
1//! Types for the peephole optimisation pass.
2
3/// A single instruction in the peephole instruction model.
4///
5/// The instruction set is intentionally small: it covers the stack-machine
6/// primitives that appear in common IR back-ends and for which standard
7/// peephole identities are well-known.
8#[allow(dead_code)]
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum PeepInstr {
11 /// Push an immediate integer constant.
12 Const(i64),
13 /// Integer addition (pops two, pushes one).
14 Add,
15 /// Integer subtraction (pops two, pushes one).
16 Sub,
17 /// Integer multiplication (pops two, pushes one).
18 Mul,
19 /// Integer division (pops two, pushes one).
20 Div,
21 /// Arithmetic negation (pops one, pushes one).
22 Neg,
23 /// Load the value of a named variable.
24 Load(String),
25 /// Store the top-of-stack into a named variable.
26 Store(String),
27 /// Conditional branch to the named label.
28 Branch(String),
29 /// Unconditional jump to the named label.
30 Jump(String),
31 /// Return from the current function.
32 Ret,
33 /// Duplicate the top-of-stack.
34 Dup,
35 /// Discard the top-of-stack.
36 Pop,
37 /// Swap the top two stack values.
38 Swap,
39 /// No-operation (placeholder; removed by the dead-nop rule).
40 Nop,
41}
42
43/// A pattern to be matched against a window of instructions.
44#[allow(dead_code)]
45#[derive(Debug, Clone)]
46pub struct PeepPattern {
47 /// The sequence of instructions that must match.
48 pub instrs: Vec<PeepInstr>,
49 /// Human-readable name for this pattern (used in diagnostics).
50 pub name: String,
51}
52
53/// The replacement sequence produced when a [`PeepPattern`] fires.
54#[allow(dead_code)]
55#[derive(Debug, Clone)]
56pub struct PeepReplacement {
57 /// The sequence that replaces the matched window.
58 pub instrs: Vec<PeepInstr>,
59 /// Human-readable name for this replacement (used in diagnostics).
60 pub name: String,
61}
62
63/// A complete peephole optimisation rule: pattern → replacement.
64#[allow(dead_code)]
65#[derive(Debug, Clone)]
66pub struct PeepRule {
67 /// The pattern to look for.
68 pub pattern: PeepPattern,
69 /// The replacement to emit when the pattern fires.
70 pub replacement: PeepReplacement,
71 /// Higher priority rules are tried first.
72 pub priority: i32,
73}
74
75/// The result returned by [`crate::opt_peephole::run_peephole`].
76#[allow(dead_code)]
77#[derive(Debug, Clone)]
78pub struct PeepResult {
79 /// The optimised instruction sequence.
80 pub instructions: Vec<PeepInstr>,
81 /// Names of the rules that were applied (in order of application).
82 pub rules_applied: Vec<String>,
83 /// The net number of instructions eliminated (original count minus final count).
84 pub reduction: usize,
85}