From 0f0237467f4d409e7ea581ea5f1eb2f637cb959c Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 17:40:42 +0200 Subject: [PATCH 1/4] emit_into!: compile a closed set of CodeInstances into the caller's module The driver for compilers with their own interpreter (GPUCompiler.jl, Enzyme.jl), as Julia's `jl_emit_native` is for them. It takes `(ci, src)` pairs, where `src` is the CodeInfo or IRCode the caller inferred. - Every function's IR comes from the set, with its CodeInstance's return type. A callee outside the set follows `on_unsupported`: it calls native code, recorded as a fallback, or it throws. - Functions that always throw are compiled, not stubbed. - It returns each CodeInstance's jlcall and specsig entries (`CompiledFunctions`) and the `CodegenOutput`. To support this: - `CGModule` takes the IR source (`ir_source`, by default native inference) and `throwing_stubs`. - A callee whose IR the source can't provide follows the failure policy. - `CodegenConfig` gains `gcstack_arg` (specsig entries without the pgcstack, in the C calling convention) and `safepoint_on_entry`, as Julia's `CodegenParams`; GPU targets turn both off. `@cfunction` keeps the runtime's convention. The tests use an interpreter with an overlay method table: its methods are the ones compiled. They run a differential corpus through `emit_into!`, and check the specsig declarations against native code with the same `CodegenParams`, calling the C entry directly, plus missing callees and always-throwing callees. Assisted-by: Claude Code (Opus 5.5) --- NEWS.md | 6 ++ docs/src/api.md | 7 ++ src/JuliaCodegen.jl | 1 + src/cfunction.jl | 3 +- src/config.jl | 22 +++++-- src/context.jl | 16 ++++- src/emit_into.jl | 97 ++++++++++++++++++++++++++++ src/function.jl | 11 +++- src/ir.jl | 2 +- src/specsig.jl | 39 +++++++---- test/emit_into.jl | 153 ++++++++++++++++++++++++++++++++++++++++++++ test/jit.jl | 2 +- test/runtests.jl | 1 + 13 files changed, 331 insertions(+), 29 deletions(-) create mode 100644 src/emit_into.jl create mode 100644 test/emit_into.jl diff --git a/NEWS.md b/NEWS.md index 3e557ab..adf7cca 100644 --- a/NEWS.md +++ b/NEWS.md @@ -60,3 +60,9 @@ the addresses a module embeds (the tests check every module); deterministic names and object order; and the pass pipelines (`JuliaCppPipeline`, `NoPipeline`, `CustomPipeline`, `run_pipeline!`). +- `emit_into!`: compile a closed set of CodeInstances, with the sources the caller's + interpreter inferred, into the caller's module (the driver for GPUCompiler.jl and + Enzyme.jl, as Julia's `jl_emit_native`), returning each one's jlcall and specsig entries + (`CompiledFunctions`) and the `CodegenOutput`. `CGModule` takes the IR source. +- `CodegenConfig`: `gcstack_arg` (specsig entries without the pgcstack argument, in the C + calling convention) and `safepoint_on_entry`, as Julia's `CodegenParams`. diff --git a/docs/src/api.md b/docs/src/api.md index a2271f7..e5b47c0 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -31,6 +31,13 @@ JuliaCodegen.has_backend JuliaCodegen.AddrSpace ``` +## Drivers + +```@docs +JuliaCodegen.emit_into! +JuliaCodegen.CompiledFunctions +``` + ## Output and pipelines ```@docs diff --git a/src/JuliaCodegen.jl b/src/JuliaCodegen.jl index 16cc819..c946c74 100644 --- a/src/JuliaCodegen.jl +++ b/src/JuliaCodegen.jl @@ -42,5 +42,6 @@ include("specsig.jl") include("cfunction.jl") include("ir.jl") include("output.jl") +include("emit_into.jl") end diff --git a/src/cfunction.jl b/src/cfunction.jl index 20fe992..64f27a0 100644 --- a/src/cfunction.jl +++ b/src/cfunction.jl @@ -212,7 +212,8 @@ function emit_cfunction_call!(wc::FnCtx, @nospecialize(sigt), @nospecialize(decl T_size = size_type(cgm) P = T_ptr() spec = try - specsig_abi(cgm, Any[sigt.parameters...], declrt) + # (the runtime's convention, which passes the pgcstack) + specsig_abi(cgm, Any[sigt.parameters...], declrt; gcstack_arg=true) catch err err isa Unsupported || rethrow() nothing # (the jlcall convention) diff --git a/src/config.jl b/src/config.jl index 682384d..f0c96b3 100644 --- a/src/config.jl +++ b/src/config.jl @@ -2,7 +2,8 @@ """ JuliaCodegen.CodegenConfig(; target=host_target(), dialect=JuliaIR.Dialect(VERSION), - on_unsupported=:fallback, on_internal_error=:fallback) + on_unsupported=:fallback, on_internal_error=:fallback, + gcstack_arg=true, safepoint_on_entry=true) The configuration of the code generator, which generates code for the running Julia: @@ -12,7 +13,11 @@ The configuration of the code generator, which generates code for the running Ju (`JuliaIR.Dialect(VERSION; gc_barrier=:snapshot)`); - `on_unsupported`, `on_internal_error`: what happens when a function uses an unsupported construct, or the code generator fails: `:fallback` to Julia's code generator (internal - errors are reported), or `:error`. Tests use `:error` for both. + errors are reported), or `:error`. Tests use `:error` for both; +- `gcstack_arg`, `safepoint_on_entry`: as Julia's `CodegenParams`, whether entries in the + specsig convention take the pgcstack as an argument (`swiftself`; without it, they use + the C calling convention), and whether functions poll for a safepoint on entry. Targets + without Julia's runtime, like GPUs, turn both off. The facts about the running Julia's runtime are `config.runtime`, see [`RuntimeFacts`](@ref JuliaCodegen.RuntimeFacts). @@ -23,9 +28,11 @@ struct CodegenConfig runtime::RuntimeFacts on_unsupported::Symbol on_internal_error::Symbol + gcstack_arg::Bool + safepoint_on_entry::Bool function CodegenConfig(target::Target, dialect::JuliaIR.Dialect, on_unsupported::Symbol, - on_internal_error::Symbol) + on_internal_error::Symbol, gcstack_arg::Bool, safepoint_on_entry::Bool) dialect.minor == JuliaIR.Dialect(VERSION).minor || throw(ArgumentError("$dialect is not the dialect of the running Julia; code is only generated for the running Julia")) for (name, value) in ((:on_unsupported, on_unsupported), @@ -33,10 +40,13 @@ struct CodegenConfig value in FAILURE_POLICIES || throw(ArgumentError("invalid $name policy :$value; expected one of $(join(FAILURE_POLICIES, ", "))")) end - new(target, dialect, runtime_facts(), on_unsupported, on_internal_error) + new(target, dialect, runtime_facts(), on_unsupported, on_internal_error, gcstack_arg, + safepoint_on_entry) end end CodegenConfig(; target::Target=host_target(), dialect::JuliaIR.Dialect=JuliaIR.Dialect(VERSION), - on_unsupported::Symbol=:fallback, on_internal_error::Symbol=:fallback) = - CodegenConfig(target, dialect, on_unsupported, on_internal_error) + on_unsupported::Symbol=:fallback, on_internal_error::Symbol=:fallback, + gcstack_arg::Bool=true, safepoint_on_entry::Bool=true) = + CodegenConfig(target, dialect, on_unsupported, on_internal_error, gcstack_arg, + safepoint_on_entry) diff --git a/src/context.jl b/src/context.jl index 5d78ed7..9c69b15 100644 --- a/src/context.jl +++ b/src/context.jl @@ -30,12 +30,18 @@ struct Entry end """ - JuliaCodegen.CGModule(mod::LLVM.Module, config::CodegenConfig; world) + JuliaCodegen.CGModule(mod::LLVM.Module, config::CodegenConfig; world, ir_source=get_ir, + throwing_stubs=true) The state of generating code into the LLVM module `mod` (in the LLVM context it was created in): the functions emitted for method instances, the objects the code refers to, and the per-context type layouts and TBAA metadata. Names are numbered per module, so that generating the same code twice gives the same IR. + +The IR of a function comes from `ir_source(mi, world) -> (ir, rettype)`, by default +Julia's native inference ([`get_ir`](@ref JuliaCodegen.get_ir)); it throws `Unsupported` +for functions it has no IR for. With `throwing_stubs`, functions that always throw (error +paths) call their native code instead of being compiled. """ mutable struct CGModule mod::LLVM.Module @@ -51,15 +57,19 @@ mutable struct CGModule fallbacks::Vector{Pair{Core.MethodInstance,Any}} "The entry points emitted." entries::Vector{Entry} + ir_source::Any + throwing_stubs::Bool counter::Int end -function CGModule(mod::LLVM.Module, config::CodegenConfig; world::UInt=Base.get_world_counter()) +function CGModule(mod::LLVM.Module, config::CodegenConfig; world::UInt=Base.get_world_counter(), + ir_source=get_ir, throwing_stubs::Bool=true) mod.triple = config.target.triple mod.datalayout = config.target.datalayout return CGModule(mod, config, world, Layouts(config), TBAA(config.dialect), IdDict{Core.MethodInstance,FuncInfo}(), Tuple{FuncInfo,Any}[], - IdDict{Any,LLVM.GlobalVariable}(), Pair{Core.MethodInstance,Any}[], Entry[], 0) + IdDict{Any,LLVM.GlobalVariable}(), Pair{Core.MethodInstance,Any}[], Entry[], ir_source, + throwing_stubs, 0) end "A name that is unique in the module, from `prefix` and the function `f` (if any)." diff --git a/src/emit_into.jl b/src/emit_into.jl new file mode 100644 index 0000000..8c69c7e --- /dev/null +++ b/src/emit_into.jl @@ -0,0 +1,97 @@ +# The driver for compilers that infer code themselves (GPUCompiler.jl, Enzyme.jl): compile a +# closed set of CodeInstances, with the IR the caller's interpreter inferred, into a module +# the caller owns. This is what Julia's `jl_emit_native` does for them, and what it returns: +# the functions of each CodeInstance, and the objects the code refers to. + +""" + JuliaCodegen.CompiledFunctions + +The functions emitted for a CodeInstance by [`emit_into!`](@ref JuliaCodegen.emit_into!): +`func`, its entry in the jlcall convention, and `specfunc`, its entry in the specsig +convention (see [`specsig_abi`](@ref JuliaCodegen.specsig_abi)), or `nothing` when the +signature isn't handled in it. +""" +struct CompiledFunctions + func::String + specfunc::Union{Nothing,String} +end + +""" + JuliaCodegen.emit_into!(mod, codeinfos; config=CodegenConfig(), world) -> (compiled, output) + JuliaCodegen.emit_into!(cgm, codeinfos) -> (compiled, output) + +Compile the CodeInstances of `codeinfos`, `(ci, src)` pairs whose source `src` (a +`CodeInfo` or `IRCode`, optimized) the caller's interpreter inferred, into the module `mod` +(or the module of `cgm`), as Julia's `jl_emit_native` does: + +- the IR of every function comes from `codeinfos`, with the return type of its + CodeInstance; `:invoke`s of the CodeInstances (or method instances) of the set call + their functions, and any other is compiled as a call of native code (a fallback, see + `output.fallbacks`), or throws with `on_unsupported = :error`; +- functions that always throw are compiled too (no native-code stubs for error paths); +- every CodeInstance gets an entry in the jlcall convention and, where its signature is + handled, one in the specsig convention (with the configuration's `gcstack_arg`); the + functions themselves have internal linkage. + +Returns `compiled`, an `IdDict` from each CodeInstance to its +[`CompiledFunctions`](@ref JuliaCodegen.CompiledFunctions), and the module's +[`CodegenOutput`](@ref JuliaCodegen.CodegenOutput), whose `literals` the caller binds to +the objects' addresses (or relocates). The pass pipeline is the caller's to run. +""" +function emit_into!(mod::LLVM.Module, codeinfos; config::CodegenConfig=CodegenConfig(), + world::UInt=Base.get_world_counter()) + sources = codeinfo_sources(codeinfos) + cgm = CGModule(mod, config; world, ir_source=closed_ir_source(sources), throwing_stubs=false) + return emit_sources!(cgm, codeinfos, sources) +end + +function emit_into!(cgm::CGModule, codeinfos) + sources = codeinfo_sources(codeinfos) + cgm.ir_source = closed_ir_source(sources) + cgm.throwing_stubs = false + return emit_sources!(cgm, codeinfos, sources) +end + +# the IR and return type of each method instance of `codeinfos` +function codeinfo_sources(codeinfos) + sources = IdDict{Core.MethodInstance,Tuple{CC.IRCode,Any}}() + for (ci, src) in codeinfos + ci isa Core.CodeInstance || throw(ArgumentError("expected a CodeInstance, got $(typeof(ci))")) + mi = CC.get_ci_mi(ci) + haskey(sources, mi) && + throw(ArgumentError("two CodeInstances of $mi; pass one per method instance")) + ir = src isa CC.IRCode ? src : + src isa Core.CodeInfo ? CC.inflate_ir(src, mi) : + throw(ArgumentError("expected the CodeInfo or IRCode of $ci, got $(typeof(src))")) + sources[mi] = (ir, ci.rettype) + end + return sources +end + +closed_ir_source(sources) = function (mi::Core.MethodInstance, world::UInt) + src = get(sources, mi, nothing) + src === nothing && unsupported("a call of ", mi, ", which is not among the code instances to compile") + return src +end + +function emit_sources!(cgm::CGModule, codeinfos, sources) + infos = Pair{Core.CodeInstance,FuncInfo}[] + for (ci, _) in codeinfos + push!(infos, ci => get_function!(cgm, CC.get_ci_mi(ci))) + end + process_worklist!(cgm) + compiled = IdDict{Core.CodeInstance,CompiledFunctions}() + for (ci, info) in infos + name = LLVM.name(info.llvmf) + func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * name) + push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) + specfunc = try + LLVM.name(emit_specsig_wrapper!(cgm, info, "j_" * name)) + catch err + err isa Unsupported || rethrow() + nothing + end + compiled[ci] = CompiledFunctions(LLVM.name(func), specfunc) + end + return compiled, codegen_output(cgm) +end diff --git a/src/function.jl b/src/function.jl index eb89b2e..6e89723 100644 --- a/src/function.jl +++ b/src/function.jl @@ -57,7 +57,7 @@ function emit_prologue!(fc::FnCtx; safepoint::Bool=true) cfg = config(fc) fc.pgcstack = get_pgcstack!(b, fc.cgm.mod, cfg.dialect) fc.current_task = current_task!(b, cfg.runtime, fc.pgcstack) - if safepoint + if safepoint && cfg.safepoint_on_entry ptls = current_ptls!(b, cfg, fc.cgm.tbaa, fc.current_task) safepoint_poll!(b, fc.cgm.mod, cfg, fc.cgm.tbaa, ptls) end @@ -338,12 +338,17 @@ function get_function!(cgm::CGModule, mi::Core.MethodInstance) reason = "a varargs method" else try - ir, rt = get_ir(mi, cgm.world) + ir, rt = cgm.ir_source(mi, cgm.world) catch err err isa Unsupported || rethrow() + # (calling native code instead follows the configuration's policy) + handle_failure(cgm.config, mi, err, catch_backtrace()) reason = err end - ir !== nothing && rt === Union{} && (reason = "a method that always throws"; ir = nothing) + if ir !== nothing && rt === Union{} && cgm.throwing_stubs + reason = "a method that always throws" + ir = nothing + end end info = declare_function!(cgm, mi, signature_argtypes(mi), ir === nothing ? Any : rt) push!(cgm.worklist, (info, ir === nothing ? reason : ir)) diff --git a/src/ir.jl b/src/ir.jl index b876bab..4f94ff1 100644 --- a/src/ir.jl +++ b/src/ir.jl @@ -31,7 +31,7 @@ jlcall entry wrapper named `name`. The entry function itself must be supported: """ function emit_entry!(cgm::CGModule, @nospecialize(tt::Type); name::AbstractString=unique_name(cgm, "jfptr")) mi = method_instance(tt, cgm.world) - ir, rt = get_ir(mi, cgm.world) + ir, rt = cgm.ir_source(mi, cgm.world) info = declare_function!(cgm, mi, signature_argtypes(mi), rt) push!(cgm.worklist, (info, ir)) process_worklist!(cgm; strict=mi) diff --git a/src/specsig.jl b/src/specsig.jl index 7affdb6..ee7a12b 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -3,6 +3,7 @@ # # swiftcc f([ptr sret(T) %sret,] ptr swiftself %pgcstack, args...) # +# (or, without the pgcstack argument, `gcstack_arg=false`, in the C calling convention). # Ghost arguments are not passed; boxed values (and unboxed unions) are passed as tracked # pointers, primitive and vector values by value (small integers `signext` or `zeroext`), # and other inline values by a `ptr addrspace(11)` reference. Inline results larger than @@ -20,7 +21,8 @@ A function signature in Julia's native specialized calling convention: how each argument is passed (`nothing` for ghosts, which aren't), how the result is returned (`:void`, -`:value`, `:boxed` or `:sret`), the LLVM function type and the return and parameter +`:value`, `:boxed` or `:sret`), whether the pgcstack is passed (`gcstack`, then in the +Swift calling convention), the LLVM function type and the return and parameter attributes. """ struct SpecSig @@ -28,6 +30,7 @@ struct SpecSig rettype::Any args::Vector{Union{Nothing,SpecArg}} ret::Symbol + gcstack::Bool ft::LLVM.FunctionType retattrs::Vector{LLVM.Attribute} paramattrs::Vector{Vector{LLVM.Attribute}} @@ -51,13 +54,16 @@ is_singleton_type(@nospecialize T) = T isa DataType && isdefined(T, :instance) is_aggregate(ty::LLVM.LLVMType) = ty isa LLVM.StructType || ty isa LLVM.ArrayType """ - JuliaCodegen.specsig_abi(cgm, argtypes, rettype) -> SpecSig + JuliaCodegen.specsig_abi(cgm, argtypes, rettype; gcstack_arg) -> SpecSig The signature of a function of the Julia argument types `argtypes` and return type -`rettype` in the specsig convention, as native code declares it. Throws `Unsupported` for -signatures it doesn't handle. +`rettype` in the specsig convention, as native code declares it. With `gcstack_arg` +(by default the configuration's), the pgcstack is passed as `swiftself`; without, the +function has the C calling convention. Throws `Unsupported` for signatures it doesn't +handle. """ -function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype)) +function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype); + gcstack_arg::Bool=cgm.config.gcstack_arg) ls = cgm.layouts params = LLVM.LLVMType[] paramattrs = Vector{LLVM.Attribute}[] @@ -85,9 +91,11 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype ret, rty = :value, lt end end - push!(params, T_ptr()) - push!(paramattrs, LLVM.Attribute[attr("nonnull"), attr("swiftself")]) - cgm.config.dialect.gc_stack_argument && push!(paramattrs[end], LLVM.StringAttribute("gcstack")) + if gcstack_arg + push!(params, T_ptr()) + push!(paramattrs, LLVM.Attribute[attr("nonnull"), attr("swiftself")]) + cgm.config.dialect.gc_stack_argument && push!(paramattrs[end], LLVM.StringAttribute("gcstack")) + end args = Union{Nothing,SpecArg}[] for T in argtypes k = repr_kind(T) @@ -115,7 +123,8 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype push!(paramattrs, ext === nothing ? LLVM.Attribute[] : LLVM.Attribute[attr(ext)]) end end - return SpecSig(argtypes, rettype, args, ret, LLVM.FunctionType(rty, params), retattrs, paramattrs) + return SpecSig(argtypes, rettype, args, ret, gcstack_arg, LLVM.FunctionType(rty, params), + retattrs, paramattrs) end function add_attributes!(f::Union{LLVM.Function,LLVM.CallBase}, sig::SpecSig) @@ -139,7 +148,7 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri m isa Method && m.isva && unsupported("the specsig convention for the varargs method ", m) sig = specsig_abi(cgm, info.argtypes, info.rettype) f = LLVM.Function(cgm.mod, String(name), sig.ft) - LLVM.callconv!(f, LLVM.API.LLVMSwiftCallConv) + sig.gcstack && LLVM.callconv!(f, LLVM.API.LLVMSwiftCallConv) init_function!(f, cgm.config.target) add_attributes!(f, sig) @dispose b=LLVM.IRBuilder() begin @@ -148,8 +157,10 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri fc = FnCtx(cgm, info, nothing, b, top) ps = LLVM.parameters(f) p = sig.ret === :sret ? 2 : 1 - fc.pgcstack = ps[p] - p += 1 + if sig.gcstack + fc.pgcstack = ps[p] + p += 1 + end ops = LLVM.Value[] for (T, k) in zip(info.argtypes, sig.args) k === nothing && continue @@ -197,7 +208,7 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V slot = entry_alloca!(fc, layout(fc, rt).llvm; align=Base.datatype_alignment(rt)) push!(ops, slot) end - push!(ops, fc.pgcstack) + sig.gcstack && push!(ops, fc.pgcstack) for (a, T, k) in zip(args, sig.argtypes, sig.args) k === nothing && continue if k === SpecBoxed @@ -211,7 +222,7 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V end end r = LLVM.call!(b, sig.ft, callee, ops) - LLVM.callconv!(r, LLVM.API.LLVMSwiftCallConv) + sig.gcstack && LLVM.callconv!(r, LLVM.API.LLVMSwiftCallConv) add_attributes!(r, sig) k = repr_kind(rt) k === Bottom && return emit_unreachable!(fc) diff --git a/test/emit_into.jl b/test/emit_into.jl new file mode 100644 index 0000000..fd4655c --- /dev/null +++ b/test/emit_into.jl @@ -0,0 +1,153 @@ +# `emit_into!`: a closed set of CodeInstances, inferred by the caller's interpreter (here, +# one with an overlay method table, as GPU compilers use), compiled into the caller's module. + +const CC = Base.Compiler + +Base.Experimental.@MethodTable EI_MT +ei_hook(x) = x +Base.Experimental.@overlay EI_MT ei_hook(x) = x * 100 +@noinline ei_inner(x) = ei_hook(x) + 1 +ei_kernel(x) = ei_inner(x) * 2 +ei_fib(n) = n < 2 ? n : ei_fib(n - 1) + ei_fib(n - 2) +ei_sum(v) = (s = zero(eltype(v)); for x in v; s += x; end; s) +@noinline ei_throw(x) = throw(ArgumentError("negative")) +@noinline ei_check(x) = x > 0 ? x : ei_throw(x) +ei_checked(x) = ei_check(x) + 1 +ei_try(x) = try ei_check(x) catch; -1 end +ei_pair(x) = (x, x + 1.0) +ei_missing(x) = ei_inner(x) + +struct EIInterp <: CC.AbstractInterpreter + world::UInt + inf_cache::Any +end +# (Julia 1.15 indexes the local inference cache) +EIInterp(world) = EIInterp(world, isdefined(CC, :InferenceCache) ? CC.InferenceCache() : CC.InferenceResult[]) +CC.InferenceParams(::EIInterp) = CC.InferenceParams() +CC.OptimizationParams(::EIInterp) = CC.OptimizationParams() +CC.get_inference_world(i::EIInterp) = i.world +CC.get_inference_cache(i::EIInterp) = i.inf_cache +CC.cache_owner(::EIInterp) = :jctest_emit_into +CC.method_table(i::EIInterp) = CC.OverlayMethodTable(i.world, EI_MT) +CC.may_discard_trees(::EIInterp) = false +CC.may_compress(::EIInterp) = false + +# the CodeInstances (with their sources) of `mi` and of what it invokes, transitively; the +# callees `exclude` names are left out +function ei_codeinfos(mi; world=Base.get_world_counter(), exclude=()) + interp = EIInterp(world) + out = Pair{Core.CodeInstance,Core.CodeInfo}[] + seen = IdSet{Core.MethodInstance}() + work = [mi] + while !isempty(work) + m = pop!(work) + (m in seen || m.def.name in exclude) && continue + push!(seen, m) + ci = CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + push!(out, ci => ci.inferred::Core.CodeInfo) + for st in ci.inferred.code + Meta.isexpr(st, :invoke) || continue + t = st.args[1] + push!(work, t isa Core.CodeInstance ? CC.get_ci_mi(t) : t) + end + end + return out +end + +# the test JIT's entry `name`: the jlcall entry of the root CodeInstance (or, with +# `specsig`, its specsig entry) +function emit_through_emit_into!(cgm, @nospecialize(tt), name; specsig=false) + mi = JuliaCodegen.method_instance(tt, cgm.world) + pairs = ei_codeinfos(mi; world=cgm.world) + compiled, _ = JuliaCodegen.emit_into!(cgm, pairs) + fs = compiled[first(pairs[1])] + entry = LLVM.functions(cgm.mod)[specsig ? fs.specfunc : fs.func] + # (the other entries' names are the same in every module, which the test JIT may + # put in one dylib) + for f in LLVM.functions(cgm.mod) + LLVM.isdeclaration(f) || f == entry || LLVM.linkage!(f, LLVM.API.LLVMInternalLinkage) + end + LLVM.name!(entry, name) +end +run_emit_into(f, args...) = cgrun(f, args...; emit=emit_through_emit_into!) + +const EI_GPU = JuliaCodegen.CodegenConfig(; on_unsupported=:error, on_internal_error=:error, + gcstack_arg=false, safepoint_on_entry=false) + +function ei_module(f, types; config=test_config(), exclude=()) + @dispose ctx=LLVM.Context() mod=LLVM.Module("jcemitinto") begin + mi = JuliaCodegen.method_instance(Tuple{Core.Typeof(f), types...}, Base.get_world_counter()) + pairs = ei_codeinfos(mi; exclude) + compiled, out = JuliaCodegen.emit_into!(mod, pairs; config) + verify_ir(mod) + return (; pairs, compiled, out, ir=string(mod), + linkage=Dict(LLVM.name(f) => LLVM.linkage(f) for f in LLVM.functions(mod))) + end +end + +@testset "emit_into!" begin + +@testset "the caller's IR" begin + # the overlay of the interpreter, not the method native inference sees + @test run_emit_into(ei_kernel, 3) == (300 + 1) * 2 + @test ei_kernel(3) == 8 +end + +@testset "differential" begin + @cgtest run=run_emit_into ei_fib(15) + @cgtest run=run_emit_into ei_sum([1, 2, 3, 4]) + @cgtest run=run_emit_into ei_sum(Float64[]) + @cgtest run=run_emit_into ei_checked(1) + @cgtest run=run_emit_into ei_checked(-1) + @cgtest run=run_emit_into ei_try(-1) + @cgtest run=run_emit_into ei_pair(2) +end + +@testset "functions" begin + r = ei_module(ei_kernel, (Int,)) + @test length(r.compiled) == length(r.pairs) == 2 + for (ci, _) in r.pairs + fs = r.compiled[ci] + @test r.linkage[fs.func] == LLVM.API.LLVMExternalLinkage + @test fs.specfunc !== nothing && r.linkage[fs.specfunc] == LLVM.API.LLVMExternalLinkage + end + @test count(l -> l == LLVM.API.LLVMInternalLinkage, values(r.linkage)) == 2 + @test sort([e.abi for e in r.out.entries]) == [:jlcall, :jlcall, :specsig, :specsig] + @test isempty(r.out.fallbacks) + # error paths are compiled, not stubs that call native code + r = ei_module(ei_checked, (Int,)) + @test any(((ci, _),) -> CC.get_ci_mi(ci).def.name === :ei_throw && ci.rettype === Union{}, r.pairs) + @test !any(((mi, _),) -> mi.def.name === :ei_throw, r.out.fallbacks) +end + +@testset "GPU-style configuration" begin + # no pgcstack argument (the C calling convention) and no safepoint, as with Julia's + # `CodegenParams(gcstack_arg=false, safepoint_on_entry=false)` + params = Base.CodegenParams(; gcstack_arg=false, safepoint_on_entry=false, prefer_specsig=true) + for (f, types) in ((ss_id, (Int,)), (ss_swap, (SS_Pair,)), (ss_dup, (Int,)), (ss_id, (String,)), + (ss_mix, (Int8, Bool, UInt16, Float32, SS_Pair, Nothing, String))) + native = sprint(io -> code_llvm(io, f, types; raw=true, optimize=false, debuginfo=:none, params)) + r = ei_module(f, types; config=EI_GPU) + spec = r.compiled[first(r.pairs[1])].specfunc + ours = something(match(Regex("^define .*@\\Q$spec\\E\\(.*\$", "m"), r.ir)).match + @test normalize_header(ours) == normalize_header(something(match(r"^define .*$"m, native)).match) + @test !occursin("@julia.safepoint", r.ir) + end + # the specsig entry is a C function + c = test_compile(Tuple{typeof(ei_kernel), Int}; config=EI_GPU, + emit=(cgm, tt, name) -> emit_through_emit_into!(cgm, tt, name; specsig=true)) + @test ccall(c.fptr, Int, (Int,), 3) == 602 +end + +@testset "a closed set" begin + # a callee that is not in the set: an error, or a call of native code + @test_throws JuliaCodegen.Unsupported ei_module(ei_missing, (Int,); exclude=(:ei_inner,)) + fallback = JuliaCodegen.CodegenConfig(; on_unsupported=:fallback, on_internal_error=:error) + r = ei_module(ei_missing, (Int,); config=fallback, exclude=(:ei_inner,)) + @test only(r.out.fallbacks).first.def.name === :ei_inner + @test_throws "two CodeInstances" @dispose ctx=LLVM.Context() mod=LLVM.Module("x") begin + JuliaCodegen.emit_into!(mod, [r.pairs; r.pairs]) + end +end + +end diff --git a/test/jit.jl b/test/jit.jl index 780788d..6b864b2 100644 --- a/test/jit.jl +++ b/test/jit.jl @@ -41,7 +41,7 @@ emits the function `name` in the jlcall convention that calls it. Every module p """ function test_compile(@nospecialize(tt); optimize::Bool=true, config=test_config(), emit=emit_jlcall_entry!, relocatable::Bool=true) - @lock TEST_LOCK get!(TEST_CACHE, (tt, optimize, config.on_unsupported, emit)) do + @lock TEST_LOCK get!(TEST_CACHE, (tt, optimize, config, emit)) do jit = test_jit() fallbacks = Pair{Core.MethodInstance,Any}[] roots = Any[] diff --git a/test/runtests.jl b/test/runtests.jl index 34ee7bd..39f866c 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -27,6 +27,7 @@ include("exceptions.jl") include("specsig.jl") include("cfunction.jl") include("output.jl") +include("emit_into.jl") include("cabi_targets.jl") @testset "Aqua" begin From 56b12622b5fa68fb34f6bc718a7b7bfe84d810a5 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 18:35:35 +0200 Subject: [PATCH 2/4] Entries inline the function they wrap The jlcall and specsig entries call their function with `alwaysinline`, so that after any pipeline's always-inliner (Julia's, GPUCompiler's), an entry is the function itself, as native code's are. With GPUCompiler, the specsig entry of a kernel otherwise stayed a call of the kernel's body. Assisted-by: Claude Code (Opus 5.5) --- src/function.jl | 2 ++ src/specsig.jl | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/function.jl b/src/function.jl index 6e89723..40977f3 100644 --- a/src/function.jl +++ b/src/function.jl @@ -305,6 +305,8 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin push!(ops, convert_repr(fc, boxed(Any, p), T).V) end r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) + # (the entry is the function, as native code's: inlined by any pipeline) + push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline")) rt = info.rettype k = repr_kind(rt) if k === Bottom diff --git a/src/specsig.jl b/src/specsig.jl index ee7a12b..378a899 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -176,6 +176,8 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri push!(ops, convert_repr(fc, cv, T).V) end r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) + # (the entry is the function, as native code's: inlined by any pipeline) + push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline")) if sig.ret === :sret st = LLVM.store!(b, r, ps[1]) LLVM.alignment!(st, Base.datatype_alignment(info.rettype)) From 4de3189c660ee20c6308f616a99d85edc93a7a66 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 19:08:00 +0200 Subject: [PATCH 3/4] emit_into!: name the entries as native code's The specsig entry of a CodeInstance is `julia_f_N` and its jlcall entry `jfptr_f_N`, as Julia's code generator names them; the function they inline is `jlbody_f_N`. GPUCompiler's tests, and whoever else matches the names, see the same functions with either code generator. Assisted-by: Claude Code (Opus 5.5) --- src/emit_into.jl | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/emit_into.jl b/src/emit_into.jl index 8c69c7e..5c69dab 100644 --- a/src/emit_into.jl +++ b/src/emit_into.jl @@ -30,8 +30,9 @@ Compile the CodeInstances of `codeinfos`, `(ci, src)` pairs whose source `src` ( `output.fallbacks`), or throws with `on_unsupported = :error`; - functions that always throw are compiled too (no native-code stubs for error paths); - every CodeInstance gets an entry in the jlcall convention and, where its signature is - handled, one in the specsig convention (with the configuration's `gcstack_arg`); the - functions themselves have internal linkage. + handled, one in the specsig convention (with the configuration's `gcstack_arg`), named + as native code's (`jfptr_f_N` and `julia_f_N`); the functions themselves have internal + linkage. Returns `compiled`, an `IdDict` from each CodeInstance to its [`CompiledFunctions`](@ref JuliaCodegen.CompiledFunctions), and the module's @@ -82,11 +83,14 @@ function emit_sources!(cgm::CGModule, codeinfos, sources) process_worklist!(cgm) compiled = IdDict{Core.CodeInstance,CompiledFunctions}() for (ci, info) in infos - name = LLVM.name(info.llvmf) - func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * name) + # the entries are named as native code's (`julia_f_N` in the specsig convention, + # `jfptr_f_N` in the jlcall one); the function they inline is `jlbody_f_N` + base = chopprefix(LLVM.name(info.llvmf), "julia_") + LLVM.name!(info.llvmf, "jlbody_" * base) + func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base) push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) specfunc = try - LLVM.name(emit_specsig_wrapper!(cgm, info, "j_" * name)) + LLVM.name(emit_specsig_wrapper!(cgm, info, "julia_" * base)) catch err err isa Unsupported || rethrow() nothing From 9e887f920faaec39c0b04b4654cbbe030974efe8 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Mon, 19 Oct 2026 19:31:25 +0200 Subject: [PATCH 4/4] emit_into!: keep the functions' names, name the specsig entries j_f_N Functions that other functions call keep native code's name `julia_f_N`, as calls that aren't inlined refer to them; the specsig entry is `j_f_N`, the prefix of native code's specsig wrappers. Assisted-by: Claude Code (Opus 5.5) --- src/emit_into.jl | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/emit_into.jl b/src/emit_into.jl index 5c69dab..d74d768 100644 --- a/src/emit_into.jl +++ b/src/emit_into.jl @@ -31,8 +31,8 @@ Compile the CodeInstances of `codeinfos`, `(ci, src)` pairs whose source `src` ( - functions that always throw are compiled too (no native-code stubs for error paths); - every CodeInstance gets an entry in the jlcall convention and, where its signature is handled, one in the specsig convention (with the configuration's `gcstack_arg`), named - as native code's (`jfptr_f_N` and `julia_f_N`); the functions themselves have internal - linkage. + as native code's (`jfptr_f_N`, and `j_f_N` for the specsig entry of `julia_f_N`); the + functions themselves have internal linkage. Returns `compiled`, an `IdDict` from each CodeInstance to its [`CompiledFunctions`](@ref JuliaCodegen.CompiledFunctions), and the module's @@ -83,14 +83,14 @@ function emit_sources!(cgm::CGModule, codeinfos, sources) process_worklist!(cgm) compiled = IdDict{Core.CodeInstance,CompiledFunctions}() for (ci, info) in infos - # the entries are named as native code's (`julia_f_N` in the specsig convention, - # `jfptr_f_N` in the jlcall one); the function they inline is `jlbody_f_N` + # named as native code's functions: the function `julia_f_N` (which other functions + # call), its entries `j_f_N` in the specsig convention (the prefix of native code's + # specsig wrappers) and `jfptr_f_N` in the jlcall one base = chopprefix(LLVM.name(info.llvmf), "julia_") - LLVM.name!(info.llvmf, "jlbody_" * base) func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base) push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) specfunc = try - LLVM.name(emit_specsig_wrapper!(cgm, info, "julia_" * base)) + LLVM.name(emit_specsig_wrapper!(cgm, info, "j_" * base)) catch err err isa Unsupported || rethrow() nothing