From 3338b2ce7908fb1d11caf1a5b145279108d5ff97 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 19 Oct 2026 19:38:37 +0200 Subject: [PATCH 1/3] Reflect on the job's method instance instead of looking it up again `code_lowered`, `code_typed` and `code_warntype` looked up the method for the signature of `job.source` again, in Base's method table (and on 1.12+ through the interpreter for `code_typed`). When the job compiles an overlay method, that showed different code from what is compiled. Use `job.source` directly. --- src/reflection.jl | 19 ++++++--------- src/reflection_compat.jl | 52 ++++++++++++++++++++++++---------------- test/native.jl | 22 +++++++++++++++++ 3 files changed, 60 insertions(+), 33 deletions(-) diff --git a/src/reflection.jl b/src/reflection.jl index 1d7db645..03edcd7e 100644 --- a/src/reflection.jl +++ b/src/reflection.jl @@ -201,30 +201,25 @@ function descend(@nospecialize(sig); kwargs...) end function code_lowered(@nospecialize(job::CompilerJob); kwargs...) - sig = job.source.specTypes # XXX: can we just use the method instance? - code_lowered_by_type(sig; kwargs...) + code_lowered_by_mi(job.source; kwargs...) end function code_typed(@nospecialize(job::CompilerJob); interactive::Bool=false, kwargs...) - sig = job.source.specTypes # XXX: can we just use the method instance? + interp = get_interpreter(job) if interactive - interp = get_interpreter(job) - descend(sig; warntype=false, interp, kwargs...) + descend(job.source.specTypes; warntype=false, interp, kwargs...) else - interp = get_interpreter(job) - Base.code_typed_by_type(sig; interp, kwargs...) + code_typed_by_mi(job.source; interp, kwargs...) end end function code_warntype(io::IO, @nospecialize(job::CompilerJob); interactive::Bool=false, kwargs...) - sig = job.source.specTypes # XXX: can we just use the method instance? + interp = get_interpreter(job) if interactive @assert io == stdout - interp = get_interpreter(job) - descend(sig; warntype=true, interp, kwargs...) + descend(job.source.specTypes; warntype=true, interp, kwargs...) else - interp = get_interpreter(job) - code_warntype_by_type(io, sig; interp, kwargs...) + code_warntype_by_mi(io, job.source; interp, kwargs...) end end code_warntype(@nospecialize(job::CompilerJob); kwargs...) = code_warntype(stdout, job; kwargs...) diff --git a/src/reflection_compat.jl b/src/reflection_compat.jl index 0e00af8d..3f495217 100644 --- a/src/reflection_compat.jl +++ b/src/reflection_compat.jl @@ -3,35 +3,45 @@ using InteractiveUtils: highlighting using Base: hasgenerator -function method_instances(@nospecialize(tt::Type), world::UInt=Base.get_world_counter()) - return map(Core.Compiler.specialize_method, method_matches(tt; world)) -end - -function code_lowered_by_type(@nospecialize(tt); generated::Bool=true, debuginfo::Symbol=:default) - +# like `Base.code_lowered`, but for a specific method instance +function code_lowered_by_mi(mi::MethodInstance; generated::Bool=true, + debuginfo::Symbol=:default) debuginfo = Base.IRShow.debuginfo(debuginfo) if debuginfo !== :source && debuginfo !== :none throw(ArgumentError("'debuginfo' must be either :source or :none")) end - return map(method_instances(tt)) do m - if generated && hasgenerator(m) - if Base.may_invoke_generator(m) - return ccall(:jl_code_for_staged, Any, (Any,), m)::CodeInfo - else - error("Could not expand generator for `@generated` method ", m, ". ", - "This can happen if the provided argument types (", t, ") are ", - "not leaf types, but the `generated` argument is `true`.") - end + if generated && hasgenerator(mi) + if Base.may_invoke_generator(mi) + return Any[ccall(:jl_code_for_staged, Any, (Any,), mi)::CodeInfo] + else + error("Could not expand generator for `@generated` method ", mi, ". ", + "This can happen if the provided argument types (", mi.specTypes, ") are ", + "not leaf types, but the `generated` argument is `true`.") end - code = Base.uncompressed_ir(m.def::Method) - debuginfo === :none && Base.remove_linenums!(code) - return code end + code = Base.uncompressed_ir(mi.def::Method) + debuginfo === :none && Base.remove_linenums!(code) + return Any[code] +end + +# like `Base.code_typed_by_type`, but for a specific method instance +function code_typed_by_mi(mi::MethodInstance; interp::CC.AbstractInterpreter, + optimize::Bool=true, debuginfo::Symbol=:default) + debuginfo = Base.IRShow.debuginfo(debuginfo) + if debuginfo !== :source && debuginfo !== :none + throw(ArgumentError("'debuginfo' must be either :source or :none")) + end + ret = CC.typeinf_code(interp, mi.def::Method, mi.specTypes, mi.sparam_vals, optimize) + # 1.10/1.11 return the code and its return type, later versions only the code + code, rt = ret isa Tuple ? ret : (ret, ret === nothing ? Any : ret.rettype) + code === nothing && return Any[mi.def => Any] + debuginfo === :none && Base.remove_linenums!(code) + return Any[code => rt] end -function code_warntype_by_type(io::IO, @nospecialize(tt); - debuginfo::Symbol=:default, optimize::Bool=false, kwargs...) - for (src, rettype) in Base.code_typed_by_type(tt; optimize, kwargs...) +function code_warntype_by_mi(io::IO, mi::MethodInstance; + debuginfo::Symbol=:default, optimize::Bool=false, kwargs...) + for (src, rettype) in code_typed_by_mi(mi; optimize, kwargs...) if src isa Core.CodeInfo code_warntype(io, src, rettype; debuginfo) else diff --git a/test/native.jl b/test/native.jl index 41ed10f9..44bfbd32 100644 --- a/test/native.jl +++ b/test/native.jl @@ -2872,6 +2872,28 @@ end end end +@testset "kernel overrides" begin + mod = @eval module $(gensym()) + Base.Experimental.@MethodTable(method_table) + + kernel() = 0 + Base.Experimental.@overlay method_table kernel() = 1 + end + + # reflection shows the method instance that is compiled + job, _ = Native.create_job(mod.kernel, (); mod.method_table) + mi = generic_methodinstance(typeof(mod.kernel), Tuple{}; + method_table_view=GPUCompiler.method_table_view(job)) + @test mi.def.external_mt === mod.method_table + job = CompilerJob(job; source=mi) + lowered = only(GPUCompiler.code_lowered(job)) + @test lowered.code[end] == Core.ReturnNode(1) + src, rt = only(GPUCompiler.code_typed(job)) + @test src.code[end] == Core.ReturnNode(1) + @test rt === Int + @test occursin("return 1", sprint(GPUCompiler.code_warntype, job)) +end + @testset "runtime functions from overlay methods" begin # runtime library functions (`signal_exception`, `malloc`, ...) should be resolved # through the job's method table, so that back-ends can keep GPU-only code out of From 549e7275864b04de548504829877703523570fb6 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 19 Oct 2026 19:45:08 +0200 Subject: [PATCH 2/3] Add methodinstance(job) to look up kernels in the job's method tables Back-ends look up the method instance for a kernel with `methodinstance(ft, tt)`, which only considers Base's method table, so an overlay method for the kernel function itself was never compiled (#208). Looking it up in the job's method tables requires the config, as the tables may depend on it, so add `methodinstance(job)` that resolves `job.source` again through `method_table_view(job)`, for back-ends to call after constructing the job. Use it for deferred compilation and in the native test helper. On Julia versions with JuliaLang/julia#60718 this uses Julia's dispatch cache for every table; otherwise it falls back to a slower generic lookup. --- src/driver.jl | 5 ++-- src/jlgen.jl | 66 ++++++++++++++++++++++++++++++++++++++++-- test/helpers/native.jl | 3 +- test/native.jl | 54 +++++++++++++++++++++++++++++++--- 4 files changed, 119 insertions(+), 9 deletions(-) diff --git a/src/driver.jl b/src/driver.jl index 13c3f81d..f57534dc 100644 --- a/src/driver.jl +++ b/src/driver.jl @@ -259,8 +259,9 @@ const __llvm_initialized = Ref(false) dyn_val else ft, tt = dyn_val - dyn_src = methodinstance(ft, tt, job.world) - CompilerJob(dyn_src, job.config, job.world) + dyn_job = CompilerJob(methodinstance(ft, tt, job.world), job.config, + job.world) + CompilerJob(dyn_job; source=methodinstance(dyn_job)) end push!(get!(worklist, dyn_job, LLVM.CallInst[]), call) diff --git a/src/jlgen.jl b/src/jlgen.jl index aadb4278..1332e85f 100644 --- a/src/jlgen.jl +++ b/src/jlgen.jl @@ -105,10 +105,17 @@ end sig = signature_type_by_tt(ft, tt) @assert Base.isdispatchtuple(sig) # JuliaLang/julia#52233 + mi = method_lookup_by_tt(sig, world, #=method_table=# nothing) + mi === nothing && throw(MethodError(ft, tt, world)) + return mi +end + +@inline function method_lookup_by_tt(@nospecialize(sig::Type), world::Integer, + mt::Union{Nothing,Core.MethodTable}) mi = ccall(:jl_method_lookup_by_tt, Any, (Any, Csize_t, Any), - sig, world, #=method_table=# nothing) - mi === nothing && throw(MethodError(ft, tt, world)) + sig, world, mt) + mi === nothing && return nothing mi = mi::MethodInstance # `jl_method_lookup_by_tt` and `jl_method_lookup` can return a unspecialized mi @@ -125,6 +132,61 @@ else const methodinstance = generic_methodinstance end +# `jl_method_lookup_by_tt` supports overlay tables since JuliaLang/julia#60718 +const HAS_OVERLAY_LOOKUP_BY_TT = v"1.11.9" <= VERSION < v"1.12-" || + v"1.12.5" <= VERSION < v"1.13-" || + VERSION >= v"1.13.0-beta2" + +""" + methodinstance(job::CompilerJob) + +Look up the method instance that `job` should compile: the one for the signature of +`job.source` in the method tables of the job (see [`method_table_view`](@ref)). This +differs from `job.source` when those tables contain an overlay method for the function +itself, which `methodinstance(ft, tt)` does not know about. Back-ends that support such +overlays should construct their jobs as follows: + +```julia +job = CompilerJob(methodinstance(ft, tt), config) +job = CompilerJob(job; source=methodinstance(job)) +``` +""" +# specialized on the job type, as back-ends call this on every kernel launch +function methodinstance(job::CompilerJob) + sig = dispatch_signature(job.source.specTypes) + mtv = method_table_view(job) + @static if HAS_OVERLAY_LOOKUP_BY_TT + tables = overlay_tables(mtv) + if tables !== nothing + for mt in tables + mi = method_lookup_by_tt(sig, job.world, mt) + mi === nothing || return mi + end + mi = method_lookup_by_tt(sig, job.world, nothing) + mi === nothing && throw(signature_method_error(sig, job.world)) + return mi + end + end + match = first(CC.findsup(sig, mtv)) + match === nothing && throw(signature_method_error(sig, job.world)) + return CC.specialize_method(match)::MethodInstance +end + +@static if isdefined(Core, :TypeEgal) + function dispatch_signature(@nospecialize(sig::Type)) + u = Base.unwrap_unionall(sig)::DataType + any(Base.isType, u.parameters) || return sig + return Base.rewrap_unionall(Tuple{(dispatch_key(p) for p in u.parameters)...}, sig) + end +else + dispatch_signature(@nospecialize(sig::Type)) = sig +end + +function signature_method_error(@nospecialize(sig::Type), world::Integer) + params = (Base.unwrap_unionall(sig)::DataType).parameters + return MethodError(params[1], Tuple{params[2:end]...}, world) +end + ## method overrides diff --git a/test/helpers/native.jl b/test/helpers/native.jl index d0f83c3b..5a9dbd6c 100644 --- a/test/helpers/native.jl +++ b/test/helpers/native.jl @@ -83,7 +83,8 @@ function create_job(@nospecialize(func), @nospecialize(types); target = NativeCompilerTarget(;jlruntime) params = CompilerParams(entry_safepoint, method_table, relocations) config = CompilerConfig(target, params; kernel=false, config_kwargs...) - CompilerJob(source, config), kwargs + job = CompilerJob(source, config) + CompilerJob(job; source=methodinstance(job)), kwargs end # Add an object to a fresh ORC JIT and supply its relocation words, the loader in miniature. diff --git a/test/native.jl b/test/native.jl index 44bfbd32..dd298d3d 100644 --- a/test/native.jl +++ b/test/native.jl @@ -2880,18 +2880,64 @@ end Base.Experimental.@overlay method_table kernel() = 1 end + @test @filecheck begin + # before 1.12, overlay methods are named `julia__kernel_N` + @check_label "@{{(julia|j)_+kernel_[0-9]+}}" + @check "ret i64 1" + Native.code_llvm(mod.kernel, Tuple{}; mod.method_table) + end + # reflection shows the method instance that is compiled job, _ = Native.create_job(mod.kernel, (); mod.method_table) - mi = generic_methodinstance(typeof(mod.kernel), Tuple{}; - method_table_view=GPUCompiler.method_table_view(job)) - @test mi.def.external_mt === mod.method_table - job = CompilerJob(job; source=mi) + @test job.source.def.external_mt === mod.method_table lowered = only(GPUCompiler.code_lowered(job)) @test lowered.code[end] == Core.ReturnNode(1) src, rt = only(GPUCompiler.code_typed(job)) @test src.code[end] == Core.ReturnNode(1) @test rt === Int @test occursin("return 1", sprint(GPUCompiler.code_warntype, job)) + + # ... also when that is not the method the job's tables would select + job = CompilerJob(job; source=methodinstance(typeof(mod.kernel), Tuple{})) + lowered = only(GPUCompiler.code_lowered(job)) + @test lowered.code[end] == Core.ReturnNode(0) + src, _ = only(GPUCompiler.code_typed(job)) + @test src.code[end] == Core.ReturnNode(0) + + # the overlay is picked up when it is added after compiling the function + mod = @eval module $(gensym()) + Base.Experimental.@MethodTable(method_table) + kernel() = 0 + end + @test @filecheck begin + @check_label "@julia_kernel" + @check "ret i64 0" + Native.code_llvm(mod.kernel, Tuple{}; mod.method_table) + end + @eval mod Base.Experimental.@overlay method_table kernel() = 1 + @test @filecheck begin + # before 1.12, overlay methods are named `julia__kernel_N` + @check_label "@{{(julia|j)_+kernel_[0-9]+}}" + @check "ret i64 1" + Native.code_llvm(mod.kernel, Tuple{}; mod.method_table) + end + + # ... and for deferred compilation + mod = @eval module $(gensym()) + using ..GPUCompiler + Base.Experimental.@MethodTable(method_table) + @noinline child() = 0 + Base.Experimental.@overlay method_table @noinline child() = 1 + function kernel() + ptr = GPUCompiler.deferred_codegen(Val(typeof(child)), Val(Tuple{})) + ccall(ptr, Int, ()) + end + end + @test @filecheck begin + @check_label "define {{.*}} @{{(julia|j)_+child_[0-9]+}}" + @check "ret i64 1" + Native.code_llvm(mod.kernel, Tuple{}; mod.method_table, dump_module=true) + end end @testset "runtime functions from overlay methods" begin From e6f56b267f5793ec7192f5b12c15efc9d7f0141b Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 19 Oct 2026 19:50:37 +0200 Subject: [PATCH 3/3] Cache failed lookups of kernels in overlay tables Julia doesn't cache lookups that fail, and those take about 70 ns per overlay table, against 10 ns for a cached lookup. Kernels rarely have an overlay method, so `methodinstance(job)` would add 140 ns or more to every launch for a back-end with a couple of tables. Remember the misses for the world they happened in, which brings that back to around 30 ns in total. --- src/GPUCompiler.jl | 2 ++ src/jlgen.jl | 49 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/GPUCompiler.jl b/src/GPUCompiler.jl index 8231c94b..417bd4e0 100644 --- a/src/GPUCompiler.jl +++ b/src/GPUCompiler.jl @@ -94,6 +94,8 @@ include("precompile.jl") function __init__() STDERR_HAS_COLOR[] = get(stderr, :color, false) empty!(session_results_cache) + # world ages from the session that generated the package image are meaningless here + @atomic overlay_miss_cache.entries = IdDict{Any,OverlayMissesRef}() @static if !HAS_INTEGRATED_CACHE # CodeInstances created by GPUCompiler's precompile workload are process-local. diff --git a/src/jlgen.jl b/src/jlgen.jl index 1332e85f..e7fe1dd7 100644 --- a/src/jlgen.jl +++ b/src/jlgen.jl @@ -159,8 +159,10 @@ function methodinstance(job::CompilerJob) tables = overlay_tables(mtv) if tables !== nothing for mt in tables + overlay_missed(sig, job.world, mt) && continue mi = method_lookup_by_tt(sig, job.world, mt) mi === nothing || return mi + overlay_missed!(sig, job.world, mt) end mi = method_lookup_by_tt(sig, job.world, nothing) mi === nothing && throw(signature_method_error(sig, job.world)) @@ -172,6 +174,53 @@ function methodinstance(job::CompilerJob) return CC.specialize_method(match)::MethodInstance end +# Julia does not cache failed lookups, which makes them several times slower than ones that +# succeed. Kernels rarely have an overlay method, so remember the misses. A lookup always +# has the same result in a given world, so a miss is valid in the world it happened in. +struct OverlayMisses + world::UInt + tables::Vector{Core.MethodTable} # not modified once published +end +mutable struct OverlayMissesRef + @atomic misses::OverlayMisses +end +mutable struct OverlayMissCache + # copied when adding a signature, so that lookups do not need to take the lock + @atomic entries::IdDict{Any,OverlayMissesRef} + const lock::ReentrantLock +end +const overlay_miss_cache = OverlayMissCache(IdDict{Any,OverlayMissesRef}(), ReentrantLock()) + +function overlay_missed(@nospecialize(sig::Type), world::UInt, mt::Core.MethodTable) + ref = get(@atomic(:acquire, overlay_miss_cache.entries), sig, nothing) + ref === nothing && return false + misses = @atomic :acquire ref.misses + misses.world == world || return false + for table in misses.tables + table === mt && return true + end + return false +end + +function overlay_missed!(@nospecialize(sig::Type), world::UInt, mt::Core.MethodTable) + # lookups in future worlds fail, but may not later + world <= Base.get_world_counter() || return + @lock overlay_miss_cache.lock begin + entries = @atomic :monotonic overlay_miss_cache.entries + ref = get(entries, sig, nothing) + if ref === nothing + entries = copy(entries) + entries[sig] = OverlayMissesRef(OverlayMisses(world, [mt])) + @atomic :release overlay_miss_cache.entries = entries + else + misses = ref.misses + tables = misses.world == world ? [misses.tables; mt] : [mt] + @atomic :release ref.misses = OverlayMisses(world, tables) + end + end + return +end + @static if isdefined(Core, :TypeEgal) function dispatch_signature(@nospecialize(sig::Type)) u = Base.unwrap_unionall(sig)::DataType