Repository navigation
MLIR backend: correct against the C backend, with the mlir_vs_c gate - #1093
Merged
Merged
Conversation
Builds every tracked program with a main through `flow compile` and `flow compile --backend=mlir`, runs both with a timeout, and compares exit code and stdout. The C backend is the reference; programs it does not build are counted apart. Failures are clustered by their first diagnostic. Builds have a timeout too (--build-timeout, default 300 s): one example used to emit 100 MB of MLIR that llc never finished. The floor is the emitter as #1072 left it: 629 of the 1130 programs the C backend builds run the same through MLIR (1465 programs with main).
The emitter no longer copies the retired Python generator's bugs for text parity. The contract is now MLIR that verifies and runs with the C backend's output (compiler/scripts/mlir_vs_c.sh). Issues: - #1059: a forward declaration emits nothing beside its definition, and a declared-only function is a `func.func private` declaration. Overloads get the C backend's mangled symbols (name_T1_T2) and calls pick the overload the argument types fit. - #1060: len() of a span reads its length field; len() of a fixed array, a dynamic array and a string is lowered too. A span parameter with an extent is the {ptr, len} struct its body reads. - #1061: in @gpu kernels, -x is 0 - x with a materialized zero, !x flips a bool or tests an integer against zero, and elif is a nested scf.if. - #1062: lambdas capture only the enclosing function's locals; consts, statics, functions and builtins (println included) resolve by name. Slices and elif conditions are searched for captures. `let f = |x| ...` gets the lambda's function type, so calls through it are typed. - #1063: consts whose value is not a literal (float expressions, other consts, struct literals) are evaluated at each use instead of being zero. A record update names its struct. An unknown type name or a capability-typed value is refused instead of becoming memref<16xi8>. Behaviour the C backend defines and the emitter now follows: - println/print: %s for strings, %lld/%llu for 64-bit, %u for u32, %f for floats, space-separated arguments; string literals holding `%`. - Integer literals above the i32 range are i64 (u64 above i64); float literals are f64, written so MLIR reads them (1e9 no longer fails). - A bool widens with extui. Branch conditions of any scalar type test != 0. A returned value is cast to the return type. - String `+` (numbers and bools formatted as C does), string `==` by content, string match patterns, pointer arithmetic scaled by the pointee. - Nested and literal fields of struct patterns are checked, not ignored; a match falls through to llvm.unreachable only when every arm returns. - `a * b + c` is one math.fma, as clang contracts it, so floating point results agree to the last bit. - Runtime checks under FLOWC_CHECKS=1 (flow_to_mlir.sh default): integer division by zero, shift range, and reads of sized arrays and spans abort with `flow: <what>`, as the C backend's do. - defer runs on break and continue out of nested blocks; elif conditions see the locals as before the if; statics fold negative and constant initializers; `[v; N]` takes any constant N and fills with a loop; short array literals zero the rest; arrays over 64 KiB use the heap. - libc and <math.h> calls without a declaration are declared with their C signatures; a Flow function named like one (sin in math.flow) yields to libc as the C backend's header does. Other undeclared callees are declared as C would implicitly. - @cInclude/@cImport are accepted; @cembed C is written beside the MLIR (FLOWC_CEMBED_OUT) and linked by `flow compile --backend=mlir`. - C string escapes (octal, hex, \e) are decoded into MLIR strings. - Removed: Python's string interpolation (the C backend prints the literal), the module-wide array-name cache, the arguments evaluated last to first for struct-returning callees. parity_mlir.sh gains --record (goldens from flowc) and links with the clang next to mlir-translate. Goldens re-recorded: every fixture's text changes with the string escapes and literals; run output changes are the fixes above (consts_calls: 64-bit literal; defer_addr: defer on break; imports_statics and print_logic: string println; spans_data: a folded float const). New fixture gpu_ops covers #1061.
- sizeof<T>() (monomorphized to sizeof_T) is the size of T as i64, from the offset of element 1 of a T array at null. - flow_panic(msg), the trap a flow invariant lowers to, writes the message to stderr and exits 1; i32_to_f32, declared or not, is a conversion. - `str` is the string type, as in the C backend. - A lambda capturing a loop index stores it as i64 (index has no LLVM storage type). - The linalg.generic rewrite of `out[i] = a[i] op b[i]` over pointers is gone: its unrealized casts from !llvm.ptr to memref never lowered. The loop lowers as any other. corpus.txt re-recorded: 17 programs change text (the pointer loops and the new lowerings), one more is accepted.
math.fma needs the math-to-llvm conversion, which the pass pipelines of `flow jit`, `ml` and the optimizer do not all run; llvm.intr.fma lowers in every pipeline. The parity_mlir fixture text changes accordingly. tests/mlir_commands goldens re-recorded from flowc for the cases the emitter fixes changed: the MLIR, LLVM IR and optimizer text of the fixtures, jit_spans (its folded float const now prints 3.000000) and audio_offline (the last digit now matches the C build: R=0.116318).
…ompares - An array returned by value is copied to the heap (memref.copy into a memref.alloc), since the callee's storage is an alloca; a sized array local held as an !llvm.array is copied with memcpy into the heap memref of the return type. - Assigning to a sized array local copies into its storage (memcpy), as a C array assignment does, instead of rebinding the name. - array<T>(n) zeroes its elements, as the C backend's calloc. - `expect c` writes `expect failed (line N)` to stderr and exits 1 when c is false; it was evaluated and ignored. - Float `!=`, and the truth test of a float, are unordered (une): NaN != NaN holds, as in C. - i128 operands combine as i128 (they were narrowed to i64). - A float literal fits an f32 overload as well as an f64 one. corpus.txt and spans_data.mlir re-recorded (spans_data builds arrays with array<f32>(8), which now zero-fills).
- A `ui_row(args) { body }` layout block calls ui_row_begin and ui_row_end
around its body, with the implicit `_ui_state` (a module global, null at
start) or the pointer or array its first argument names, as the C
backend lowers it. ui_layout_bind(p) sets `_ui_state`. The body alone
used to be emitted.
- `let buf: array<u8, N>` with no initializer is a memref of the array
type. It was spelled memref<Nxu8>, which is no MLIR type.
data.mlir and corpus.txt re-recorded for the uninitialized array.
An array literal with more elements than the declared length stored the extra elements past the end of the alloca, over neighbouring locals. C drops excess initializers; the emitter now stores only the declared length. compiler/src/mono_usage.flow has 198-element literals for array<u8, 192>, which broke every tests/lang *_port test that imports it. corpus.txt re-recorded: 15 programs import such literals.
…nd functions as values - A program's own allocator stub (`malloc(size: i32) -> i32`, a `free` returning a value) is its own function under __flowc_libc_<name>, as the C backend decides; calls no longer reach libc's malloc and free with its arguments. Closure environments always use libc's malloc. - A field read on a struct pointer a call or a cast returns reads through the pointer (#1065 in the C backend). - A sized array held as an !llvm.array passed to a memref parameter is copied into a memref before the call and back after it, so the callee sees and changes the caller's elements. - A function returned from, or bound to a local of, a function type is its closure adapter. corpus.txt re-recorded: 6 more programs are accepted, 6 change text.
The next group of causes from the MLIR-vs-C gate: - `xs |> sort ...` and `xs |> find(t)` lower to a stable merge sort and a linear search with the C backend's three-way compare (strcmp, IEEE totalOrder, signed or unsigned order), keys, descending and unique. - `+ - * /` and unary minus on Dual, and the Tensor operators, call the overloads the C backend calls. The tensor_add intrinsic applies only when the program does not define tensor_add. An f64 argument now prefers an f32 overload over a struct one. - The proof layer is erased as for C; proof-only files emit an empty module, so 853 examples/verify and lib/verify files join the corpus. - @max_iterations(N) counts iterations and aborts past the bound. - `v in arr` over a sized array, pointer difference in elements, and a value function whose end is reachable returns zero. - A field read through a mutable pointer local uses its current value (the tools and driver mains failed dominance). - Rows of a nested array literal are heap copies, so returned nested arrays keep their values. - Any expression statement is evaluated. Goldens: corpus.txt digests change for the programs above and gain the newly accepted ones. mlir_data, mlir_spans_data and llvm_spans_data are re-recorded; their text trailed the earlier array<T>(n) zero-fill change.
- A contracted a * b + c is llvm.intr.fmuladd, the intrinsic clang emits for the C build. LLVM then fuses or splits it the same way for both builds: the loop vectorizer splits it in an in-order reduction, which llvm.intr.fma forbade (psychstats lognormal sigma and mna_dc differed in the last bit). - An unsigned integer converts to float with uitofp, and a float cast to an unsigned type with fptoui, as in C. - The string table holds 16384 constants in a 1 MiB pool, so the compiler's own main.flow builds through MLIR. Goldens: every fixture and command golden with a multiply-add changes llvm.intr.fma to llvm.intr.fmuladd (arith, arrays, closures, spans_data, structs; the mlir_, llvm_ and opt_ commands). corpus.txt digests change for the programs that hold one.
The design page records the new contract, the gate's numbers before and after (629 to 1002 of 1131 programs run the same), what changed, and what the gate still reports. The copied Python quirks it listed are removed or marked fixed.
Nine programs that main changed since the branch point (the gif encoder, python embedding, parser forms, prefix deref) emit different MLIR.
On the branch rebased onto main, 1018 of the 1156 programs the C backend builds run the same through MLIR (629 of 1130 at #1072). The floor for Darwin is 1013, 5 under the run. The design page's table takes these numbers.
# Conflicts: # compiler/bootstrap/flowc_stage_a # compiler/bootstrap/flowc_stage_a.c # compiler/fixtures/mlir/corpus.txt
godofecht
added a commit
that referenced
this pull request
Oct 1, 2026
The emitter writes a newline in an MLIR string constant as \0A since #1093. mlir_hello and mlir_run_hello were recorded before it.
godofecht
added a commit
that referenced
this pull request
Oct 1, 2026
…#1095) The flow command line is a Flow program (tools/flow_cli). ./flow is a short sh stub that builds and runs it. The 4,311-line bash flow-driver is deleted, and the scripts and tools that called it now call the CLI. tests/cli/run.sh holds the CLI to goldens for every subcommand, per OS. It passes 149/149 on macOS and on Linux CI. The Linux exit-code and stderr goldens came from the bash driver; the Linux stdout goldens were recorded on the CI runner, and in that run no exit code or stderr differed from the bash driver. Carried over while rebasing onto main: - #1093's @cembed linking on the MLIR path, which #1093 added to flow-driver, is now in tools/flow_cli's flow_link_mlir_ll. - The two MLIR CLI goldens follow #1093's string escape (\0A). - The MLIR corpus digest for test_c_import_dirs follows #1098. corpus_parity compares only the build of nine programs whose run depends on machine load: concurrency examples and nbody under seven parallel jobs with a 10s limit, and three whose Python golden run timed out. They are listed in compiler/corpus_parity/timing.txt. The floor stays 1033; this tree scores 1038. The flow-driver references that remain are historical git archive calls of old revisions (corpus_parity --python, the gpu parity reference), docs that describe the deletion, and two guarded lines in packaging/homebrew/Formula/flow.rb that install flow-driver only if it exists.
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.
With the Python generator deleted (#1072), the MLIR emitter no longer copies its text. The contract is now the C backend's: the MLIR verifies, and the program built from it prints what the C build prints and exits with the same code.
The gate
compiler/scripts/mlir_vs_c.shbuilds every tracked program with amainthroughflow compileandflow compile --backend=mlir. It runs both with stdin closed and a timeout, then compares exit code and stdout. Programs the C backend cannot build are counted separately. Output that changes between two runs of the same build is not compared (compiler/mlir_vs_c/nondet.txt, plus a second-run check). Causes are clustered and ranked. The floor lives incompiler/mlir_vs_c/floor.txt, 5 under the recorded run, and--checkfails below it.macOS, LLVM 22:
mainIssues
lenof spans, arrays and strings. Sized span parameters are spans.@gpunegation and!with real operands.elifis emitted.elifconditions are searched. Untyped lambda bindings and void lambdas are fixed.memref<16xi8>.The quirks listed in
docs/design/mlir-in-flow.mdare fixed too: elif conditions seeing then-arm assignments, statics,[v; N]with only a literal N, vector bounds, nested arrays, the void lambda undef, and untypedlet x = e.Causes the gate surfaced
+,==and match on contents work.a * b + cbecomesllvm.intr.fmuladd, the intrinsic clang emits, so LLVM fuses or splits it the same way for both builds.FLOWC_CHECKS) for division, shifts and sized reads.deferruns on break and continue.@max_iterations.|> sort/|> findas a stable merge sort with the C three-way compare.in. Pointer difference.@cEmbedC is linked beside the MLIR.expect. ui layout blocks.compiler/src/main.flow),tools/*/main.flowanddriver.flownow build and run the same through MLIR.What is left is listed under "Known gaps" in the design doc. Much of it is C-header-only types (
pthread_*,c64),implblocks, and programs whose C reference is itself undefined: signed-overflow LCGs, the dynamics DSL's 32-slot GA history written for 40 generations, and out-of-bounds reads.Goldens
parity_mlir.shgains--recordand remains the text regression gate. Each golden change is in the commit of the fix that caused it:llvm.intr.fmatollvm.intr.fmuladd.corpus.txtnow has 2405 accepted programs, up from 1252 at the deletion. That includes 853 proof-only verify files that now emit an empty module.tests/mlir_commands: goldens re-recorded with their fixes (for example jit_spans now prints3.000000, and audio_offline R=0.116318 matches C).Base
The branch is rebased on 366baa2 (#1085). Main has since taken #908, which also edits
compiler/src/mlirgen.flow, and the bootstrap C will conflict as usual. Merging needs a rebase, the #908 change folded into the emitter, andbootstrap_from_c.sh --regenagain.Gates
bootstrap_from_c.sh --verify, self_host_full.sh, roundtrip.sh, parse_coverage.sh --check, fmt_check.sh --check, tests/cgen/run.sh, flow test-lang, corpus_parity.sh --check, parity_typecheck.sh --check, typecheck_rules.sh, every parity_*.sh (the parity_shader_dsl Metal step fails only for the missing Metal toolchain), tests/mlir_commands/run.sh 72/72, and mlir_vs_c.sh.
Fixes #1059
Fixes #1060
Fixes #1061
Fixes #1062
Fixes #1063
Fixes #1069