Modern compiler stacks often tempt architects into forcing every intermediate representation into LLVM IR or MLIR. Weyl deliberately rejects that one-size-fits-all approach by drawing a hard boundary between its symbolic middle-end (SIR + KIR) and its numerical back-end (TIR → MLIR / Cranelift). Graded non-commutative normal forms, monomial-ideal truncation, and tens of millions of sparse operator terms live exclusively in pure-Rust symbolic kernels; only after all symbolic parameters are eliminated and rational coefficients are reconstructed via CRT + Wang does execution cross into TirKernel and enter weyl-mlir.
Why Keep MLIR and LLVM IR Out of the Symbolic Middle-End?
SSA value graphs and heap-allocated rewrite nodes excel at dense tensors and structured control flow. High-order perturbation theory (e.g. 14th-order pCUT), however, is dominated by streaming sparse non-commutative operator strings, multi-prime accumulation, and external-memory sorting. Encoding those streams in SSA graphs creates catastrophic allocation and pointer-chasing overhead.
Symbolic Middle-End: SIR Templates & KIR Flat Streams
Weyl's symbolic middle-end operates across two tightly scoped layers:
1. SIR: Translation-Orbit Templates & DeriveGraph
SIR keeps Hamiltonians unexpanded as translation-orbit TermTemplates and encodes expand, estimate, and compare steps as a dataflow DAG (DeriveGraph). Deterministic egg equality saturation and the Pass Manager (including sandboxed LLM scheduling) act exclusively on SIR:
// Core SIR data structures
pub struct TermTemplate {
pub coeff: ParamPoly, // Rational polynomial in J, x, kappa1, kappa2
pub local: LocalOp, // Unit-cell operator pattern: (offset, sublattice, generator)
pub orbit: OrbitSpec, // Translation group and spatial domain (bulk / Bot / Top)
pub tags: TermTags, // Conserved charge, Hermiticity, unperturbed flag, T_n grade
}
pub struct DeriveGraph {
pub nodes: IndexVec<NodeId, PassNode>,
pub edges: Vec<(NodeId, NodeId, ValueKind)>,
}
pub struct PassNode {
pub pass: PassId,
pub params: PassParams,
pub out_err: Err, // Statically inferred error tag
pub state: NodeState,
}2. KIR: 10M+ Sparse Non-Commutative Term Streams
Once a Pass chooses concrete clusters, symmetry sectors, and expansion orders, SIR instantiates into KIR (Kernel IR). A KIR value is a flat, 8-byte-aligned stream of records sorted lexicographically by canonical monomial, modeled on FORM's external-memory merge engine:
#[repr(C, align(8))]
pub struct TermHeader {
pub len: u32, // Total record size in bytes (padded to 8-byte alignment)
pub mono_len: u16, // Byte length of canonical monomial encoding
pub flags: u16, // Bit 0 encodes parity of i; sign is folded into the coefficient
}
// Flat record layout: [TermHeader][coeff: [u64; K]][mono: mono_len bytes][pad to 8]Coefficients accumulate simultaneously in Montgomery form across 63-bit prime fields . When memory approaches its budget, streaming operators (Multiply, Normalize, Project, Truncate, Apply) run MSD radix sort, NVMe chunk spilling, and loser-tree -way merges. Finally, Reconstruct executes Chinese Remainder Theorem (CRT) lifting and Wang rational reconstruction.
The Symbolic–Numerical Boundary: TirKernel
Once KIR completes rational reconstruction and eliminates all symbolic parameters, execution crosses an irreversible boundary into TirKernel (weyl-tir):
pub enum TirKernel {
/// Matrix-free H·v operator for Lanczos ED and Krylov solvers
MatVec {
basis: SectorBasis,
terms: Vec<PauliTerm>,
precision: Precision, // F64 or DoubleDouble (~106-bit significand)
},
/// Verified univariate or multivariate rational series table with error tag
SeriesTable {
var: VarId,
coeffs: Vec<Rational>,
err: Err,
},
// Planned kernels, not yet in weyl-tir:
// Mpo { bond_dim, sites, tensors, symmetry, err },
// SdpBlock { matrix_dim, constraint_polys, err },
// IbpSystem { integrals, reduction_matrix, err },
}weyl-mlir: What Is Implemented
weyl-mlir lowers verified TirKernels to MLIR in the generic operation syntax, using only the standard builtin, func, arith, math, memref and scf dialects. There is no custom weyl.* dialect: every module it prints is accepted by a stock mlir-opt.
| Module | Role | Needs LLVM? |
|---|---|---|
ir.rs | Data model (types, attributes, operations, single-block regions), printer, Builder | no |
parse.rs | Parser for the same generic syntax | no |
verify.rs | Structural verifier: SSA dominance, operand and result types, region shapes | no |
interp.rs | Reference interpreter over f64/i64 buffers | no |
lower.rs | TirKernel → Module | no |
aot.rs | mlir-opt → mlir-translate → clang, as external processes | yes |
Lowering rules
| Kernel | Emitted function | How |
|---|---|---|
MatVec (Precision::F64) | @name(in: memref<?xf64>, out: memref<?xf64>) | A Pauli term maps a basis state to ket ^ xmask with weight ±c, the sign being the parity of the bits of ket under the term's Z/Y mask. The image row of every column is tabulated once per distinct xmask, so sector bases need no hash lookup at run time. |
SeriesTable | @name(x: f64) -> f64 | Horner's rule over a constant coefficient table |
MultiSeriesTable | @name(xs: memref<?xf64>) -> f64 | Term by term, monomials by repeated multiplication |
Floating-point operations are emitted in the order the weyl-tir reference evaluators perform them, so results agree bit for bit. All f64 constants are printed as IEEE 754 bit patterns.
Not implemented
Several features remain outside the current MLIR lowering path. Precision::DoubleDouble kernels are refused with LowerError::DoubleDouble and continue to run through the Cranelift JIT, while Mpo, SdpBlock, and IbpSystem kernels do not yet exist in weyl-tir and therefore have no lowering. A kernel's error tag is not carried into the emitted MLIR text—it remains on the TirKernel and in the pipeline report, since the compiled function is a numerical backend and never produces an Exact value. Likewise, no linalg/affine/vector lowering, loop fusion, or contraction planning is implemented yet.
Inspecting Lowered IR with weylc dump-ir
# All TIR kernels of a program as one MLIR module (functions kernel_0, kernel_1, …)
$ weylc dump-ir --emit mlir --order 6 examples/toric_boundary.weyl
# The same module as LLVM IR, through the installed mlir-opt and mlir-translate
$ weylc dump-ir --emit llvm-ir --order 6 examples/toric_boundary.weyl
# A self-contained sample (a series table and a two-qubit H·v)
$ cargo run -p weyl-mlir --example emit--order stops every expansion at the given order, as it does for weylc run. A series table lowers to:
"builtin.module"() ({
"memref.global"() {constant, initial_value = dense<[0xBFF0000000000000, 0x0000000000000000, 0xBFD0000000000000]> : tensor<3xf64>, sym_name = "e0_coeff", sym_visibility = "private", type = memref<3xf64>} : () -> ()
"func.func"() ({
^bb0(%0: f64):
%1 = "memref.alloca"() {operandSegmentSizes = array<i32: 0, 0>} : () -> memref<1xf64>
%2 = "arith.constant"() {value = 0 : index} : () -> index
%3 = "arith.constant"() {value = 0x0000000000000000 : f64} : () -> f64
"memref.store"(%3, %1, %2) : (f64, memref<1xf64>, index) -> ()
%4 = "memref.get_global"() {name = @e0_coeff} : () -> memref<3xf64>
%5 = "arith.constant"() {value = 2 : index} : () -> index
%6 = "arith.constant"() {value = 0 : index} : () -> index
%7 = "arith.constant"() {value = 3 : index} : () -> index
%8 = "arith.constant"() {value = 1 : index} : () -> index
"scf.for"(%6, %7, %8) ({
^bb0(%9: index):
%10 = "arith.subi"(%5, %9) : (index, index) -> index
%11 = "memref.load"(%4, %10) : (memref<3xf64>, index) -> f64
%12 = "memref.load"(%1, %2) : (memref<1xf64>, index) -> f64
%13 = "arith.mulf"(%12, %0) : (f64, f64) -> f64
%14 = "arith.addf"(%13, %11) : (f64, f64) -> f64
"memref.store"(%14, %1, %2) : (f64, memref<1xf64>, index) -> ()
"scf.yield"() : () -> ()
}) : (index, index, index) -> ()
%15 = "memref.load"(%1, %2) : (memref<1xf64>, index) -> f64
"func.return"(%15) : (f64) -> ()
}) {function_type = (f64) -> (f64), sym_name = "e0"} : () -> ()
}) : () -> ()The inner loop of a MatVec kernel:
"scf.for"(%41, %42, %43) ({
^bb0(%44: index): // column
%45 = "arith.addi"(%40, %44) : (index, index) -> index
%46 = "memref.load"(%24, %45) : (memref<8xi64>, index) -> i64 // row = perm[group·dim + col]
%47 = "arith.cmpi"(%46, %29) {predicate = 5 : i64} : (i64, i64) -> i1 // row ≥ 0: inside the sector
"scf.if"(%47) ({
%48 = "arith.index_cast"(%46) : (i64) -> index
%49 = "memref.load"(%23, %44) : (memref<4xi64>, index) -> i64 // ket = states[col]
%50 = "arith.andi"(%49, %37) : (i64, i64) -> i64 // bits under the Z/Y mask
%51 = "math.ctpop"(%50) : (i64) -> i64
%52 = "arith.andi"(%51, %30) : (i64, i64) -> i64 // parity
%53 = "arith.cmpi"(%52, %30) {predicate = 0 : i64} : (i64, i64) -> i1
%54 = "arith.select"(%53, %36, %35) : (i1, f64, f64) -> f64 // −c or +c
%55 = "memref.load"(%16, %44) : (memref<?xf64>, index) -> f64
%56 = "arith.mulf"(%54, %55) : (f64, f64) -> f64
%57 = "memref.load"(%17, %48) : (memref<?xf64>, index) -> f64
%58 = "arith.addf"(%57, %56) : (f64, f64) -> f64
"memref.store"(%58, %17, %48) : (f64, memref<?xf64>, index) -> ()
"scf.yield"() : () -> ()
}, {
}) : (i1) -> ()
"scf.yield"() : () -> ()
}) : (index, index, index) -> ()Ahead-of-Time Compilation
With an LLVM installation that ships the MLIR tools (tested with LLVM 23.1.7: mlir-opt, mlir-translate, clang), weyl_mlir::aot::Toolchain compiles a module to an object file or a shared library. The tools run as external processes; weyl-mlir does not link LLVM.
use weyl_mlir::{aot::Toolchain, lower::lower};
let module = lower(&kernel, "h")?;
let tools = Toolchain::discover()?; // /usr/lib/llvm-N/bin, newest first, then PATH
let ir: String = tools.llvm_ir(&module)?; // mlir-opt passes, then mlir-translate
tools.object(&module, "h.o".as_ref())?; // clang -O2 -c
tools.shared_library(&module, "libh.so".as_ref())?;The mlir-opt pass list is fixed:
--convert-scf-to-cf --expand-strided-metadata --finalize-memref-to-llvm
--convert-math-to-llvm --convert-arith-to-llvm --convert-func-to-llvm
--convert-cf-to-llvm --reconcile-unrealized-castsThe compiled functions follow the MLIR C ABI: an f64 is a double, and a rank-1 memref<?xf64> argument becomes five arguments.
void h(double *in_alloc, double *in_aligned, int64_t in_offset, int64_t in_size, int64_t in_stride,
double *out_alloc, double *out_aligned, int64_t out_offset, int64_t out_size, int64_t out_stride);
double e0(double x);No LLVM is needed to build or test Weyl
Everything except aot.rs is pure Rust. The ahead-of-time tests skip themselves when no toolchain is found. Interactive runs and the ED hot loops use the Cranelift JIT (weyl-jit-clif).
How the Backend Is Checked
Each lowering is verified across four layers of testing. At the syntactic layer, a print–parse round trip checks that print → parse yields an equal module whose re-printed text is identical. Structural verification then confirms that verify accepts every emitted module and rejects any module with a type error injected into its text, ensuring that an unverified module is never passed to external tools. Next, differential execution compares the reference interpreter bit for bit against TirKernel::apply_matvec_f64 (on both full and sector bases) and TirKernel::eval_series_f64. Finally, whenever an LLVM toolchain is installed, native execution links the compiled object against a small C driver and compares its output bit for bit against the interpreter on a 6-qubit H·v with ZZ, X, and YY terms as well as a series evaluated at five points.
// crates/weyl-mlir/src/ir.rs
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Type {
F64,
Int(u32), // i1, i64, i128
Index,
MemRef { elem: Box<Type>, len: Option<u64> }, // memref<NxT> or memref<?xT>
}