Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions ext/CthulhuExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/driver.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion src/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
56 changes: 44 additions & 12 deletions src/interface.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
50 changes: 38 additions & 12 deletions src/jlgen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -64,38 +64,53 @@ 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
always return the same result. If the `world` argument is not specified, the look-up is
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"
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions src/native.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)...)

Expand Down
23 changes: 9 additions & 14 deletions src/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down
66 changes: 47 additions & 19 deletions src/reflection_compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 0 additions & 11 deletions src/validation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading