Skip to content

Fix MLIR.jl on Julia 1.13: use MLIR_jll.mlir_c directly + small bugfixes - #88

Merged
mofeing merged 4 commits into
JuliaLLVM:mainfrom
gbaraldi:fix-julia-1.13-ccall
Oct 19, 2026
Merged

mofeing merged 4 commits into
JuliaLLVM:mainfrom
gbaraldi:fix-julia-1.13-ccall

Conversation

@gbaraldi

Copy link
Copy Markdown
Contributor

Summary

Three independent fixes, the first of which is required to load MLIR.jl on Julia 1.13:

  1. Use MLIR_jll.mlir_c directly as the @ccall library name. Julia 1.13 tightened the @ccall macro to reject (MLIR_C_PATH[]).fn(...)-style library forms (TypeError: in ccall library name, expected Symbol, got a value of type Expr). Drops the now-removed MLIR_C_PATH ScopedValue and points @ccall straight at MLIR_jll's JLLWrappers-managed bare-identifier global. See commit message on 32ee56c for details and reproducer.
  2. mark_donate returns the donated object and adds a missing 1-arg overload. Without it, push!(::Region, ::Block) and several Operation.jl internals fail.
  3. Import NamedAttribute in src/Dialects/Dialects.jl — operandsegmentsizes/resultsegmentsizes reference it without it being in scope.

Reproducers

#1 — @ccall syntax on Julia 1.13 (no MLIR.jl needed)

const LIBC = Ref{String}("libc.so.6")
@ccall (LIBC[]).getpid()::Int32    # OK on 1.12; "expected Symbol, got Expr" on 1.13+

Loading MLIR.jl on Julia 1.13 fails at precompile because every auto-generated @ccall (MLIR_C_PATH[]).fn(...) site triggers this.

#2 — mark_donate MethodError

using MLIR.IR
activate(Context())
push!(Region(), Block())   # MethodError: no method matching mark_donate(::Block)

#3 — NamedAttribute UndefVar

Any op builder that constructs an operand_segment_sizes attribute via Dialects.operandsegmentsizes errors with UndefVarError: NamedAttribute not defined in MLIR.Dialects.

Behavioural change

Commit 32ee56c drops the MLIR_C_PATH indirection:

If preserving the MLIR_C_PATH ScopedValue is desired, the alternative is a dlsym-cached function-pointer form (@ccall \$(_dlsym(:fn))(args)::ret) emitted by the generator — happy to do that instead if preferred, but it's a bigger generator change for a feature that isn't exercised by tests or docs.

Files

  • bindings/wrap.toml: library_name = "MLIR_C_PATH[]" → library_name = "mlir_c"
  • src/MLIR.jl: drop MLIR_C_PATH, import mlir_c from MLIR_jll
  • src/API/API.jl: per-version submodules using ...MLIR: mlir_c
  • src/API/{14..21}/libMLIR_h.jl: text-equivalent of regenerating via make-api.jl after the wrap.toml change (substitution is purely MLIR_C_PATH[] → mlir_c). Verified the substitution is exhaustive by grep -c "MLIR_C_PATH" src/API/*/libMLIR_h.jl → 0.
  • src/IR/debug.jl: mark_donate 1-arg + return value
  • src/Dialects/Dialects.jl: import NamedAttribute

Test plan

  • using MLIR precompiles + loads on Julia 1.12 (libLLVM 18.1.7, MLIR_jll 18.1.7+4)
  • using MLIR advances past the @ccall precompile error on Julia 1.13 (a separate LazyLibrary issue in MLIR_jll's JLLWrappers compat surfaces next, but is outside this PR)
  • push!(::Region, ::Block) works
  • Dialect ops using operand_segment_sizes construct without UndefVarError

🤖 Generated with Claude Code

gbaraldi and others added 3 commits May 27, 2026 19:26
Julia 1.13 tightened the `@ccall` macro to require the library form
be a bare identifier, `Symbol`, or literal `String`. The previous form
`@ccall (MLIR_C_PATH[]).xxx(...)` (with `MLIR_C_PATH::ScopedValue{String}`,
introduced in JuliaLLVM#71) now errors at parse time with
"TypeError: in ccall library name, expected Symbol, got a value of type Expr"
and prevents the package from loading.

Reproducer (no MLIR.jl needed):

    const LIBC = Ref{String}("libc.so.6")
    @CCall (LIBC[]).getpid()::Int32   # OK on 1.12; errors on 1.13+

Switch the auto-generated `@ccall` library binding from the now-removed
`MLIR_C_PATH` indirection to `MLIR_jll.mlir_c` directly. `mlir_c` is a
JLLWrappers-managed bare-identifier global whose path is initialized at
JLL load time and whose form `@ccall mlir_c.fn(...)` is accepted across
every supported Julia version.

This drops the `LocalPreferences.toml`-based `MLIR_C_PATH` override and
the (unused) per-task `ScopedValue` override. Users who want a custom
libMLIR-C can override `MLIR_jll`'s artifact via Overrides.toml or
`Pkg.develop(MLIR_jll)` — the standard JLL-override path.

Per-task `MLIR_VERSION` override remains a `ScopedValue` and is
unaffected — that's the more useful capability and continues to work.

Changes:
- bindings/wrap.toml: `library_name` = "MLIR_C_PATH[]" -> "mlir_c"
- src/MLIR.jl: drop `MLIR_C_PATH`, import `mlir_c` from MLIR_jll
- src/API/API.jl: per-version submodules import `mlir_c` instead of `MLIR_C_PATH`
- src/API/{14..21}/libMLIR_h.jl: equivalent to running `make-api.jl` after
  the wrap.toml change — `MLIR_C_PATH[]` -> `mlir_c` throughout.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`Region.jl:65`, `Operation.jl:291`, and `Operation.jl:304` all call
`mark_donate(obj)` (single-arg) and pass the return value as the donated
object to a libMLIR C-API call (e.g. `mlirRegionAppendOwnedBlock(region,
mark_donate(block))`).

Before this change `debug.jl` only defined the 2-arg `mark_donate(new_owner, obj)`,
which calls `mark_dispose(obj)` — and `mark_dispose` returns `nothing`. So:

  - On any call site, `Region.jl:65` etc. would fail with a MethodError
    because the 1-arg form was undefined.
  - If the 1-arg form had existed (or been added) returning `nothing`, the
    consuming C API call would convert `nothing` -> C_NULL and either fail
    its own validation or crash.

Add the missing 1-arg `mark_donate(obj)` overload and change both
overloads to return `obj` after the dispose tracking. This matches the
underlying semantics ("hand ownership over but the handle remains
syntactically usable for one more call").

Reproducer:

    using MLIR.IR
    activate(Context())
    blk = Block()                    # constructs a Block
    push!(Region(), blk)             # -> MethodError before this fix
                                     # -> succeeds after

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`operandsegmentsizes` and `resultsegmentsizes` in src/Dialects/Dialects.jl
construct `NamedAttribute(...)` but the parent `MLIR.IR.NamedAttribute`
name was never brought into scope, so any call to either function fails
with `UndefVarError: NamedAttribute not defined in MLIR.Dialects`.

This surfaces immediately for any dialect op whose builder needs
`operand_segment_sizes` (e.g. `llvm.intr.assume` constructed via
`IR.create_operation` with an explicit `operand_segment_sizes` attr).

Add the missing `using ..MLIR.IR: NamedAttribute`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gbaraldi added a commit to gbaraldi/MLIRKernels that referenced this pull request May 27, 2026
…-process; multi-MLIR-version support

Replaces `Reactant.MLIR.IR` / `Reactant.MLIR.Dialects` with vanilla
`MLIR.jl` (1.0.x main, dev'd against gbaraldi/MLIR.jl#fix-julia-1.13-ccall
pending JuliaLLVM/MLIR.jl#88). Drops the `mlir-opt` / `mlir-translate`
shell-out: pipelines now run in-process via `MLIR.IR.PassManager` and
LLVM-IR translation via `mlirTranslateModuleToLLVMIR` + LLVM C API. clang
remains the final-codegen step for `-O2 -shared -fPIC` + libomp link.

The walker emits the same upstream MLIR dialects (no Reactant- or
EnzymeXLA-specific ops); per-MLIR-version dialect-syntax differences are
handled by `MLIR.MLIR_VERSION[]`-conditional emission in the walker and a
version-aware textual-pipeline builder (`_wrap_pass` nests passes
anchored at func::FuncOp under `func.func(...)`, `_pass_available`
filters passes not yet registered through libMLIR-C on the current
version).

Concrete version-conditional fixes (verified against MLIR 18 on Julia
1.12 and MLIR 20 on Julia 1.13):
  - `vector.multi_reduction.reduction_dims` — `[N : i64]` (I64ArrayAttr)
    on MLIR 18, `array<i64: N>` (DenseI64ArrayAttr) on MLIR 19+.
  - `memref.atomic_rmw kind` enum integer codes — reordered between
    MLIR 18 and 20, `xori` removed in 20; per-version table + the
    walker still routes `:xor` through the generic CAS path.
  - `memref.assume_alignment` result form — MLIR 18 is result-less, MLIR
    21+ returns the memref; emit accordingly and bind downstream Value.
  - `vector.step` — native op on MLIR 19+; on MLIR 18 emit
    `arith.constant dense<[0..N-1]>` via textual parse (typed
    `DenseElementsAttribute(::Vector{Int64})` overload builds a
    TensorType shape that can't retarget at a VectorType).
  - `vector.insert_strided_slice` kwarg — both MLIR 18 and 20 bindings
    use `res=`, not `result=` (pre-existing walker typo, surfaced now
    that the pipeline gets further on MLIR 20).

Pass pipeline order on MLIR 19+:
  1. `convert-math-to-llvm`  — math ops with LLVM intrinsics (incl.
     `math.rsqrt` → `1.0 / llvm.intr.sqrt`). MUST run before libm,
     otherwise libm emits a `rsqrtf` call to a function that doesn't
     exist in standard libm, dlopen fails at launch.
  2. `convert-math-to-libm`  — picks up the remainder (e.g. `math.tanh`
     on MLIR 20 has no LLVM intrinsic registered). Scalarizes vector
     forms via `vector.extract` per lane + scalar libm call.
  3. `func.func(lower-vector-multi-reduction)` — decomposes
     `vector.multi_reduction` into `vector.reduction` + assembly that
     `convert-vector-to-llvm` can match. Skipped on MLIR 18 (not
     registered through libMLIR-C).
  4. `convert-vector-to-scf` → `convert-vector-to-llvm` — must precede
     `convert-openmp-to-llvm` (which rewrites region argument types to
     `!llvm.array<...>`, after which residual vector ops can't be
     matched), AND must follow `convert-math-to-libm` (to lower the
     `vector.extract/insert` ops the libm scalarization emits).
  5. omp → llvm → cf → memref → arith → func → cf → ub →
     reconcile-unrealized-casts.

Other changes:
  - `compile_module_to_so(mod, mlir_ctx; ...)`: launches now take the
    `IR.Module` directly, skipping the textual round-trip (which doesn't
    round-trip cleanly through MLIR 18's printer/parser for ops like
    `vector.multi_reduction`).
  - `fresh_context()`: creates a `Context` with all upstream dialects
    pre-registered via `mlirRegisterAllDialects` + `mlirRegisterAllLLVMTranslations`
    + `load_all_available_dialects` (matches what Reactant's
    `ReactantContext` did, minus the EnzymeXLA dialects).
  - `@with_context` / `@with_module` / `@with_block` reimplemented as
    activate/deactivate try/finally wrappers (MLIR.jl exposes the
    primitives but not the macro trio).
  - `MLIR_jll` compat set to `"18, 19, 20"`: omits v21 which the
    resolver picks unusably on Julia 1.13 (Pkg ignores its
    `libLLVM_jll = "21.1.2-21"` compat against stdlib libLLVM_jll;
    JLLWrappers then returns `is_available() == false` at runtime).

Test status:
  - Julia 1.13 + MLIR_jll v20.1.8: 232/232 tests pass.
  - Julia 1.12 + MLIR_jll v18.1.7: ~218/232 pass, 14 errored / 1 fail —
    same as pre-swap baseline. Remaining gaps are MLIR-18-specific
    (lower-vector-multi-reduction not registered through libMLIR-C,
    `math.tanh` LLVMTranslationDialectInterface missing) and self-heal
    on Julia 1.13+.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gbaraldi added a commit to gbaraldi/MLIRKernels that referenced this pull request May 29, 2026
…-process; multi-MLIR-version support

Replaces `Reactant.MLIR.IR` / `Reactant.MLIR.Dialects` with vanilla
`MLIR.jl` (1.0.x main, dev'd against gbaraldi/MLIR.jl#fix-julia-1.13-ccall
pending JuliaLLVM/MLIR.jl#88). Drops the `mlir-opt` / `mlir-translate`
shell-out: pipelines now run in-process via `MLIR.IR.PassManager` and
LLVM-IR translation via `mlirTranslateModuleToLLVMIR` + LLVM C API. clang
remains the final-codegen step for `-O2 -shared -fPIC` + libomp link.

The walker emits the same upstream MLIR dialects (no Reactant- or
EnzymeXLA-specific ops); per-MLIR-version dialect-syntax differences are
handled by `MLIR.MLIR_VERSION[]`-conditional emission in the walker and a
version-aware textual-pipeline builder (`_wrap_pass` nests passes
anchored at func::FuncOp under `func.func(...)`, `_pass_available`
filters passes not yet registered through libMLIR-C on the current
version).

Concrete version-conditional fixes (verified against MLIR 18 on Julia
1.12 and MLIR 20 on Julia 1.13):
  - `vector.multi_reduction.reduction_dims` — `[N : i64]` (I64ArrayAttr)
    on MLIR 18, `array<i64: N>` (DenseI64ArrayAttr) on MLIR 19+.
  - `memref.atomic_rmw kind` enum integer codes — reordered between
    MLIR 18 and 20, `xori` removed in 20; per-version table + the
    walker still routes `:xor` through the generic CAS path.
  - `memref.assume_alignment` result form — MLIR 18 is result-less, MLIR
    21+ returns the memref; emit accordingly and bind downstream Value.
  - `vector.step` — native op on MLIR 19+; on MLIR 18 emit
    `arith.constant dense<[0..N-1]>` via textual parse (typed
    `DenseElementsAttribute(::Vector{Int64})` overload builds a
    TensorType shape that can't retarget at a VectorType).
  - `vector.insert_strided_slice` kwarg — both MLIR 18 and 20 bindings
    use `res=`, not `result=` (pre-existing walker typo, surfaced now
    that the pipeline gets further on MLIR 20).

Pass pipeline order on MLIR 19+:
  1. `convert-math-to-llvm`  — math ops with LLVM intrinsics (incl.
     `math.rsqrt` → `1.0 / llvm.intr.sqrt`). MUST run before libm,
     otherwise libm emits a `rsqrtf` call to a function that doesn't
     exist in standard libm, dlopen fails at launch.
  2. `convert-math-to-libm`  — picks up the remainder (e.g. `math.tanh`
     on MLIR 20 has no LLVM intrinsic registered). Scalarizes vector
     forms via `vector.extract` per lane + scalar libm call.
  3. `func.func(lower-vector-multi-reduction)` — decomposes
     `vector.multi_reduction` into `vector.reduction` + assembly that
     `convert-vector-to-llvm` can match. Skipped on MLIR 18 (not
     registered through libMLIR-C).
  4. `convert-vector-to-scf` → `convert-vector-to-llvm` — must precede
     `convert-openmp-to-llvm` (which rewrites region argument types to
     `!llvm.array<...>`, after which residual vector ops can't be
     matched), AND must follow `convert-math-to-libm` (to lower the
     `vector.extract/insert` ops the libm scalarization emits).
  5. omp → llvm → cf → memref → arith → func → cf → ub →
     reconcile-unrealized-casts.

Other changes:
  - `compile_module_to_so(mod, mlir_ctx; ...)`: launches now take the
    `IR.Module` directly, skipping the textual round-trip (which doesn't
    round-trip cleanly through MLIR 18's printer/parser for ops like
    `vector.multi_reduction`).
  - `fresh_context()`: creates a `Context` with all upstream dialects
    pre-registered via `mlirRegisterAllDialects` + `mlirRegisterAllLLVMTranslations`
    + `load_all_available_dialects` (matches what Reactant's
    `ReactantContext` did, minus the EnzymeXLA dialects).
  - `@with_context` / `@with_module` / `@with_block` reimplemented as
    activate/deactivate try/finally wrappers (MLIR.jl exposes the
    primitives but not the macro trio).
  - `MLIR_jll` compat set to `"18, 19, 20"`: omits v21 which the
    resolver picks unusably on Julia 1.13 (Pkg ignores its
    `libLLVM_jll = "21.1.2-21"` compat against stdlib libLLVM_jll;
    JLLWrappers then returns `is_available() == false` at runtime).

Test status:
  - Julia 1.13 + MLIR_jll v20.1.8: 232/232 tests pass.
  - Julia 1.12 + MLIR_jll v18.1.7: ~218/232 pass, 14 errored / 1 fail —
    same as pre-swap baseline. Remaining gaps are MLIR-18-specific
    (lower-vector-multi-reduction not registered through libMLIR-C,
    `math.tanh` LLVMTranslationDialectInterface missing) and self-heal
    on Julia 1.13+.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@Pangoraw
Pangoraw requested a review from mofeing October 16, 2026 17:34

@mofeing mofeing left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Replacement: Users who want a custom libMLIR-C.so can override MLIR_jll's artifact via Overrides.toml or Pkg.develop(MLIR_jll) — the standard JLL-override path that already works for every other JLL-backed library.

If preserving the MLIR_C_PATH ScopedValue is desired, the alternative is a dlsym-cached function-pointer form (@ccall \$(_dlsym(:fn))(args)::ret) emitted by the generator — happy to do that instead if preferred, but it's a bigger generator change for a feature that isn't exercised by tests or docs.

As we discussed at JuliaCon, this is a blocker for MLIR.jl users because most probably, each Julia package that wants to use MLIR.jl will need their own libMLIR build.

I'm accepting it because (1) the ScopedValue approach we use is bad practice here, (2) this package is not yet stable and AFAIK have no users, and (3) it's broken for Julia 1.13, but we should definitely move to a function-pointer form or sth similar.

I have a WIP branch that I started during JuliaCon but didn't find the time this last month. @gbaraldi will ask for your review hopefully soon.

tldr: merging because what we currently have no longer works, but keep in mind that this will also be refactored for sth that fits better to everyone.

@mofeing
mofeing merged commit fc01e72 into JuliaLLVM:main Oct 19, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants