diff --git a/ext/CthulhuExt.jl b/ext/CthulhuExt.jl index d81ecd9f..925f090d 100644 --- a/ext/CthulhuExt.jl +++ b/ext/CthulhuExt.jl @@ -10,9 +10,9 @@ if isdefined(Cthulhu, :AbstractProvider) Cthulhu.AbstractProvider(interp::GPUInterpreter) = Cthulhu.DefaultProvider(interp) end -descend(@nospecialize(sig); warntype::Bool, kwargs...) = - warntype ? Cthulhu.descend_code_warntype(sig; kwargs...) : - Cthulhu.descend_code_typed(sig; kwargs...) +descend(mi::Core.MethodInstance; warntype::Bool, kwargs...) = + warntype ? Cthulhu.descend_code_warntype(mi; kwargs...) : + Cthulhu.descend_code_typed(mi; kwargs...) function __init__() GPUCompiler.descender[] = descend diff --git a/src/driver.jl b/src/driver.jl index 8e9ed0b1..ad312dd7 100644 --- a/src/driver.jl +++ b/src/driver.jl @@ -267,7 +267,7 @@ end function deferred_job(@nospecialize(spec), @nospecialize(job::CompilerJob)) spec isa CompilerJob && return spec ft, tt = spec - return CompilerJob(methodinstance(ft, tt, job.world), job.config, job.world) + return CompilerJob(methodinstance(ft, tt, method_table_view(job)), job.config, job.world) end # In a module that Julia generated, give the legacy markers in the code of requests the diff --git a/src/execution.jl b/src/execution.jl index 883d1ca9..2eb55fad 100644 --- a/src/execution.jl +++ b/src/execution.jl @@ -14,7 +14,10 @@ the method instance, build a `CompilerJob` and query the compiler's caches every function cufunction(f::F, tt::TT=Tuple{}; kwargs...) where {F,TT} fun, state = GPUCompiler.cached_lookup(Tuple{CuFunction,KernelState}, F, tt, (context(), values(kwargs))) do - cufunction_link(methodinstance(F, tt); kwargs...) + config = compiler_config(device(); kwargs...) + world = GPUCompiler.tls_world_age() # the world the result is cached for + source = methodinstance(F, tt, GPUCompiler.method_table_view(config, world)) + cufunction_link(CompilerJob(source, config, world)) end return HostKernel{F,tt}(f, fun, state) end diff --git a/src/interface.jl b/src/interface.jl index ac764f5d..4d638897 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -680,46 +680,78 @@ end # HAS_INTEGRATED_CACHE @public supports_relocatable_ir @public GPUCompilerCacheToken, cache_owner, cached_results -# the method table to use +## method tables # # NOTE: these (like `inference_params`, `optimization_params` and `julia_ir_passes` below) -# may only depend on the job's world and its config's `target`/`params` values +# may only depend on the world and the config's `target`/`params` values # (+ `always_inline`); [`cache_owner`](@ref) relies on that to partition inference # results correctly. + # deprecate method_table on next-breaking release -method_table(@nospecialize(job::CompilerJob)) = GLOBAL_METHOD_TABLE +method_table(@nospecialize(config::CompilerConfig)) = GLOBAL_METHOD_TABLE +method_table(@nospecialize(job::CompilerJob)) = method_table(job.config) """ + method_tables(config::CompilerConfig)::Tuple{Vararg{Core.MethodTable}} method_tables(job::CompilerJob)::Tuple{Vararg{Core.MethodTable}} -The method tables with overlays for code compiled by `job`, ordered from most to least +The method tables with overlays for code compiled with `config`, ordered from most to least specific: a method in an earlier table wins over one in a later table, even when the latter -is more specific. The default is the job's [`method_table`](@ref). +is more specific. The default is the [`method_table`](@ref). Back-ends that combine several tables, e.g., their own overlays with the ones from a package of device intrinsics, should return all of them here rather than override [`method_table_view`](@ref). GPUCompiler then adds [`SHARED_METHOD_TABLE`](@ref) at the bottom of the stack. -Like `method_table`, this may only depend on the job's `target` and `params` (see -[`cache_owner`](@ref)). +The tables may only depend on the `target` and `params` of the config (see +[`cache_owner`](@ref)), so they are known before there is a job, which is what makes it +possible to look up the function to compile in them (see [`method_table_view`](@ref)). +Back-ends define the method for their config type, and have the one for jobs, which the +compiler uses, forward to it: + +```julia +GPUCompiler.method_tables(config::MyCompilerConfig) = (method_table, other_table) +GPUCompiler.method_tables(job::MyCompilerJob) = GPUCompiler.method_tables(job.config) +``` + +A back-end that only defines the method for jobs keeps compiling what it did: +`method_table_view(config, world)` doesn't know about its tables, so a function that is +looked up through it is the one Julia would call. (What a job compiles deferred is looked up +through the view of that job, which does.) """ +method_tables(@nospecialize(config::CompilerConfig)) = (method_table(config),) method_tables(@nospecialize(job::CompilerJob)) = (method_table(job),) @public method_tables """ + method_table_view(config::CompilerConfig, world::UInt)::Core.Compiler.MethodTableView method_table_view(job::CompilerJob)::Core.Compiler.MethodTableView -The view that inference uses to look up methods for `job`. The default stacks the tables -from [`method_tables`](@ref), then [`SHARED_METHOD_TABLE`](@ref), over Base's method table. +The view through which methods are looked up for code that is compiled with `config` in +`world`, or by `job`: the tables from [`method_tables`](@ref), then +[`SHARED_METHOD_TABLE`](@ref), over Base's method table. Inference uses it for the calls +that the code makes. Use it with [`methodinstance`](@ref) to look up what to compile, so +that the two agree, and an overlay of the function itself is found: + +```julia +world = GPUCompiler.tls_world_age() +source = methodinstance(typeof(f), tt, GPUCompiler.method_table_view(config, world)) +job = CompilerJob(source, config, world) +``` Back-ends should not need to override this. Ones that do replace the whole stack, including -`SHARED_METHOD_TABLE`, so code compiled for them behaves as if it were compiled by Julia. -Returning a view of another type also gives inference a different interpreter type, so the -back-end doesn't share the inference code that GPUCompiler precompiles. +`SHARED_METHOD_TABLE`, so code compiled for them behaves as if it were compiled by Julia; +they should define both methods, like for `method_tables` (the one for a config as +`method_table_view(config::MyCompilerConfig, world::UInt)`). Returning a view of another type +also gives inference a different interpreter type, so the back-end doesn't share the +inference code that GPUCompiler precompiles. """ +method_table_view(@nospecialize(config::CompilerConfig), world::UInt) = + stack_method_tables(world, method_tables(config)..., SHARED_METHOD_TABLE) method_table_view(@nospecialize(job::CompilerJob)) = stack_method_tables(job.world, method_tables(job)..., SHARED_METHOD_TABLE) +@public method_table_view # the inference parameters to use when constructing the GPUInterpreter function inference_params(@nospecialize(job::CompilerJob)) diff --git a/src/jlgen.jl b/src/jlgen.jl index 8602a22d..10d0fb6a 100644 --- a/src/jlgen.jl +++ b/src/jlgen.jl @@ -64,6 +64,7 @@ MethodError(ft, tt, world=typemax(UInt)) = Base.MethodError(ft, tt, world) """ methodinstance(ft::Type, tt::Type, [world::UInt]) + methodinstance(ft::Type, tt::Type, view::Core.Compiler.MethodTableView) Look up the method instance that corresponds to invoking the function with type `ft` with argument typed `tt`. If the `world` argument is specified, the look-up is static and will @@ -71,31 +72,45 @@ always return the same result. If the `world` argument is not specified, the loo dynamic and the returned method instance will depende on the current world age. If no method is found, a `MethodError` is thrown. -This function is highly optimized, and results do not need to be cached additionally. +With a `view`, methods are looked up through it, in its world, like inference does for the +calls in code that is compiled with it (see [`method_table_view`](@ref)). That finds an +overlay method for the function, where the other forms only know Base's method table. + +The forms without a view are highly optimized, and results do not need to be cached +additionally. Looking up through a view is slower, as it searches every table, and belongs +where a launch is not already cached (see [`cached_lookup`](@ref)). Only use this function with concrete signatures, i.e., using the types of values you would -pass at run time. For non-concrete signatures, use `generic_methodinstance` instead. +pass at run time. For non-concrete signatures, use `generic_methodinstance` instead. That +selects the single method that covers the whole signature, as `invoke` does, where a call +with such argument types could dispatch to several. """ methodinstance function generic_methodinstance(@nospecialize(ft::Type), @nospecialize(tt::Type), world::Integer=tls_world_age(); method_table_view::Union{Nothing,CC.MethodTableView}=nothing) + method_table_view === nothing || + return generic_methodinstance(ft, tt, method_table_view, world) sig = signature_type_by_tt(ft, tt) - - match = if method_table_view === nothing - first(CC._findsup(sig, nothing, world)) - else - # e.g. an overlay table: prefer its methods, falling back to the global table - first(CC.findsup(sig, method_table_view)) - end + match = first(CC._findsup(sig, nothing, world)) match === nothing && throw(MethodError(ft, tt, world)) + return CC.specialize_method(match)::MethodInstance +end - mi = CC.specialize_method(match) - - return mi::MethodInstance +# through a view, e.g. of overlay tables: prefer their methods, falling back to the global +# table. `world` is only used to report a failure. +function generic_methodinstance(@nospecialize(ft::Type), @nospecialize(tt::Type), + view::CC.MethodTableView, + world::Union{Nothing,Integer}=nothing) + sig = signature_type_by_tt(ft, tt) + match = first(CC.findsup(sig, view)) + match === nothing && + throw(MethodError(ft, tt, @something(world, method_table_view_world(view)))) + return CC.specialize_method(match)::MethodInstance end + # On 1.11+ (JuliaLang/julia#52572 / JuliaLang/julia#52233) `jl_method_lookup_by_tt` returns # a usable `MethodInstance` directly, so we just call it. @static if VERSION >= v"1.11.0-DEV.1552" @@ -119,6 +134,9 @@ end return mi end +methodinstance(@nospecialize(ft::Type), @nospecialize(tt::Type), view::CC.MethodTableView) = + generic_methodinstance(ft, tt, view) + # On 1.10 we always use the generic lookup. (A @generated fast path used to exist, # but it was unreachable: the (ft::Type, tt::Type) method above it always won dispatch.) else @@ -250,6 +268,14 @@ end stack_method_tables(world::UInt, mts::Core.MethodTable...) = MethodTableStack(world, Core.MethodTable[mts...]) +# the world a view looks methods up in, for the views we know +method_table_view_world(view::CC.MethodTableView) = typemax(UInt) +method_table_view_world(view::Union{CC.InternalMethodTable,CC.OverlayMethodTable, + MethodTableStack,StackedMethodTable}) = view.world +@static if isdefined(CC, :CachedMethodTable) + method_table_view_world(view::CC.CachedMethodTable) = method_table_view_world(view.table) +end + ## interpreter diff --git a/src/native.jl b/src/native.jl index 738d9c6f..6c851bde 100644 --- a/src/native.jl +++ b/src/native.jl @@ -36,6 +36,8 @@ function finish_module!(job::CompilerJob{NativeCompilerTarget}, mod::LLVM.Module end # code for the host, which shouldn't see the overlays for devices +method_table_view(@nospecialize(config::CompilerConfig{NativeCompilerTarget}), world::UInt) = + stack_method_tables(world, method_tables(config)...) method_table_view(@nospecialize(job::CompilerJob{NativeCompilerTarget})) = stack_method_tables(job.world, method_tables(job)...) diff --git a/src/reflection.jl b/src/reflection.jl index d86170ad..c70e6f94 100644 --- a/src/reflection.jl +++ b/src/reflection.jl @@ -185,38 +185,33 @@ include("reflection_compat.jl") # and initialize a large package in the middle of a debugging session. const descender = Ref{Union{Nothing,Function}}(nothing) -function descend(@nospecialize(sig); kwargs...) +function descend(mi::MethodInstance; kwargs...) f = descender[] f === nothing && error("""Interactive code reflection requires Cthulhu.jl. Run `using Cthulhu` first; if it is not installed, install it with `import Pkg; Pkg.add("Cthulhu")`.""") - Base.invokelatest(f, sig; kwargs...) + Base.invokelatest(f, mi; 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; job.world, 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; 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; 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..5028f1af 100644 --- a/src/reflection_compat.jl +++ b/src/reflection_compat.jl @@ -3,35 +3,63 @@ 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; world::UInt=Base.get_world_counter(), + generated::Bool=true, debuginfo::Symbol=:default) + ccall(:jl_is_in_pure_context, Bool, ()) && + error("code reflection cannot be used from generated functions") 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 + if generated && hasgenerator(mi) + if Base.may_invoke_generator(mi) + code = @static if VERSION >= v"1.12-" + ccall(:jl_code_for_staged, Ref{CodeInfo}, (Any, UInt, Ptr{Cvoid}), + mi, world, C_NULL) 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`.") + ccall(:jl_code_for_staged, Any, (Any, UInt), mi, world)::CodeInfo end + return Any[code] + 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. The interpreter +# determines the world; `world` is only accepted to say the same. +function code_typed_by_mi(mi::MethodInstance; interp::CC.AbstractInterpreter, + world::UInt=get_inference_world(interp), + optimize::Bool=true, debuginfo::Symbol=:default) + world == get_inference_world(interp) || + throw(ArgumentError("cannot reflect in world $world on code that is compiled in world $(get_inference_world(interp))")) + ccall(:jl_is_in_pure_context, Bool, ()) && + error("code reflection cannot be used from generated functions") + debuginfo = Base.IRShow.debuginfo(debuginfo) + if debuginfo !== :source && debuginfo !== :none + throw(ArgumentError("'debuginfo' must be either :source or :none")) + end + ret = @static if hasmethod(CC.typeinf_code, Tuple{CC.AbstractInterpreter,MethodInstance,Bool}) + CC.typeinf_code(interp, mi, optimize) + else + CC.typeinf_code(interp, mi.def::Method, mi.specTypes, mi.sparam_vals, optimize) + end + # 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/src/validation.jl b/src/validation.jl index d9f5326e..914fda33 100644 --- a/src/validation.jl +++ b/src/validation.jl @@ -2,17 +2,6 @@ export InvalidIRError -# TODO: upstream -function method_matches(@nospecialize(tt::Type{<:Tuple}); world::Integer) - methods = Core.MethodMatch[] - matches = Base._methods_by_ftype(tt, -1, world) - matches === nothing && return methods - for match in matches::Vector - push!(methods, match::Core.MethodMatch) - end - return methods -end - function typeinf_type(mi::MethodInstance; interp::CC.AbstractInterpreter) @static if hasmethod(Core.Compiler.typeinf_type, Tuple{CC.AbstractInterpreter, MethodInstance}) rt = Core.Compiler.typeinf_type(interp, mi) diff --git a/test/helpers/native.jl b/test/helpers/native.jl index 7bf587da..a8ed05cd 100644 --- a/test/helpers/native.jl +++ b/test/helpers/native.jl @@ -23,12 +23,14 @@ module Runtime end NativeCompilerJob = CompilerJob{NativeCompilerTarget,CompilerParams} GPUCompiler.runtime_module(::NativeCompilerJob) = Runtime -GPUCompiler.method_table(@nospecialize(job::NativeCompilerJob)) = job.config.params.method_table +NativeCompilerConfig = CompilerConfig{NativeCompilerTarget,CompilerParams} # `method_table` can also be a tuple of tables, ordered from most to least specific -GPUCompiler.method_tables(@nospecialize(job::NativeCompilerJob)) = - let mt = job.config.params.method_table +GPUCompiler.method_tables(@nospecialize(config::NativeCompilerConfig)) = + let mt = config.params.method_table mt isa Tuple ? mt : (mt,) end +GPUCompiler.method_tables(@nospecialize(job::NativeCompilerJob)) = + GPUCompiler.method_tables(job.config) GPUCompiler.can_safepoint(@nospecialize(job::NativeCompilerJob)) = job.config.params.entry_safepoint # Every mode ends up in an ORC JIT: `patch` emits definitions for `load` to write after adding @@ -80,11 +82,15 @@ function create_job(@nospecialize(func), @nospecialize(types); entry_safepoint::Bool=false, method_table=test_method_table, relocations::Symbol=:bake, jlruntime::Bool=true, kwargs...) config_kwargs, kwargs = GPUToolbox.partition_kwargs(kwargs, GPUCompiler.CONFIG_KWARGS) - source = methodinstance(typeof(func), Base.to_tuple_type(types), Base.get_world_counter()) target = NativeCompilerTarget(;jlruntime) params = CompilerParams(entry_safepoint, method_table, relocations) config = CompilerConfig(target, params; kernel=false, config_kwargs...) - CompilerJob(source, config), kwargs + # look the function up like inference looks up what it calls, so that an overlay of the + # function itself is compiled + world = Base.get_world_counter() + source = methodinstance(typeof(func), Base.to_tuple_type(types), + GPUCompiler.method_table_view(config, world)) + CompilerJob(source, config, world), 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 380c96aa..c5246389 100644 --- a/test/native.jl +++ b/test/native.jl @@ -394,11 +394,12 @@ end @test_throws "using Cthulhu" GPUCompiler.code_typed(job; interactive=true) calls = [] - GPUCompiler.descender[] = (sig; kwargs...) -> push!(calls, (sig, NamedTuple(kwargs))) + GPUCompiler.descender[] = (mi; kwargs...) -> push!(calls, (mi, NamedTuple(kwargs))) GPUCompiler.code_typed(job; interactive=true, optimize=false) GPUCompiler.code_warntype(job; interactive=true) @test length(calls) == 2 - @test all(((sig, _),) -> sig == Tuple{typeof(mod.kernel), Int}, calls) + # ... with the method instance that is compiled, not its signature to look up again + @test all(((mi, _),) -> mi === job.source, calls) @test all(((_, kw),) -> kw.interp isa GPUCompiler.GPUInterpreter, calls) @test calls[1][2].warntype == false && calls[1][2].optimize == false @test calls[2][2].warntype == true @@ -3331,6 +3332,162 @@ end interpreter_type((mod.method_table, mod.other_method_table, mod.method_table)) end +@testset "kernel overrides" begin + mod = @eval module $(gensym()) + Base.Experimental.@MethodTable(method_table) + + kernel() = 0 + Base.Experimental.@overlay method_table kernel() = 1 + end + + # an overlay of the function to compile is found through the view of its config + # (JuliaGPU/GPUCompiler.jl#208) + @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) + @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) + + # ... also when its code is generated + mod = @eval module $(gensym()) + Base.Experimental.@MethodTable(method_table) + + kernel(x) = 0 + Base.Experimental.@overlay method_table @generated kernel(x) = :(x + 1) + end + job, _ = Native.create_job(mod.kernel, (Int,); mod.method_table) + lowered = only(GPUCompiler.code_lowered(job)) + @test any(stmt -> Meta.isexpr(stmt, :call) && 1 in stmt.args, lowered.code) + + # the function is looked up through the same view as the calls it makes + mod = @eval module $(gensym()) + using ..GPUCompiler + Base.Experimental.@MethodTable(method_table) + Base.Experimental.@MethodTable(other_method_table) + kernel() = 0 + function only_overlay end + Base.Experimental.@overlay other_method_table only_overlay() = 3 + @noinline child() = 0 + Base.Experimental.@overlay method_table @noinline child() = 1 + function parent() + ptr = GPUCompiler.deferred_codegen(Val(typeof(child)), Val(Tuple{})) + ccall(ptr, Int, ()) + end + end + tables = (mod.method_table, mod.other_method_table) + job, _ = Native.create_job(mod.kernel, (); method_table=tables) + config_view = GPUCompiler.method_table_view(job.config, job.world) + job_view = GPUCompiler.method_table_view(job) + @test typeof(config_view) == typeof(job_view) + @test config_view.world == job_view.world == job.world + @test config_view.tables == job_view.tables == collect(tables) + @test methodinstance(typeof(mod.kernel), Tuple{}, GPUCompiler.method_table_view(job)) === + methodinstance(typeof(mod.kernel), Tuple{}, job.world) === job.source + + # the overlay is picked up when it is added after compiling the function + @test @filecheck begin + @check_label "@julia_kernel" + @check "ret i64 0" + Native.code_llvm(mod.kernel, Tuple{}; method_table=tables) + end + @eval mod Base.Experimental.@overlay other_method_table kernel() = 1 + @test @filecheck begin + @check_label "@{{(julia|j)_+kernel_[0-9]+}}" + @check "ret i64 1" + Native.code_llvm(mod.kernel, Tuple{}; method_table=tables) + end + # ... but not by a launch in a world from before it. `cached_lookup` caches by the world + # it is called in, which is the one to look the function up in. + @eval mod late() = 0 + lookup() = let world = GPUCompiler.tls_world_age() + mi = methodinstance(typeof(mod.late), Tuple{}, + GPUCompiler.method_table_view(job.config, world)) + isdefined(mi.def, :external_mt) ? 1 : 0 + end + launch() = GPUCompiler.cached_lookup(lookup, Int, typeof(mod.late), Tuple{}, nothing) + old_world = Base.get_world_counter() + @eval mod Base.Experimental.@overlay method_table late() = 1 + @test Base.invoke_in_world(old_world, launch) == 0 + @test Base.invokelatest(launch) == 1 + @test Base.invoke_in_world(old_world, launch) == 0 + + # ... from the first table that has one + @eval mod Base.Experimental.@overlay method_table kernel() = 2 + @test @filecheck begin + @check_label "@{{(julia|j)_+kernel_[0-9]+}}" + @check "ret i64 2" + Native.code_llvm(mod.kernel, Tuple{}; method_table=tables) + end + + # a function that only has an overlay method + @test @filecheck begin + @check_label "@{{(julia|j)_+only_overlay_[0-9]+}}" + @check "ret i64 3" + Native.code_llvm(mod.only_overlay, Tuple{}; method_table=tables) + end + @test_throws MethodError Native.create_job(mod.only_overlay, (); mod.method_table) + @test_throws MethodError methodinstance(typeof(mod.only_overlay), Tuple{}, job.world) + + # deferred compilation looks up what to compile in the tables of the job that asks + @test @filecheck begin + @check_label "define {{.*}} @{{(julia|j)_+child_[0-9]+}}" + @check "ret i64 1" + Native.code_llvm(mod.parent, Tuple{}; method_table=tables, dump_module=true) + end +end + +@testset "method tables of a back-end that only defines them for jobs" begin + mod = @eval module $(gensym()) + using ..GPUCompiler + import ..Native + Base.Experimental.@MethodTable(method_table) + + struct LegacyParams <: AbstractCompilerParams end + const LegacyJob = CompilerJob{NativeCompilerTarget,LegacyParams} + GPUCompiler.runtime_module(::LegacyJob) = Native.Runtime + GPUCompiler.method_tables(::LegacyJob) = (method_table,) + + kernel() = child() + @inline child() = 0 + Base.Experimental.@overlay method_table child() = 1 + Base.Experimental.@overlay method_table kernel() = 2 + end + config = CompilerConfig(NativeCompilerTarget(), mod.LegacyParams(); kernel=false) + world = Base.get_world_counter() + compiled(source) = JuliaContext() do ctx + string(GPUCompiler.compile(:llvm, CompilerJob(source, config, world))[1]) + end + + # the compiler uses the tables for the calls in the code + @test occursin("ret i64 1", compiled(methodinstance(typeof(mod.kernel), Tuple{}, world))) + # ... but the view of the config doesn't know them, and finds Julia's method + view = GPUCompiler.method_table_view(config, world) + @test methodinstance(typeof(mod.kernel), Tuple{}, view) === + methodinstance(typeof(mod.kernel), Tuple{}, world) + # ... unlike the view of a job + job = CompilerJob(methodinstance(typeof(mod.kernel), Tuple{}, world), config, world) + source = methodinstance(typeof(mod.kernel), Tuple{}, GPUCompiler.method_table_view(job)) + @test occursin("ret i64 2", compiled(source)) +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