MLIR text ⇄ IR ⇄ typed Rust ops.
MLIR behavior follows MLIR 23.1.5 (llvm-project llvmorg-23.1.5): the textual format, the
dialects and their assembly formats are checked against mlir-opt 23.1.5.
cargo add mlirformat # the library
cargo install mlirformat # the `mlirformat` command line| feature | default | what it is |
|---|---|---|
std |
yes | the standard library (without it the library is no_std and needs alloc), moremath's threads for parse_in / print_in |
tblgen |
yes | the mlirformat command line, which generates dialects from ODS .td files (TableGen built in, no LLVM needed); pulls in clap and serde_json; jemalloc as the command line's global allocator (not on MSVC; the library leaves the allocator to the program); turns on std |
gen-tests |
no | test only: the dialects mlirformat tblgen generated, one test crate each (tests/generated/) |
less |
no | test only: the fixture tests read every 10th file of tests/fixtures, the same 10 % on every run (also when neither less nor more is on) |
more |
no | test only: the fixture tests read every file of tests/fixtures (before a minor or major release) |
For the library alone: cargo add mlirformat --no-default-features.
use mlirformat::{MlirOpt, Operation, Type, Value, mlir};
// An op: a struct with `#[mlir::op]`.
#[mlir::op("demo.max", format = "$lhs `,` $rhs attr-dict `:` type($result)", results(result))]
pub struct Max<'a> {
#[slot(result)]
pub lhs: Value<'a>,
#[slot(result)]
pub rhs: Value<'a>,
pub result: Type<'a>,
}
// A dialect: a struct listing its ops with `#[mlir::dialect]` (and its traits, if any:
// `dependents = [..]`, `materializer`, `canonicalizer`).
#[mlir::dialect("demo", ops = [Max])]
pub struct DemoDialect;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// custom form ⇄ struct ⇄ generic op
let op = Max::try_from("demo.max %a, %b : i32")?;
assert_eq!(Max::new(op.lhs.clone(), op.rhs.clone(), op.result.clone()), op); // `new`: the declared fields, in order
let generic = Operation::try_from(&op)?;
assert_eq!(generic.to_string(), r#""demo.max"(%a, %b) : (i32, i32) -> i32"#);
assert_eq!(Max::try_from(&generic)?, op);
// whole files: load the dialect
let mut opt = MlirOpt::upstream();
opt.load(DemoDialect);
let module = opt.parse(r#"%0 = "demo.max"(%a, %b) : (i32, i32) -> i32"#)?;
assert_eq!(opt.show(&module).to_string(), "%0 = demo.max %a, %b : i32\n");
Ok(())
}A field's MLIR role is its Rust type: a Type is a type variable, a Region a region, anything
else but a Value a property (bool: a unit attribute). A marker is written for an operand
(#[slot(T)]), a successor, a role the type does not say (#[attr] on a Type: a type
attribute), or to carry the options below. A Vec field is variadic; the MLIR name is the field
name unless name = "..." (overflow_flags spelled overflowFlags).
| marker | the field is |
|---|---|
#[slot(T)] |
an operand, typed by type variable T |
#[dtype], #[dtype(i1)], #[dtype(i1 = x)], #[dtype(of = attr)], #[dtype(eq = x)], #[dtype(is = index)], #[dtype(el = x)], #[dtype(width = x)] |
a type variable (results by results(...)), and how the custom form infers it when unspelled |
#[attr], #[attr(int = "i32")], #[attr(dialect = "arith.overflow", default = "<none>")], dense = "i64", symbol, bits = ... |
a property: bool is a unit attribute, an enum a case typed int |
#[region], #[successor] |
a region, a successor |
A property with a declared default is an Option: None leaves it absent, and whoever builds
the op fills the default (#arith.overflow<none>, 0 : i32) — the same op as one built by name.
Parsing fills the default and printing drops it, so a round trip keeps it as written.
Op options: format = "..." (the ODS assembly format), results(a, b), custom (Print /
Parse written by hand); without format the op has no custom form and always prints generic.
attrs (discardable attributes) and loc fields are added.
#[derive(mlir::Cases)] on an integer enum gives TryFrom<i64> by case value (the variant's
position; the hidden __N variants filling gaps take none) — CmpIPredicate::try_from(2) is
slt. Every enum mlirformat tblgen generates derives it.
Built in and registered by MlirOpt::upstream(): affine, arith, async, bufferization,
builtin, cf, complex, emitc, func, gpu, index, linalg, llvm, math, memref,
pdl, scf, shape, tensor, tosa, ub, vector; the CPUs' x86 (AVX-512, AVX10 and AMX, one dialect since MLIR 23), arm_neon,
arm_sve and arm_sme; the GPU vendors' nvgpu, nvvm, amdgpu, rocdl, xegpu and xevm;
spirv. arith, builtin, cf, complex,
func, index, math and ub are written by hand; the rest are generated from ODS by
mlirformat tblgen; llvm_types::LlvmType, emitc_types::EmitcType and
spirv_types::SpirvType read and build those dialects' types. An op whose syntax ODS leaves to C++ gets a hand-written form, injected by name
over the generated one so the generated files stay as mlirformat tblgen wrote them:
affine_ops (affine.for / if / parallel / apply / min / max / load / store),
scf_hand (scf.for / if / while), vector_hand (vector.shuffle: its result type is the mask's length over the first operand's trailing shape, which the format engine cannot infer), gpu_hand (gpu.func, gpu.launch_func), llvm_hand (llvm.func,
llvm.call, llvm.icmp / fcmp, llvm.getelementptr: read and written on the generic Operation, the typed ops stay
the generated ones), linalg_hand
(linalg.generic / yield, the named ops: the OpDSL ones generated from
LinalgNamedStructuredOps.yaml by scripts/linalg_named.py, matmul / batch_matmul /
batch_reduce_matmul / contract, transpose / broadcast / map / reduce / elementwise;
mlir-opt does not print a named op's region, so reading one rebuilds it as the op's region
builder does, with the ODS defaults of the ops it makes). An op
whose ODS syntax the format engine cannot express stays on the generic form, which is still valid
MLIR — tests/dialects.rs checks every custom form against mlir-opt 23.1.5 and counts the rest.
Not in MlirOpt::upstream() (load it with opt.load(nir::NirDialect)): nir, Mesa's NIR ALU opcodes, one op
each (nir.fadd %a, %b : (f32, f32) -> f32, every type written, exact its NIR flag), generated by
scripts/nir_opcodes.py from Mesa 25.2.8's src/compiler/nir/nir_opcodes.py; NirDialect::OPCODES keeps each
opcode's sources, sizes, types and algebraic properties. It is what a GPU backend lowers SPIR-V to when it must
compute as Mesa's drivers do.
Not in MlirOpt::upstream() either (load it with opt.load(glsl::GlslDialect)): glsl, GLSL (ES 1.00 /
3.00) as MLIR — glsl.shader and its globals (in / out / uniform, locations, interpolation,
built-in variables), glsl.load / glsl.store, constructors, built-in functions, derivatives, texture
sampling, discard; the rest of a shader is func / arith / math / vector / scf, aggregates and
samplers !spirv.* types. GLSL source itself is read and written by
mlirpass (target.glsl).
ODS keeps a custom<X>(...) directive's syntax out of the .td and leaves it to a hand-written
parseX / printX pair in C++, so the .td alone never says what the syntax is. src/syntax.rs
declares those directives instead, once each and in one direction only:
syntax! {
/// `[%a, 7, 42]`
DynamicIndexList($values, $integers) = "[" zip($integers, $values) "]";
}Names are shared across dialects, so one rule covers every op that calls it. The name never
reaches run time: mlirformat tblgen asks whether a directive is declared before it keeps a
format, and the format tokenizer expands the call site into plain elements.
What ODS says about each op — its native traits and interfaces (Trait::Pure,
Trait::RegionBranchOpInterface, …), its memory effects, its inherent attributes — is asked
of the context, never a global table: opt.op_info("memref.load"), opt.knows_dialect("tosa").
MlirOpt::upstream() knows every upstream op (not only the dialects above) and the dialects
mlir-opt registers; a loaded dialect brings its own rows. The context keeps them in an OpInfos,
filled by OpInfos::upstream() or insert / dialect. The upstream rows (src/traits.gen.rs) are generated
from llvm-project's ODS by scripts/traits.py:
python3 scripts/traits.py --llvm $LLVM --mlirformat target/release/mlirformat -I $LLVM_BUILD/tools/mlir/includeThe same run writes src/verifier/ods.gen.rs: each op's inherent attributes with their ODS
constraints, which MlirOpt::verify checks as verifyInherentAttrs does, and the kind of each
operand and result type (the C++ class its constraint is of: IntegerType, VectorType, …).
scripts/spirv_enums.py writes src/verifier/spirv.gen.rs, the cases of every SPIR-V enum
attribute (SPIRVBase.td).
Attributes and types keep their text (Attribute::Builtin { name, body }, a dialect type's
body in Extended), so the text round trip stays exact. src/values/ says what that text means
as values, in both directions, for whoever computes with the IR (folds, rewrites, lowerings):
| what | as | MLIR |
|---|---|---|
| numbers | ApInt, ApFloat (and MLIR's float printing) |
APInt, APFloat |
| constants | Const ⇄ Attribute (TryFrom / From), elements as Scalar |
IntegerAttr, FloatAttr, BoolAttr, DenseElementsAttr |
| memref layouts | StridedLayout ⇄ Attribute; Shaped::layout / strided / memory_space |
StridedLayoutAttr |
| affine maps and sets | AffineMap, IntegerSet, AffineExpr ⇄ Attribute |
AffineMap, IntegerSet, AffineExpr |
| quantized types | UniformQuantized ⇄ Type, storage_type |
quant::UniformQuantizedType |
| locations | Loc (a loc(...)'s text), Loc::fuse |
FusedLoc::get, Builder::getFusedLoc |
Builtin types and attributes are read and built through methods named as MLIR names them:
Type::element_type, element_count, shape, dims, with_element, bit_width,
Type::tensor(dims, elem), Type::vector(shape, scalable, elem); Attribute::integer,
index, i32, i64, dense_array (dense_i64, dense_i32), dense_values, int_array, int_array_of, int_values, dicts / dict_at (per-argument dictionaries), dialect_with / inner / case_of (a dialect attribute's <...> body), is_poison, is_layout. A ? dim is
Dim::DYNAMIC (ShapedType::kDynamic), and Dim ⇄ i64 through From.
Affine text has one parser, affine_expr, which keeps an expression as written (Map, Set)
so that the affine ops' custom forms print back exactly. AffineMap / IntegerSet are the
canonical form built from it through MLIR's simplifying constructors (AffineMap::try_from(&map),
AffineMap::parse(text)): that is the form to fold, compose and simplify, and it prints what
mlir-opt prints for a map it built.
Module, Operation and the rest borrow their text (Cow<'a, str>) from the source they were
read from. IntoStatic::into_static makes a value own all of it (by move: owned text moves, only
borrowed text is copied). Reborrow::reborrow goes the other way: a view of a value that borrows
all its text from it, copying only the lists that hold it, so that an IR keeping its own text can
hand it to the printer without a deep copy.
MlirOpt::parse_file(src, name) (and parse_file_in) reads text as the file name: an op or block
argument written without loc(...) is at loc("name":line:col) of where it starts, as mlir-opt
locates it; parse leaves it without one.
MlirOpt::parse_in(src, &exec) and MlirOpt::print_in(&module, &source, &exec) take an
executor (ThreadMulti, re-exported from moremath; feature
std). Reading, a block of at least MlirOpt::PARALLEL_BYTES is cut at its ops into runs read
in parallel, an op as big as a run splitting again; printing, the ops of a module's body are
printed in runs into strings of their own, joined in order. Either gives exactly what parse /
show_from give. A [Source] names its regions by u64 ids.
mlirformat tblgen turns an ODS .td file into <dialect>.gen.rs: one #[mlir::op] struct per
op and a #[mlir::dialect] struct listing them, with the dialect's traits from its Dialect record.
Each struct's doc comment is the op's ODS summary and description (Markdown kept; a code block
without a language or an indented one becomes text, so none is a doctest), so cargo doc on a
crate holding generated dialects documents every op as its .td does. TableGen itself is built in: a port of LLVM 23.1.5's front end (its let append / let prepend included; !sort and !switch, which no MLIR .td uses, are not)
resolves the records in process (no LLVM build needed; only the .td sources, e.g. mlir/include).
--dump-json prints those records exactly as llvm-tblgen --dump-json does (checked byte for byte on
every MLIR dialect .td that llvm-tblgen accepts on its own). Several .td files are generated in parallel. The generated files also compile in
no_std crates; --params <namespace>=<path> attaches a dialect's type / attribute parameter hook.
mlirformat tblgen $LLVM/mlir/include/mlir/Dialect/Arith/IR/ArithOps.td \
-I $LLVM/mlir/include -o src/dialectstd/ is llvm-project 23.1.5's mlir/include, cut down to what the built-in dialects include:
the upstream .td files, unchanged, at their own paths; -I td is the root their
include "mlir/..." lines read from. A dialect whose ops upstream splits over several files is one
--dialect <namespace> run over those files (linalg: LinalgOps.td, LinalgStructuredOps.td,
LinalgRelayoutOps.td). An include the upstream .td declares relative to itself
(ArmSMEOps.td's include "ArmSME.td") is found beside its includer, as each upstream build passes
its own directory as -I:
D=td/mlir/Dialect/Linalg/IR
mlirformat tblgen --dialect linalg $D/LinalgOps.td $D/LinalgStructuredOps.td $D/LinalgRelayoutOps.td \
-I td -o src/dialectsscripts/regen-dialects.sh regenerates every one of them. Three files are what a 23.1.5 build
generates rather than keeps in the source tree, and td/ holds them too, at the same paths:
LinalgNamedStructuredOps.yamlgen.td (from the OpDSL YAML), and OpenMP/OmpCommon.td /
OpenACC/AccCommon.td (--gen-directive-decl of llvm's OMP.td / ACC.td, which
scripts/directive_common.py reproduces).
mlirformat bc converts between MLIR text and bytecode (.mlirbc, version 6, as mlir-opt --emit-bytecode writes it): bytecode in, text out; text in, bytecode out. In the library the same is
Bytecode::read / Bytecode::write. tests/bytecode holds a module per upstream test file, each
written by mlir-opt 23.1.5 (scripts/mlirbc_fixtures.py); 2243 of 2269 write byte for byte, 2245 read
back as mlir-opt prints them. The properties table is read off an LLVM build by scripts/mlirbc_props.py.
mlirformat bc module.mlir -o module.mlirbc # text ⇒ bytecode
mlirformat bc module.mlirbc # bytecode ⇒ textMeasured with 0.6.2 against mlir-opt 22.1.8 (BENCHMARK.md), 16 CPUs, both threaded, jemalloc (the command
line's global allocator): parse_in reads a 54 MB generic module in 182 ms and a 32 MB
custom one in 214 ms; as whole processes, generic in ⇒ generic out is 5.8× faster than mlir-opt,
custom in ⇒ custom out 1.6×. Peak memory is 2.6–3.2× mlir-opt's.
MIT