Skip to main content

ruxla_codegen/
lib.rs

1//! Ahead-of-time compilation of the IR to Rust: a traced function is optimized
2//! ([`opt`]) and turned into a Rust function of fixed-size arrays and scalars
3//! ([`emit`]) that `rustc` compiles with the rest of the program. Generated
4//! code calls [`rt`].
5//!
6//! # Examples
7//!
8//! ```
9//! use ruxla_ir::{AVal, DType, Eqn, Function, Params, Var};
10//!
11//! let x = Var::new(AVal::new([3], DType::F32));
12//! let y = Var::new(AVal::new([3], DType::F32));
13//! let f = Function {
14//!     invars: vec![x.clone()],
15//!     eqns: vec![Eqn {
16//!         prim: ruxla_prims::MUL,
17//!         inputs: vec![x.clone().into(), x.into()],
18//!         params: Params::None,
19//!         outputs: vec![y.clone()],
20//!         loc: None,
21//!     }],
22//!     outvars: vec![y.into()],
23//!     ..Function::default()
24//! };
25//! let code = ruxla_codegen::compile("square", &f, &Default::default()).unwrap();
26//! assert!(code.contains("pub fn square(a0: &[f32; 3]) -> ([f32; 3],)"));
27//! ```
28
29pub mod emit;
30pub mod opt;
31pub mod rt;
32
33pub use emit::{
34    ConstPool, Error, Input, Output, Signature, emit_function, emit_function_pooled,
35    emit_function_with,
36};
37pub use opt::{Options, Skip, optimize};
38
39/// Optimizes `f` and generates the Rust function `name` that computes it
40/// (see [`emit_function`]).
41///
42/// # Errors
43///
44/// Returns an error if the function uses element types or operations that
45/// cannot be generated.
46pub fn compile(name: &str, f: &ruxla_ir::Function, options: &Options) -> Result<String, Error> {
47    let g = optimize(f, options);
48    emit::with_skip(options.skip, || emit_function(name, &g))
49}
50
51/// [`compile`] with the arguments and results of `sig`.
52///
53/// # Errors
54///
55/// As [`compile`] and [`emit_function_with`].
56pub fn compile_with(
57    name: &str,
58    f: &ruxla_ir::Function,
59    options: &Options,
60    sig: &Signature,
61) -> Result<String, Error> {
62    let g = optimize(f, options);
63    emit::with_skip(options.skip, || emit_function_with(name, &g, sig))
64}
65
66/// [`compile_with`] whose constant arrays go to `pool`, shared by the
67/// functions of a module (see [`ConstPool`]).
68///
69/// # Errors
70///
71/// As [`compile`] and [`emit_function_with`].
72pub fn compile_pooled(
73    name: &str,
74    f: &ruxla_ir::Function,
75    options: &Options,
76    sig: &Signature,
77    pool: &mut ConstPool,
78) -> Result<String, Error> {
79    let g = optimize(f, options);
80    emit::with_skip(options.skip, || emit_function_pooled(name, &g, sig, pool))
81}
82
83#[cfg(test)]
84mod tests {
85    use ruxla_ir::{AVal, DType, Eqn, Function, HostArray, Params, Var};
86
87    /// Empty arrays (a constant, an input, and an element-wise result) are
88    /// generated as `[T; 0]`.
89    #[test]
90    fn empty_arrays() {
91        let c = Var::new(AVal::new([0], DType::I32));
92        let x = Var::new(AVal::new([0], DType::I32));
93        let y = Var::new(AVal::new([0], DType::I32));
94        let f = Function {
95            constvars: vec![(c.clone(), HostArray::from_vec(Vec::<i32>::new(), [0]))],
96            invars: vec![x.clone()],
97            eqns: vec![Eqn {
98                prim: ruxla_prims::ADD,
99                inputs: vec![x.into(), c.clone().into()],
100                params: Params::None,
101                outputs: vec![y.clone()],
102                loc: None,
103            }],
104            outvars: vec![y.into(), c.into()],
105        };
106        let code = crate::compile("empty", &f, &Default::default()).unwrap();
107        assert!(
108            code.contains("pub fn empty(a0: &[i32; 0]) -> ([i32; 0], [i32; 0])"),
109            "{code}"
110        );
111    }
112
113    /// A select on a constant empty predicate (JaxMARL's MPE with no
114    /// adversaries) is generated, not simplified by looking at its first
115    /// element.
116    #[test]
117    fn select_on_empty_constant_predicate() {
118        let p = Var::new(AVal::new([0], DType::Bool));
119        let x = Var::new(AVal::new([0], DType::F32));
120        let y = Var::new(AVal::new([0], DType::F32));
121        let z = Var::new(AVal::new([0], DType::F32));
122        let f = Function {
123            constvars: vec![(p.clone(), HostArray::from_vec(Vec::<bool>::new(), [0]))],
124            invars: vec![x.clone(), y.clone()],
125            eqns: vec![Eqn {
126                prim: ruxla_prims::SELECT_N,
127                inputs: vec![p.into(), x.into(), y.into()],
128                params: Params::None,
129                outputs: vec![z.clone()],
130                loc: None,
131            }],
132            outvars: vec![z.into()],
133        };
134        crate::compile("select_empty", &f, &Default::default()).unwrap();
135    }
136
137    /// A reduction over axes that are not adjacent is generated as a loop
138    /// (through a table of the output elements), not evaluated by the
139    /// interpreter.
140    #[test]
141    fn reduce_over_axes_apart() {
142        let x = Var::new(AVal::new([2, 3, 2, 3], DType::I32));
143        let y = Var::new(AVal::new([2, 2], DType::I32));
144        let f = Function {
145            constvars: Vec::new(),
146            invars: vec![x.clone()],
147            eqns: vec![Eqn {
148                prim: ruxla_prims::REDUCE_SUM,
149                inputs: vec![x.into()],
150                params: Params::Reduce { axes: vec![1, 3] },
151                outputs: vec![y.clone()],
152                loc: None,
153            }],
154            outvars: vec![y.into()],
155        };
156        let code = crate::compile("sum13", &f, &Default::default()).unwrap();
157        assert!(!code.contains("rt::eval"), "{code}");
158        assert!(code.contains("for i in 0..36usize"), "{code}");
159    }
160}