Repository navigation
selfhost: flowc MLIR emitter for spans, closures, effects, forward declarations, @gpu and the GPU dialect - #1070
Merged
Merged
Conversation
…rals, folded consts Spans lower as Python's !llvm.struct<(!llvm.ptr, i64)>: parameters, locals, .len, indexing, stores, slices of pointers, memrefs and spans, and borrows at call sites. [T; N] is array<T, N>. [v; N] is written out N times as Python's parser does. An array literal used as a value is a stack memref, array<T>(n) is memref.alloc, and a single-statement elementwise loop over local f32/i32 memrefs takes Python's vector<4xT> rewrite. List patterns bind and compare elements. Consts take Python's second path: cast-wrapped and negated literals, folded integer expressions, and zero for anything else. A call to an undeclared name is func.call @name returning i32, as Python emits it. The MLIR output buffer is 32 MiB. Accepted 829 of the corpus, 828 text-equal to Python at 84806b0, 0 text failures.
Function types lower to Python's fat closure !llvm.struct<(!llvm.ptr, !llvm.ptr)>. A lambda is lifted to func.func private @lambda_N(%env, ...) ahead of the declarations; its captures are its free names in sorted order, copied into a malloc'd environment, and read back through it. Calls through closure locals and parameters extract the code and env pointers. A named function passed where a closure is expected goes through a __flow_callback_ adapter, and a function name used as a value is func.constant plus a cast to !llvm.ptr. Also: i64 literals up to 2^63-1, return void, and array and struct consts Python zero-fills. Accepted 844 of the corpus, 843 text-equal to Python at 84806b0, 0 text failures.
…alls Effects lower as Python's generate_effect: a current-handler global and a NULL-checked dispatch function per operation. Capabilities emit their methods as <Cap>_<method> functions and one zeroed vtable per handled effect, which @_flow_effects_init fills and main calls first. handle blocks install and restore the vtables, and an effect call inside one calls the handling capability directly. Other method calls lower as a call with the receiver first, as Python desugars them. Variadic externs and the printf/scanf family are llvm.func declarations called through llvm.call with a vararg callee type. Overloads are all emitted, with calls resolving to the last, and calls pass the arguments they have against the parameter types. Unknown type names and capability parameters take Python's memref<16xi8>. Accepted 920 of the corpus, 919 text-equal to Python at 84806b0, 0 text failures.
A forward declaration is emitted the way Python emits it, as a function with an empty body beside the definition, which calls then resolve to. An absolute import whose first part is a [dependencies] key in flow.toml resolves under flow_packages/<key>/src, then flow_packages/<key>, as Python's resolver does. The remaining unresolved imports are programs Python cannot build either: packages missing from the checkout and proof-layer claim imports. Accepted 947 of the corpus, 946 text-equal to Python at 84806b0, 0 text failures.
An @gpu function is left out of the module, as Python's generate_module splits GPU kernels off (they reach MLIR only under --mlir-gpu). Mode guards follow transpiler._function_allowed with the modes the MLIR backend runs under (compile, mlir): @hot, @jit, @interp and @c drop a function, @compile and @MLIR keep it, @only and @guard keep it when they name an active mode. @Cinclude, @cembed and @cImport stay refused: Python rejects the first two, and the third reads C headers. Accepted 955 of the corpus, 953 text-equal to Python at 84806b0, 0 text failures.
The Stage-A parser reads Python's record-update form into an AST_STRUCT_LIT whose c holds the base, marked by a new parse-only AST_RECORD_UPDATE node. The typecheck and the MLIR emitter pass over the marker; cgen and jsgen refuse it with a located message as for any other parse-only form. The emitter follows generate_record_update: copy the base and insert each listed field, converted to its declared type. A base whose type names no struct (an unannotated let, a pointer) is the whole value, as in Python. Corpus digests of the programs that import compiler/src/ast.flow change with it. Accepted 956 of the corpus, 954 text-equal to Python at 84806b0, 0 text failures.
With FLOWC_MLIR_GPU=1, the counterpart of Python's --mlir-gpu, the @gpu kernels the host module leaves out become gpu.module @flow_kernels, as mlir_gpu_codegen.py writes it: gpu.func per kernel with the SPIR-V entry point ABI, the gpu_* id intrinsics as gpu.block_id/block_dim/thread_id, memref loads and stores, scf.if and scf.for with loop-carried locals, and gpu.barrier. The GPU generator numbers each kernel's values from %1, so the normalizer starts value names over at each gpu.func. parity_mlir.sh compares gpu_* fixtures in GPU mode too, and in --python mode every accepted program with an @gpu kernel. 5 of 5 such corpus programs Python builds match; the other 3 fail in Python as well.
A type alias lowers as its base type and a unit as f64, as Python's _resolve_type_alias resolves TypeAliasDecl and DistinctTypeDecl (UnitDecl) in flow_type_to_mlir. Name-based checks (unsigned, struct lookup) still see the alias name, as Python's do. Accepted 968 of the corpus, 966 text-equal to Python at 84806b0, 0 text failures.
MLIR corpus rerecorded with --write-golden 84806b0 (1040 programs, 18 fixtures); the parse coverage floor rises to 2480.
godofecht
force-pushed
the
selfhost/mlir-emit-3
branch
from
September 29, 2026 20:12
104551a to
eed32fd
Compare
This was referenced Sep 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Builds on #1041 (branch
selfhost/mlir-emit-2, not merged yet): its commits are the first seven here, and this PR's own work starts at0f5becc9. Once #1041 merges, this branch rebases onto main. Plan:docs/design/mlir-in-flow.md.What changes
The Flow MLIR emitter (
compiler/src/mlirgen.flow,FLOWC_EMIT=mlir) covers the rest of slice 4, slices 5 and 6, attributes, and the GPU dialect text of slice 10, each step text-equal to the Python generator.!llvm.struct<(!llvm.ptr, i64)>(parameters, locals,.len, indexing and stores, slices of pointers, memrefs and spans, borrows at call sites),&[T]and[T; N],[v; N]written out N times, array literals as memref values,array<T>(n), thevector<4xT>rewrite of single-store memref loops, list patterns, and consts Python folds (cast-wrapped, negated, integer expressions; zero otherwise). A call to an undeclared name isfunc.call @name ... -> i32as Python writes it.Name { ..base, f: v }: new in the Stage-A parser, marked by a parse-onlyAST_RECORD_UPDATEthat the typecheck and MLIR emitter pass over and cgen and jsgen refuse with a located message.mlir_closure_parity.py,mlir_nested_closure_parity.py): the fat{code, env}closure, lifted@lambda_Nfunctions with sorted free-name captures in a malloc'd environment, calls through closure locals and parameters,__flow_callback_adapters for named functions, function names as values.@_flow_effects_init,handleinstall and restore, effect calls resolved to the handling capability. Other method calls lower with the receiver first. Variadic externs and the printf and scanf families arellvm.funcvarargs; overloads are all emitted.[dependencies]package imports throughflow_packages/.@gpukernels and mode guards (@hot,@jit,@only(...), ...) leave the host module as in Python.FLOWC_MLIR_GPU=1(Python's--mlir-gpu) emitsgpu.module @flow_kernels.@cInclude,@cEmbedand@cImportstay refused: Python rejects the first two in all 38 corpus programs, and the third reads C headers.parity_mlir.sh: fixturesspans_data,closures,effects,record_update,gpu_kernelswith goldens;gpu_*fixtures are also checked in GPU mode, and--pythoncompares every accepted program with an@gpukernel in GPU mode too. The normalizer starts value names over at eachgpu.func, since the GPU generator numbers each kernel from%1. Corpus digests re-recorded (948 programs).[v; N]out N times).Parity
Against the Python generator at
84806b0d, every.flowunderexamples/,tests/,lib/,benchmarks/andcompiler/fixtures/, macOS, Homebrew LLVM 22.tests/lang(of 183)@gpukernels and mode guardsAccepted programs beyond the text-equal ones fail in Python itself (a parser crash, and an
@gpukernel using avectype Python cannot parse). No program builds on one path only. The run columns come from one run of the final text-equal set through both MLIR paths, counted over each commit's recorded corpus and fixtures. GPU mode: 5 of 5 corpus programs whose kernels Python lowers are text-equal; Python fails on the other 3 and flowc refuses them.Of the refusal groups this work targeted, none of
effect or capability(51),forward declaration(27) orfunction, span or fixed-array type(27) is left as a refusal reason; programs from those groups that still refuse stop on something else (a typecheck error, a tensor type). Of the 36 unresolved imports, 1 now resolves; Python fails on the other 35 as well (17 modules or packages missing from the checkout, 18 proof-layer programs). Of the 47@gpu/C-interop refusals, the 8 that Python builds are@gpu, and 7 are now text-equal (the eighth has a generic function); the other 39 fail in Python.Largest refusals left
Leaving aside proof programs (902, which Python rejects) and files flowc cannot parse (169): C-interop attributes (38, Python rejects all), unresolved imports (35, Python fails on all), Tensor-shaped struct fields (18) and Tensor arguments to struct-returning calls (8), span borrows Python rejects (15),
tensor/vector/memreftype names (14), typecheck failures (13), names the emitter cannot place (12), generic functions (12),while trueloops Python rotates (11), expression statement forms (8) andparallel for(7).Verification (local, macOS)
bootstrap_from_c.sh --verify,self_host_full.sh,roundtrip.sh,parse_coverage.sh --check,fmt_check.sh --check,corpus_parity.sh --checkpass.parity_mlir(golden: 18 of 18 fixtures text and run, 1 GPU-mode fixture, 948 corpus programs),parity_lowering,parity_effects,parity_proofs,parity_field_dsl,parity_dynamics_dsl,parity_flow_blockspass.parity_shader_dslpasses except its Metal compile step (no Metal toolchain on this Mac).flow run --backend=mlirbuilds and runseffects.flow,closures.flow,spans_data.flowandrecord_update.flowwithpythonandpython3replaced by failing stubs.Python behaviour copied, and issues opened
The emitter reproduces these for text parity; the doc lists them, and the real bugs are filed so both generators can change together:
func.funcbodies, and overloads share one symbol.len(span)calls an undeclared@len;&[T; N]parameters are declared!llvm.ptrwhile the body treats them as spans.@gpukernels,-xisx - 0,!xuses an immediate operand, andelifbranches are dropped.ptrtoint); a lambda that prints fails in Python;elifconditions and slices are not searched for captures.memref<16xi8>.Also copied without an issue:
[v; N]needs a literal N, the vector rewrite casts bounds as i32 and always says "f32" in its comment,array<u8>(n)spellsmemref<?xu8>, nested arrays becomememref<4xmemref<3xi32>>, and a void lambda returnsllvm.mlir.undef : (). Arithmetic on structs with float members (dual numbers) is refused because the emitter does not reproduce Python's float ops on struct types.