diff --git a/.github/workflows/Test.yml b/.github/workflows/Test.yml index 9681d16d..5e7f7801 100644 --- a/.github/workflows/Test.yml +++ b/.github/workflows/Test.yml @@ -76,12 +76,29 @@ jobs: done - name: Run tests + if: matrix.version != '1.10' uses: julia-actions/julia-runtest@v1 with: coverage: ${{ matrix.coverage != 'false' }} env: JULIA_LLVM_ARGS: ${{ matrix.llvm_args }} + # TODO: remove once GPUToolbox 3.9 is registered (JuliaGPU/GPUToolbox.jl#50). Julia 1.10 + # ignores `[sources]`, so install it by URL and run the tests in the test environment. + - name: Run tests (Julia 1.10) + if: matrix.version == '1.10' + shell: bash + run: | + julia --project=test -e 'using Pkg + Pkg.add(url="https://github.com/JuliaGPU/GPUToolbox.jl", rev="tb/binding-overlays") + Pkg.develop(path=".")' + # precompile with the test flags, like Pkg.test does, so Aqua's persistent-task + # check doesn't have to build packages within its time limit + julia --project=test --check-bounds=yes --code-coverage=user -e 'using Pkg; Pkg.precompile()' + julia --project=test --check-bounds=yes --code-coverage=user test/runtests.jl + env: + JULIA_LLVM_ARGS: ${{ matrix.llvm_args }} + - name: Process coverage # CoverageTools 1.4.1 uses a PkgLoadSpec field renamed in Julia 1.14. if: matrix.version != 'nightly' && matrix.coverage != 'false' diff --git a/Project.toml b/Project.toml index 5ec60c84..388e590a 100644 --- a/Project.toml +++ b/Project.toml @@ -9,6 +9,7 @@ projects = ["test"] [deps] CompilerCaching = "9db33cc3-5358-4881-8759-fa4194144afd" ExprTools = "e2ba6199-217a-4e67-a87a-7c52f15ade04" +GPUToolbox = "096a3bc2-3ced-46d0-87f4-dd12716f4bfc" InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240" LLVM = "929cbde3-209d-540e-8aea-75f648917ca0" Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb" @@ -35,6 +36,11 @@ NVVM = "423072a2-8eda-41a8-b560-ab106c23935b" SPIRV_LLVM_Backend_jll = "4376b9bf-cff8-51b6-bb48-39421dff0d0c" SPIRV_LLVM_Translator_jll = "4a5d46fc-d8cf-5151-a261-86b458210efb" +# TODO: remove once GPUToolbox 3.9 is registered (JuliaGPU/GPUToolbox.jl#50) +# TODO: remove once GPUToolbox 3.9 is registered (JuliaGPU/GPUToolbox.jl#50) +[sources] +GPUToolbox = {url = "https://github.com/JuliaGPU/GPUToolbox.jl", rev = "tb/binding-overlays"} + [extensions] CthulhuExt = "Cthulhu" HighlightsExt = "Highlights" @@ -44,6 +50,7 @@ AMDGPU_LLVM_Backend_jll = "23.1.3" CompilerCaching = "0.4, 0.5, 0.6" Cthulhu = "2, 3" ExprTools = "0.1" +GPUToolbox = "3.9" Highlights = "0.6" InteractiveUtils = "1" LLVM = "10.4" diff --git a/ext/CthulhuExt.jl b/ext/CthulhuExt.jl index d81ecd9f..a524c208 100644 --- a/ext/CthulhuExt.jl +++ b/ext/CthulhuExt.jl @@ -10,6 +10,32 @@ if isdefined(Cthulhu, :AbstractProvider) Cthulhu.AbstractProvider(interp::GPUInterpreter) = Cthulhu.DefaultProvider(interp) end +# Cthulhu infers with an interpreter of its own that wraps ours, and that creates the frames. +# Their reads of overlaid bindings have to be redirected like in the frames we create (see +# bindings.jl), or the code shown is not the code that is compiled. +const CC = GPUCompiler.CC +@static if VERSION >= v"1.11-" + function CC.InferenceState(result::CC.InferenceResult, cache_mode::UInt8, + interp::Cthulhu.CthulhuInterpreter) + sv = @invoke CC.InferenceState(result::CC.InferenceResult, cache_mode::UInt8, + interp::CC.AbstractInterpreter) + sv === nothing && return nothing + native = interp.native + native isa GPUInterpreter && GPUCompiler.redirect_binding_reads!(native, sv) + return sv + end +else + function CC.InferenceState(result::CC.InferenceResult, cache::Symbol, + interp::Cthulhu.CthulhuInterpreter) + sv = @invoke CC.InferenceState(result::CC.InferenceResult, cache::Symbol, + interp::CC.AbstractInterpreter) + sv === nothing && return nothing + native = interp.native + native isa GPUInterpreter && GPUCompiler.redirect_binding_reads!(native, sv) + return sv + end +end + descend(@nospecialize(sig); warntype::Bool, kwargs...) = warntype ? Cthulhu.descend_code_warntype(sig; kwargs...) : Cthulhu.descend_code_typed(sig; kwargs...) diff --git a/src/GPUCompiler.jl b/src/GPUCompiler.jl index 1d990120..8e02d191 100644 --- a/src/GPUCompiler.jl +++ b/src/GPUCompiler.jl @@ -76,6 +76,7 @@ include("runtime.jl") # compiler implementation include("deprecated.jl") include("jlgen.jl") +include("bindings.jl") include("irgen.jl") include("exception_sites.jl") include("determinism.jl") diff --git a/src/bindings.jl b/src/bindings.jl new file mode 100644 index 00000000..1bd1cdf9 --- /dev/null +++ b/src/bindings.jl @@ -0,0 +1,405 @@ +# binding overlays: reads of host globals that have another meaning in device code +# +# A back-end declares these with `GPUToolbox.Overlays.@binding_overlay`, in the method tables +# it also keeps its method overlays in. For code compiled with those tables, a read that +# reaches the overlaid binding (the source) is a read of a constant of the back-end (the +# target). It is one more hop in the walk Julia does from a name, through its imports, to +# the binding that holds the value; the target is then read like any constant. +# +# Julia only asks the interpreter about a global during inference: the optimizer and codegen +# look at the binding again. So the read is redirected before inference, in the frame's copy +# of the lowered code, after which every stage sees an ordinary read of the target. + +using GPUToolbox: Overlays + +const EVERY_WORLD = CC.WorldRange(typemin(UInt), typemax(UInt)) + + +## reading bindings in a world + +@static if VERSION >= v"1.12-" + +partition_worlds(partition::Core.BindingPartition) = + CC.WorldRange(partition.min_world, partition.max_world) + +# Follow `binding` through the import partitions that link bindings, as a read does, to the +# binding and partition that hold the value. Also returns the worlds in which every +# partition on the way is the current one. +function walk_binding(world::UInt, binding::Core.Binding) + valid_worlds = EVERY_WORLD + while true + partition = CC.lookup_binding_partition(world, binding) + valid_worlds = CC.intersect(valid_worlds, partition_worlds(partition)) + CC.is_some_binding_imported(CC.binding_kind(partition)) || + return binding, partition, valid_worlds + binding = CC.partition_restriction(partition)::Core.Binding + end +end + +is_global_partition(partition::Core.BindingPartition) = + let kind = CC.binding_kind(partition) + kind == Base.PARTITION_KIND_GLOBAL || kind == Base.PARTITION_KIND_DECLARED + end +# (a constant that is defined in a later world reads as undefined until then) +is_constant_partition(partition::Core.BindingPartition) = + let kind = CC.binding_kind(partition) + CC.is_defined_const_binding(kind) && kind != Base.PARTITION_KIND_BACKDATED_CONST + end + +# What a read of `g` gives in `world`: `:global` and the binding that is loaded from, +# `:constant` and the value, or `:other`. +function read_binding(world::UInt, g::GlobalRef) + binding, partition, valid_worlds = walk_binding(world, convert(Core.Binding, g)) + if is_global_partition(partition) + return :global, binding, valid_worlds + elseif is_constant_partition(partition) + return :constant, CC.partition_restriction(partition), valid_worlds + end + return :other, nothing, valid_worlds +end + +function global_type(world::UInt, binding::Core.Binding) + partition = CC.lookup_binding_partition(world, binding) + CC.binding_kind(partition) == Base.PARTITION_KIND_GLOBAL || return Any + return CC.partition_restriction(partition) +end + +else + +# Without binding partitions, a binding resolves once, and its owner holds the value. +function read_binding(world::UInt, g::GlobalRef) + isdefined(g.mod, g.name) || return :other, nothing, EVERY_WORLD # (resolves it) + binding = ccall(:jl_get_module_binding, Any, (Any, Any, Cint), g.mod, g.name, false) + binding isa Core.Binding && isdefined(binding, :owner) || return :other, nothing, EVERY_WORLD + binding = binding.owner + (; mod, name) = binding.globalref + isconst(mod, name) && return :constant, getglobal(mod, name), EVERY_WORLD + return :global, binding, EVERY_WORLD +end + +global_type(world::UInt, binding::Core.Binding) = + Core.get_binding_type(binding.globalref.mod, binding.globalref.name) + +end + + +## the overlays of a stack of method tables + +@static if VERSION >= v"1.14.0-DEV.3088" + find_declarations(mt::Core.MethodTable, world::UInt) = + CC._findall(Overlays.binding_overlay_signature(mt), mt, world, -1, false) +else + find_declarations(mt::Core.MethodTable, world::UInt) = + CC._findall(Overlays.binding_overlay_signature(mt), mt, world, -1) +end + +# Code that looked up the declarations in `tables` depends on none being added there ... +function record_declaration_lookups!(edges::Vector{Any}, tables::Tuple) + for mt in tables + record_overlay_lookup!(edges, Overlays.binding_overlay_signature(mt), (mt,)) + end + return +end + +# ... and on the declaration a read selected not being deleted or replaced. That is an +# `invoke` of the method declaring it, which Julia validates in package images (by the +# method's own table) and whose backedge it invalidates when the method goes away. +declaration_instance(method::Method) = CC.specialize_method(method, method.sig, Core.svec()) + +BindingOverlayCache(world::UInt, mtv::CC.MethodTableView) = + BindingOverlayCache(ReentrantLock(), BindingOverlays(world, mtv), + VERSION >= v"1.12-" ? nothing : WeakKeyDict{Any,Vector{Method}}()) + +# the overlays of an interpreter that is derived from `interp`: the same, with the frames +# that depend on them, unless it looks elsewhere +derived_binding_overlays(interp, world::UInt, mtv::CC.MethodTableView) = + world == interp.world && mtv === interp.method_table_view ? + interp.binding_overlays : BindingOverlayCache(world, mtv) + +# The overlays as of now. The tables may have been looked at before a declaration was added +# that isn't visible in the interpreter's world, but that ends the worlds in which the list +# is what it is. Code that is inferred with the list has to know. +function current_binding_overlays(interp::GPUInterpreter) + cache = interp.binding_overlays + overlays = @lock cache.lock cache.overlays + overlays.counter == Base.get_world_counter() && return overlays + overlays = BindingOverlays(interp.world, interp.method_table_view) + @lock cache.lock begin + cache.overlays.counter < overlays.counter && (cache.overlays = overlays) + end + return overlays +end + +function BindingOverlays(world::UInt, mtv::CC.MethodTableView) + counter = Base.get_world_counter() + list = BindingOverlay[] + valid_worlds = EVERY_WORLD + tables = overlay_tables(mtv) + tables === nothing && (tables = ()) + for mt in tables + result = find_declarations(mt, world)::CC.MethodLookupResult + valid_worlds = CC.intersect(valid_worlds, result.valid_worlds) + first_in_table = length(list) + 1 + for match in result.matches + method = (match::Core.MethodMatch).method + source, target = Overlays.binding_overlay_refs(method) + overlay, worlds = BindingOverlay(world, method, source, target) + valid_worlds = CC.intersect(valid_worlds, worlds) + if overlay.active + for i in first_in_table:length(list) + other = list[i] + other.active && other.binding === overlay.binding && + other.object === overlay.object && + error("""Binding overlays in $mt apply to the same reads: + - $(other.source), declared at $(other.method.file):$(other.method.line) + - $(overlay.source), declared at $(method.file):$(method.line)""") + end + end + push!(list, overlay) + end + end + return BindingOverlays(list, valid_worlds, counter) +end + +# A declaration whose source or target doesn't qualify in this world (anymore) is kept, but +# inactive: code still depends on what its source is bound to. +function BindingOverlay(world::UInt, method::Method, source::GlobalRef, target::GlobalRef) + target_kind, value, valid_worlds = read_binding(world, target) + kind, read, worlds = read_binding(world, source) + valid_worlds = CC.intersect(valid_worlds, worlds) + if target_kind !== :constant + return BindingOverlay(method, source, target, nothing, nothing, false), valid_worlds + elseif kind === :global && (read::Core.Binding).globalref == source + active = value isa global_type(world, read) + return BindingOverlay(method, source, target, read, nothing, active), valid_worlds + elseif kind === :constant && Overlays.has_identity(read) + return BindingOverlay(method, source, target, nothing, read, true), valid_worlds + end + return BindingOverlay(method, source, target, nothing, nothing, false), valid_worlds +end + +# The overlay that applies to a read of `g`, and whether one could: reads of functions, +# types, modules and constants without identity are never overlaid, so the code that makes +# them doesn't depend on the overlays. +# - A read of a global is overlaid by binding. Compiled code loads from the binding, and +# Julia invalidates it when a name comes to refer to another one (from 1.14 on, where +# the binding is part of `binding_access_key`). +# - A read of a constant is overlaid by the object it gives. For constants Julia only tracks +# the value: code is not invalidated when a name moves between bindings that hold the +# same value. So the overlay applies to every name bound to the object. +function find_overlay(overlays::BindingOverlays, world::UInt, g::GlobalRef) + kind, read, valid_worlds = read_binding(world, g) + if kind === :global + for overlay in overlays.list + overlay.active && overlay.binding === read && return overlay, true, valid_worlds + end + return nothing, true, valid_worlds + elseif kind === :constant && Overlays.has_identity(read) + for overlay in overlays.list + overlay.active && overlay.object === read && return overlay, true, valid_worlds + end + return nothing, true, valid_worlds + end + return nothing, false, valid_worlds +end + + +## static reads in lowered code + +@static if VERSION >= v"1.14-" + narrow_valid_worlds!(sv::CC.InferenceState, world::UInt, worlds::CC.WorldRange) = + CC.update_valid_age!(sv, world, worlds) +else + narrow_valid_worlds!(sv::CC.InferenceState, world::UInt, worlds::CC.WorldRange) = + CC.update_valid_age!(sv, worlds) +end + +function constant_value(world::UInt, g::GlobalRef) + kind, value, valid_worlds = read_binding(world, g) + return kind === :constant ? Some{Any}(value) : nothing, valid_worlds +end + +# `M.name` and `getglobal(M, :name)` read the binding `name` in `M` if `M` names a constant +# module (or is such a read itself, as in `A.B.name`) and the name is a literal. Until Julia +# 1.12, lowering resolved `M.name` to a `GlobalRef` itself. Returns that `GlobalRef`, and the +# worlds in which the statement means this. `code` is the lowered code as the method has it: +# an operand that was redirected is a module the overlay provides, not one the code names. +# +# `M.name` is taken to be what Base defines it as, a read of the global. A back-end that +# overlays `getproperty` for modules isn't supported. +# +# A module that inference only knows to be constant doesn't count. A copy of a function +# that is specialized on a constant module would then read the overlay, where the generic +# one reads the host binding at run time. +function static_module_read(interp::GPUInterpreter, code::Vector{Any}, @nospecialize(stmt)) + stmt isa Expr && stmt.head === :call && length(stmt.args) == 3 || return nothing + world = get_inference_world(interp) + f, m, name = stmt.args + name isa QuoteNode && (name = name.value) + name isa Symbol || return nothing + # from 1.12 on, lowering gives every `GlobalRef` read a statement of its own + f isa Core.SSAValue && (f = code[f.id]) + f isa GlobalRef || return nothing + f, valid_worlds = constant_value(world, f) + f === nothing && return nothing + f = something(f) + (f === Base.getproperty || f === Core.getglobal) || return nothing + m isa Core.SSAValue && (m = code[m.id]) + if !(m isa Module) + if !(m isa GlobalRef) + read = static_module_read(interp, code, m) + read === nothing && return nothing + m, worlds = read + valid_worlds = CC.intersect(valid_worlds, worlds) + end + m, worlds = constant_value(world, m) + m === nothing && return nothing + m = something(m) + m isa Module || return nothing + valid_worlds = CC.intersect(valid_worlds, worlds) + end + return GlobalRef(m, name), valid_worlds +end + +# Make the reads of overlaid bindings in a frame's lowered code reads of their targets, and +# record what that depends on. +# +function redirect_binding_reads!(interp::GPUInterpreter, sv::CC.InferenceState) + overlay_tables(interp.method_table_view) in (nothing, ()) && return sv + overlays = current_binding_overlays(interp) + world = get_inference_world(interp) + code = sv.src.code + # (statements are rewritten in place, and may be nested) + lowered = Any[stmt isa Expr ? copy(stmt) : stmt for stmt in code] + # after `:latestworld`, reads are not resolved in the world code is inferred in + any(stmt -> Meta.isexpr(stmt, :latestworld), code) && return sv + depends = Ref(false) + + # the target for a read of `g`, or `g` + function redirect(g::GlobalRef, worlds::CC.WorldRange=EVERY_WORLD) + overlay, could, read_worlds = find_overlay(overlays, world, g) + could || return g + if !depends[] + depends[] = true + # This code depends on the set of overlays: declaring one that applies to this + # read inserts a method, and should invalidate it ... + narrow_valid_worlds!(sv, world, overlays.valid_worlds) + @static if VERSION >= v"1.12-" + record_declaration_lookups!(sv.edges, overlay_tables(interp.method_table_view)) + # ... and on what the sources are bound to + for overlay in overlays.list + push!(sv.edges, convert(Core.Binding, overlay.source)) + end + else + # (these edges can only be added when the frame is finished; before 1.12, + # there are no dependencies on bindings) + interp.binding_overlays.dependents[sv] = Method[] + end + end + overlay === nothing && return g + narrow_valid_worlds!(sv, world, CC.intersect(worlds, read_worlds)) + # ... on the declaration that applies + @static if VERSION >= v"1.12-" + CC.add_invoke_edge!(sv.edges, overlay.method.sig, + declaration_instance(overlay.method)) + else + selected = interp.binding_overlays.dependents[sv] + overlay.method in selected || push!(selected, overlay.method) + end + @static if VERSION >= v"1.12-" + # ... on what the name refers to (Julia finds the `GlobalRef`s in a method's + # source itself, but not the binding that `M.name` names), and on the target + push!(sv.edges, convert(Core.Binding, g)) + push!(sv.edges, convert(Core.Binding, overlay.target)) + end + # Like code that calls an overlay method, this computes something else than the + # host would, so it may not be evaluated by running host code. (The other half of + # that rule, the interpreter having overlays at all, holds: they are declared in + # its method tables.) + sv.ipo_effects = CC.Effects(sv.ipo_effects; nonoverlayed=OVERLAYED) + return overlay.target + end + + for i in eachindex(code) + stmt = code[i] + rhs = Meta.isexpr(stmt, :(=)) ? stmt.args[2] : stmt + if rhs isa GlobalRef + new = redirect(rhs) + elseif rhs === nothing || Meta.isexpr(rhs, :isdefined) + continue # (`isdefined` asks about the host binding) + else + new = rhs + read = static_module_read(interp, lowered, rhs) + if read !== nothing + target = redirect(read...) + target === read[1] || (new = target) + end + if new === rhs + # the operands that Julia's own scan for `GlobalRef`s in a method looks at, + # which leaves out the binding that a store assigns to + urs = CC.userefs(rhs) + it = CC.iterate(urs) + while it !== nothing + ur, state = it + op = CC.getindex(ur) + if op isa GlobalRef + target = redirect(op) + target === op || CC.setindex!(ur, target) + end + it = CC.iterate(urs, state) + end + new = CC.getindex(urs) + end + end + new === rhs && continue + code[i] = Meta.isexpr(stmt, :(=)) ? Expr(:(=), stmt.args[1], new) : new + end + return sv +end + +const OVERLAYED = @static VERSION >= v"1.11-" ? CC.ALWAYS_FALSE : false + +# Frames for methods are created through this constructor, with a copy of the method's +# source of their own: the ones for calls, for constant propagation, and for reflection. +# (Julia also creates frames from given source, for top-level code.) +@static if VERSION >= v"1.11-" + function CC.InferenceState(result::CC.InferenceResult, cache_mode::UInt8, + interp::GPUInterpreter) + sv = @invoke CC.InferenceState(result::CC.InferenceResult, cache_mode::UInt8, + interp::CC.AbstractInterpreter) + sv === nothing && return nothing + return redirect_binding_reads!(interp, sv) + end +else + function CC.InferenceState(result::CC.InferenceResult, cache::Symbol, + interp::GPUInterpreter) + sv = @invoke CC.InferenceState(result::CC.InferenceResult, cache::Symbol, + interp::CC.AbstractInterpreter) + sv === nothing && return nothing + return redirect_binding_reads!(interp, sv) + end +end + +@static if VERSION < v"1.12-" + # the dependencies of a frame on the binding overlays (see `redirect_binding_reads!`). + # These are added after the ones for the frame's own calls, which would otherwise get a + # missing-method edge for the signature of a declaration too, which Julia 1.10 and 1.11 + # don't tell apart from the `invoke` edge in package images. + function add_binding_overlay_dependencies!(interp::GPUInterpreter, sv::CC.InferenceState, + edges::Vector{Any}) + dependents = interp.binding_overlays.dependents::WeakKeyDict{Any,Vector{Method}} + selected = pop!(dependents, sv, nothing) + selected === nothing && return + record_declaration_lookups!(edges, overlay_tables(interp.method_table_view)) + for method in selected + mi = declaration_instance(method) + push!(edges, method.sig, mi) + @static if !HAS_INTEGRATED_CACHE + # GPUCompiler's own cache learns of invalidations through callbacks on the + # instances it depends on, which this one, never compiled, doesn't have yet + add_codecache_callback!(interp.code_cache, mi) + end + end + return + end +end diff --git a/src/interface.jl b/src/interface.jl index ac764f5d..a168bdae 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -701,6 +701,21 @@ 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. +The tables also hold the job's binding overlays, declared with +`GPUToolbox.Overlays.@binding_overlay`: host globals that read as a constant of the back-end +in the code that is compiled for the job, such as `Base.stdout` as a handle to the device's +output stream, or a lookup table that Base keeps in a `Vector` as a tuple. They are looked +up like methods: the first table that has an overlay for a binding provides it, and +declaring, replacing or deleting one invalidates the code that depends on it, which is +compiled again when it is next needed. See the macro's documentation for which bindings and +reads this applies to, and for what isn't tracked. `M.name` is taken to be a read of the global, as +Base defines it: overlaying `getproperty` for modules is not supported together with binding +overlays. + +!!! warning + + Binding overlays are experimental. Their semantics may change in a minor release. + Like `method_table`, this may only depend on the job's `target` and `params` (see [`cache_owner`](@ref)). """ diff --git a/src/jlgen.jl b/src/jlgen.jl index 0ed70f5f..09ecf2a4 100644 --- a/src/jlgen.jl +++ b/src/jlgen.jl @@ -272,6 +272,39 @@ get_method_table_view(world::UInt, mt::CC.MethodTable) = CC.OverlayMethodTable(w # VERSION >= v"1.14.0-DEV.1691" const INFERENCE_CACHE_TYPE = isdefined(CC, :InferenceCache) ? CC.InferenceCache : Vector{CC.InferenceResult} +# A host binding that reads as a constant of the back-end in device code (see bindings.jl). +struct BindingOverlay + # the method that declares it + method::Method + source::GlobalRef + target::GlobalRef + # what makes a read one of the source: the binding it loads from if the source is a + # global, or the object it gives if the source is a constant + binding::Union{Nothing,Core.Binding} + object::Any + active::Bool +end + +# The binding overlays in an interpreter's method tables, in its world, from the most to the +# least specific table, as found when the world counter was at `counter`. +struct BindingOverlays + list::Vector{BindingOverlay} + valid_worlds::CC.WorldRange + counter::UInt +end + +# What an interpreter, and the ones derived from it, know about their binding overlays. +mutable struct BindingOverlayCache + lock::ReentrantLock + # the latest look at the tables: a declaration since then may have ended the worlds in + # which the list is what it is + overlays::BindingOverlays + # frames whose code depends on the overlays, with the declarations their reads selected, + # until they are finished. Only used before Julia 1.12, where these dependencies can't be + # recorded in the frame. + dependents::Union{Nothing,WeakKeyDict{Any,Vector{Method}}} +end + """ GPUInterpreter @@ -287,6 +320,7 @@ are attached lazily when looked up (see [`cached_results`](@ref)). struct GPUInterpreter{MTV<:CC.MethodTableView} <: CC.AbstractInterpreter world::UInt method_table_view::MTV + binding_overlays::BindingOverlayCache @static if HAS_INTEGRATED_CACHE owner::Any @@ -313,8 +347,8 @@ function GPUInterpreter(world::UInt=Base.get_world_counter(); julia_ir_passes::Tuple=()) @assert world <= Base.get_world_counter() return GPUInterpreter{typeof(method_table_view)}( - world, method_table_view, owner, INFERENCE_CACHE_TYPE(), - inf_params, opt_params, always_inline, julia_ir_passes) + world, method_table_view, BindingOverlayCache(world, method_table_view), owner, + INFERENCE_CACHE_TYPE(), inf_params, opt_params, always_inline, julia_ir_passes) end function GPUInterpreter(interp::GPUInterpreter; @@ -327,8 +361,8 @@ function GPUInterpreter(interp::GPUInterpreter; always_inline::Bool=interp.always_inline, julia_ir_passes::Tuple=interp.julia_ir_passes) return GPUInterpreter{typeof(method_table_view)}( - world, method_table_view, owner, inf_cache, - inf_params, opt_params, always_inline, julia_ir_passes) + world, method_table_view, derived_binding_overlays(interp, world, method_table_view), owner, + inf_cache, inf_params, opt_params, always_inline, julia_ir_passes) end CC.cache_owner(interp::GPUInterpreter) = interp.owner @@ -344,8 +378,8 @@ function GPUInterpreter(world::UInt=Base.get_world_counter(); julia_ir_passes::Tuple=()) @assert world <= Base.get_world_counter() return GPUInterpreter{typeof(method_table_view)}( - world, method_table_view, code_cache, Vector{CC.InferenceResult}(), - inf_params, opt_params, always_inline, julia_ir_passes) + world, method_table_view, BindingOverlayCache(world, method_table_view), code_cache, + Vector{CC.InferenceResult}(), inf_params, opt_params, always_inline, julia_ir_passes) end function GPUInterpreter(interp::GPUInterpreter; @@ -358,8 +392,8 @@ function GPUInterpreter(interp::GPUInterpreter; always_inline::Bool=interp.always_inline, julia_ir_passes::Tuple=interp.julia_ir_passes) return GPUInterpreter{typeof(method_table_view)}( - world, method_table_view, code_cache, inf_cache, - inf_params, opt_params, always_inline, julia_ir_passes) + world, method_table_view, + derived_binding_overlays(interp, world, method_table_view), code_cache, inf_cache, inf_params, opt_params, always_inline, julia_ir_passes) end CC.code_cache(interp::GPUInterpreter) = WorldView(interp.code_cache, interp.world) @@ -607,8 +641,10 @@ end # 1.11: backedges are stored when finishing the frame, after optimization function CC.finish!(interp::GPUInterpreter, caller::CC.InferenceState) tables = overlay_tables(interp.method_table_view) - tables === nothing || isempty(tables) || + if tables !== nothing && !isempty(tables) add_overlay_dependencies!(caller.stmt_edges[1], tables) + add_binding_overlay_dependencies!(interp, caller, caller.stmt_edges[1]) + end return @invoke CC.finish!(interp::CC.AbstractInterpreter, caller::CC.InferenceState) end else @@ -617,8 +653,10 @@ else function CC.finish(me::CC.InferenceState, interp::GPUInterpreter) ret = @invoke CC.finish(me::CC.InferenceState, interp::CC.AbstractInterpreter) tables = overlay_tables(interp.method_table_view) - tables === nothing || isempty(tables) || + if tables !== nothing && !isempty(tables) add_overlay_dependencies!(me.stmt_edges[1]::Vector{Any}, tables) + add_binding_overlay_dependencies!(interp, me, me.stmt_edges[1]::Vector{Any}) + end return ret end end diff --git a/test/Project.toml b/test/Project.toml index f60efd82..e02dc67b 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -26,5 +26,9 @@ demumble_jll = "1e29f10c-031c-5a83-9565-69cddfc27673" [compat] Aqua = "0.8" -GPUToolbox = "3.8" +GPUToolbox = "3.9" ParallelTestRunner = "2" + +# TODO: remove once GPUToolbox 3.9 is registered (JuliaGPU/GPUToolbox.jl#50) +[sources] +GPUToolbox = {url = "https://github.com/JuliaGPU/GPUToolbox.jl", rev = "tb/binding-overlays"} diff --git a/test/native/bindings.jl b/test/native/bindings.jl new file mode 100644 index 00000000..530d1655 --- /dev/null +++ b/test/native/bindings.jl @@ -0,0 +1,441 @@ +import GPUToolbox +using GPUToolbox.Overlays: @binding_overlay + +# LLVM IR for `f`, compiled like a back-end does: inference results are cached, and code +# that uses a host global or object is invalid +function device_ir(f, types=(); method_table, kwargs...) + job, _ = Native.create_job(f, types; method_table, kwargs...) + JuliaContext() do ctx + ir, meta = GPUCompiler.compile(:llvm, job) + string(ir) + end +end +returns(ir, val) = occursin(Regex("ret i64 $val\\b"), ir) +function invalid(f, types=(); method_table) + try + device_ir(f, types; method_table) + return false + catch err + err isa GPUCompiler.InvalidIRError || rethrow() + return true + end +end + +@testset "binding overlays" begin + +mod = @eval module $(gensym()) + using GPUToolbox.Overlays: @binding_overlay + Base.Experimental.@MethodTable(method_table) + Base.Experimental.@MethodTable(other_table) + + module Host + global G::Int = 1 + const VEC = [1, 2, 3, 4] + const BIG = collect(1:300) + const LATE = [1, 2, 3] + const OLDER = [1, 2, 3] + global LATEG::Int = 1 + own() = G + own_big(i) = BIG[i] + export G, VEC + end + module Outer; import ..Host; end + module Using; using ..Host; g() = G; vec() = VEC[2]; end + module Importing; import ..Host: G, VEC; g() = G; vec() = VEC[2]; end + module Alias; import ..Host; const T = Host.VEC; vec() = T[2]; end + + @binding_overlay method_table Host.G = 100 + @binding_overlay method_table Host.VEC = (10, 20, 30, 40) + @binding_overlay method_table Host.BIG = Tuple(10 .* Host.BIG) + + qualified() = Host.G + nested() = Outer.Host.G + builtin() = getglobal(Host, :G) + @inline pick(flag::Bool) = flag ? Host.G : 0 + propagated() = pick(true) + dynamic(m::Module) = getglobal(m, :G) + dynamic() = dynamic(Host) + ordered() = getglobal(Host, :G, :monotonic) + defined() = isdefined(Host, :G) ? 1 : 0 + store() = (Host.G = 2; Host.G) + + vec() = Host.VEC[2] + vec(i) = Host.VEC[i] + big(i) = Host.BIG[i] + Base.@assume_effects :foldable @noinline folded(i) = Host.VEC[i] + evaluated() = folded(2) + + late() = Host.LATE isa Tuple ? 1 : 0 + lateg() = Host.LATEG + older() = Host.OLDER isa Tuple ? 1 : 0 + + # a global that holds a module, which an overlay replaces by another module + module A; const v = [1]; end + module B; const v = [2]; module N; const v = [3]; end; end + global M::Module = A + @binding_overlay method_table B.v = (20,) + @binding_overlay method_table B.N.v = (30,) + through_overlay() = M.v[1] + through_overlay_nested() = M.N.v[1] + through_overlay_builtin() = getglobal(getglobal(M, :N), :v)[1] + explicit_field() = getfield(Host, :G) +end +mt = mod.method_table + +@testset "globals" begin + # the binding is read by its name, through imports, and qualified + for f in (mod.Host.own, mod.Using.g, mod.Importing.g, mod.qualified, mod.nested, + mod.builtin, mod.propagated) + @test returns(device_ir(f; method_table=mt), 100) + end + + # a module that is passed as a value reads the host binding, also when inference + # knows which module it is; so do reads with a memory order + @test invalid(mod.dynamic; method_table=mt) + @test invalid(mod.ordered; method_table=mt) + @test invalid(mod.explicit_field; method_table=mt) + # ... as does a read through a module that an overlay provides + @eval mod @binding_overlay method_table $(mod).M = B + @test invalid(mod.through_overlay; method_table=mt) + @test invalid(mod.through_overlay_nested; method_table=mt) + @test invalid(mod.through_overlay_builtin; method_table=mt) + # so do stores and `isdefined` + @test invalid(mod.store; method_table=mt) + if VERSION >= v"1.11-" + # (a check that isn't folded, of the host binding) + ci, _ = only(Native.code_typed(mod.defined, (); method_table=mt)) + @test occursin(r"Host(\.|, :)G\b", sprint(show, ci)) + @test !occursin("binding_overlay", sprint(show, ci)) + else + @test returns(device_ir(mod.defined; method_table=mt), 1) + end + + # code compiled without the table, or by Julia, is unaffected + @test invalid(mod.qualified; method_table=mod.other_table) + @test mod.qualified() == 1 + @test only(Base.return_types(mod.qualified, ())) == Int +end + +@testset "constants" begin + # every name that is bound to the object reads the overlay + for f in (mod.vec, mod.Using.vec, mod.Importing.vec, mod.Alias.vec) + @test returns(device_ir(f; method_table=mt), 20) + end + # the tuple is a constant that is indexed at run time (the bounds check isn't valid + # device code for this target) + @test occursin("[4 x i64] [i64 10, i64 20, i64 30, i64 40]", + device_ir(mod.vec, (Int,); method_table=mt, validate=false)) + # ... also when it is too large to be inlined as a constant + @test occursin("[300 x i64]", device_ir(mod.big, (Int,); method_table=mt, validate=false)) + @test occursin("[300 x i64]", + device_ir(mod.Host.own_big, (Int,); method_table=mt, validate=false)) + + # code that reads an overlay is not evaluated by running the host's + @test returns(device_ir(mod.evaluated; method_table=mt), 20) + @test mod.evaluated() == 2 +end + +@testset "reflection" begin + # the target, as a value, as a reference to the constant (before 1.12), or as the + # constant's binding partition (once Julia resolves reads of constants to those) + returned(ci) = let val = (ci.code[end]::Core.ReturnNode).val + val isa QuoteNode && (val = val.value) + val isa GlobalRef ? getglobal(val.mod, val.name) : + @static(isdefined(Core, :BindingPartition) ? val isa Core.BindingPartition : false) ? + val.restriction : val + end + ci, rt = only(Native.code_typed(mod.qualified, (); method_table=mt)) + @test rt === Int + @test returned(ci) == 100 + ci, rt = only(Native.code_typed(mod.vec, (); method_table=mt)) + @test rt === Int + @test returned(ci) == 20 +end + +@testset "stacked tables" begin + tables = (mod.other_table, mt) + @test returns(device_ir(mod.qualified; method_table=tables), 100) + # the first table that has an overlay for a binding provides it + @eval mod @binding_overlay other_table Host.G = 200 + @test returns(device_ir(mod.qualified; method_table=tables), 200) + @test returns(device_ir(mod.qualified; method_table=(mt, mod.other_table)), 100) + @test returns(device_ir(mod.qualified; method_table=mt), 100) +end + +@testset "declaring again" begin + # a declaration is the same however the table and the binding are written + @eval mod const alias = method_table + @eval mod const H = Host + @eval mod @binding_overlay alias H.G = 100 + @test returns(device_ir(mod.qualified; method_table=mt), 100) + @static if VERSION >= v"1.12-" + @eval mod @binding_overlay alias H.G = 300 + @test returns(device_ir(mod.qualified; method_table=mt), 300) + @eval mod @binding_overlay method_table Host.G = 100 + @test returns(device_ir(mod.qualified; method_table=mt), 100) + end +end + +@testset "declaring an overlay invalidates code" begin + late, lateg = mod.late, mod.lateg + @test returns(device_ir(late; method_table=mt), 0) + @test invalid(lateg; method_table=mt) + @eval mod @binding_overlay method_table Host.LATE = Tuple(Host.LATE) + @eval mod @binding_overlay method_table Host.LATEG = 100 + @test returns(device_ir(late; method_table=mt), 1) + @test returns(device_ir(lateg; method_table=mt), 100) + + # ... as does declaring it again, with another value + @static if VERSION >= v"1.12-" + @eval mod @binding_overlay method_table Host.LATEG = 200 + @test returns(device_ir(lateg; method_table=mt), 200) + end + + # code that is compiled for a world from before a declaration isn't used after it + old_job, _ = Native.create_job(mod.older, (); method_table=mt) + @eval mod @binding_overlay method_table Host.OLDER = (1, 2, 3) + JuliaContext() do ctx + @test returns(string(GPUCompiler.compile(:llvm, old_job)[1]), 0) + end + @test returns(device_ir(mod.older; method_table=mt), 1) +end + +@testset "deleting an overlay invalidates code" begin + mod = @eval module $(gensym()) + using GPUToolbox.Overlays: @binding_overlay + Base.Experimental.@MethodTable(method_table) + Base.Experimental.@MethodTable(fallback_table) + module Host + const VEC = [1, 2, 3] + global G::Int = 1 + end + @binding_overlay method_table Host.VEC = (10, 20, 30) + @binding_overlay fallback_table Host.VEC = (40, 50, 60) + @binding_overlay method_table Host.G = 100 + vec() = Host.VEC[2] + g() = Host.G + end + mt, tables = mod.method_table, (mod.method_table, mod.fallback_table) + function declaration(table, source) + sig = GPUToolbox.Overlays.binding_overlay_signature(table) + matches = Base._methods_by_ftype(sig, table, -1, Base.get_world_counter()) + only(m.method for m in matches + if first(GPUToolbox.Overlays.binding_overlay_refs(m.method)) == source) + end + + @test returns(device_ir(mod.vec; method_table=tables), 20) + @test returns(device_ir(mod.g; method_table=mt), 100) + old_job, _ = Native.create_job(mod.vec, (); method_table=tables) + Base.delete_method(declaration(mt, GlobalRef(mod.Host, :VEC))) + Base.delete_method(declaration(mt, GlobalRef(mod.Host, :G))) + # the next table's overlay applies, or none + @test returns(device_ir(mod.vec; method_table=tables), 50) + @test invalid(mod.g; method_table=mt) + # ... but not to code compiled for a world from before the deletion + JuliaContext() do ctx + @test returns(string(GPUCompiler.compile(:llvm, old_job)[1]), 20) + end +end + +# code inferred with one table doesn't depend on the declarations in another +VERSION >= v"1.11-" && @testset "declarations in other tables" begin + mod = @eval module $(gensym()) + using GPUToolbox.Overlays: @binding_overlay + Base.Experimental.@MethodTable(method_table) + Base.Experimental.@MethodTable(other_table) + module Host + const VEC = [1, 2, 3] + const OTHER = [1, 2, 3] + end + @binding_overlay method_table Host.VEC = (10, 20, 30) + vec() = Host.VEC[2] + end + @test returns(device_ir(mod.vec; method_table=mod.method_table), 20) + job, _ = Native.create_job(mod.vec, (); method_table=mod.method_table) + @test check_presence(job.source, GPUCompiler.cache_owner(job)) + @eval mod @binding_overlay other_table Host.OTHER = (4, 5, 6) + @test check_presence(job.source, GPUCompiler.cache_owner(job)) + @eval mod @binding_overlay method_table Host.OTHER = (4, 5, 6) + @test !check_presence(job.source, GPUCompiler.cache_owner(job)) +end + +# GPUToolbox's overlays for the lookup tables of Base and Random +@testset "lookup tables" begin + mod = @eval module $(gensym()) + Base.Experimental.@MethodTable(method_table) + digits(x) = Base.bit_ndigits0z(x % UInt64) + end + tables = (mod.method_table, GPUToolbox.Overlays.lookup_table_overrides) + @test invalid(mod.digits, (Int,); method_table=mod.method_table) + @test occursin("[20 x i64]", device_ir(mod.digits, (Int,); method_table=tables)) +end + +# before Julia 1.12, code doesn't depend on bindings +VERSION >= v"1.12-" && @testset "rebinding invalidates code" begin + mod = @eval module $(gensym()) + using GPUToolbox.Overlays: @binding_overlay + Base.Experimental.@MethodTable(method_table) + module Host + global G::Int = 1 + const VEC = [1, 2, 3] + const A = [1] + export G, VEC + end + module Other; global G::Int = 7; end + module Shadow; using ..Host; g() = G; end + module Reimport; using ..Host; g() = G; end + module ShadowConst; using ..Host; vec() = VEC[2]; end + module Alias; import ..Host; const T = Host.VEC; vec() = T[2]; end + module Qualified; using ..Host; end + qualified() = Qualified.G + const B = [1, 2] + other() = B isa Tuple ? 1 : 0 + direct() = Host.VEC[2] + + @binding_overlay method_table Host.G = 100 + @binding_overlay method_table Host.VEC = (10, 20, 30) + end + mt = mod.method_table + + # a name that referred to an overlaid global becomes a global of its own + @test returns(device_ir(mod.Shadow.g; method_table=mt), 100) + @eval mod.Shadow global G::Int = 5 + @test invalid(mod.Shadow.g; method_table=mt) + # ... also when it was read as `M.name`, which names no binding in the source + @test returns(device_ir(mod.qualified; method_table=mt), 100) + @eval mod.Qualified global G::Int = 5 + @test invalid(mod.qualified; method_table=mt) + + # ... or is imported from elsewhere. Julia 1.12 and 1.13 don't invalidate code for that, + # compiled by Julia or by us (JuliaLang/julia#62452). + @test returns(device_ir(mod.Reimport.g; method_table=mt), 100) + @eval mod.Reimport import ..Other: G + @test invalid(mod.Reimport.g; method_table=mt) broken=(VERSION < v"1.14-") + + # a name that was bound to an overlaid object is bound to the same object otherwise + @test returns(device_ir(mod.ShadowConst.vec; method_table=mt), 20) + @eval mod.ShadowConst const VEC = $(mod.Host.VEC) + @test returns(device_ir(mod.ShadowConst.vec; method_table=mt), 20) + # ... or to another one + @eval mod.ShadowConst const VEC = [7, 8, 9] + @test invalid(mod.ShadowConst.vec; method_table=mt) + + # the source is bound to another object + @test returns(device_ir(mod.Alias.vec; method_table=mt), 20) + @eval mod.Host const VEC = [4, 5, 6] + @test invalid(mod.Alias.vec; method_table=mt) + @test returns(device_ir(mod.direct; method_table=mt), 20) + + # ... also when the declaration didn't apply to anything before that + @eval mod @binding_overlay method_table Host.A = (100,) + @eval mod.Host const A = 0 + @test returns(device_ir(mod.other; method_table=mt), 0) + @eval mod.Host const A = $(mod.B) + @test returns(device_ir(mod.other; method_table=mt), 1) +end + +@testset "ambiguous overlays" begin + mod = @eval module $(gensym()) + using GPUToolbox.Overlays: @binding_overlay + Base.Experimental.@MethodTable(method_table) + module Host + const A = [1] + const B = A + end + @binding_overlay method_table Host.A = (1,) + @binding_overlay method_table Host.B = (2,) + f() = Host.A[1] + end + @test_throws "apply to the same reads" device_ir(mod.f; method_table=mod.method_table) +end + +end + +# binding overlays, and code that was compiled with them, in package images +VERSION >= v"1.11" && precompile_test_harness("binding overlays in package images") do load_path + create_standalone(load_path, "BindingsCompiler", "native.jl") + + write(joinpath(load_path, "BindingsBackend.jl"), :( + module BindingsBackend + import BindingsCompiler + using GPUToolbox.Overlays: @binding_overlay + + Base.Experimental.@MethodTable(method_table) + module Host + global G::Int = 1 + const VEC = [1, 2, 3] + const LATE = [1, 2, 3] + end + @binding_overlay method_table Host.G = 100 + @binding_overlay method_table Host.VEC = (10, 20, 30) + + g() = Host.G + vec() = Host.VEC[2] + late() = Host.LATE isa Tuple ? 1 : 0 + + for f in (g, vec, late) + job, _ = BindingsCompiler.Native.create_job(f, (); method_table) + precompile(job) + end + end) |> string) + Base.compilecache(Base.PkgId("BindingsBackend"), stderr, stdout) + + # a package that adds an overlay to another package's table + write(joinpath(load_path, "BindingsExtension.jl"), :( + module BindingsExtension + import BindingsBackend + using GPUToolbox.Overlays: @binding_overlay + @binding_overlay BindingsBackend.method_table BindingsBackend.Host.LATE = (1, 2, 3) + end) |> string) + Base.compilecache(Base.PkgId("BindingsExtension"), stderr, stdout) + + @eval let + import BindingsCompiler, BindingsBackend + method_table = BindingsBackend.method_table + function ir(f) + job, _ = BindingsCompiler.Native.create_job(f, (); method_table) + JuliaContext() do ctx + string(GPUCompiler.compile(:llvm, job)[1]) + end + end + cached(f) = let (job, _) = BindingsCompiler.Native.create_job(f, (); method_table) + check_presence(job.source, GPUCompiler.cache_owner(job)) + end + function cached_instance(f) + job, _ = BindingsCompiler.Native.create_job(f, (); method_table) + ci = isdefined(job.source, :cache) ? job.source.cache : nothing + while ci !== nothing + ci.owner === GPUCompiler.cache_owner(job) && ci.max_world == typemax(UInt) && + return ci + ci = isdefined(ci, :next) ? ci.next : nothing + end + end + + # the overlays apply, and the code that was inferred with them is still valid + # (Julia 1.11 doesn't revalidate code without edges whose validity starts at the world + # of a declaration, like `late`, which reads no overlay; it is inferred again) + @test cached(BindingsBackend.g) + @test cached(BindingsBackend.vec) + @test cached(BindingsBackend.late) broken=(VERSION < v"1.12-") + restored = cached_instance(BindingsBackend.vec) + @test returns(ir(BindingsBackend.g), 100) + @test returns(ir(BindingsBackend.vec), 20) + @test returns(ir(BindingsBackend.late), 0) + + # deleting a declaration that code from the image read invalidates that code + sig = GPUToolbox.Overlays.binding_overlay_signature(method_table) + declaration = only(m.method for m in Base._methods_by_ftype(sig, method_table, -1, + Base.get_world_counter()) + if first(GPUToolbox.Overlays.binding_overlay_refs(m.method)) == + GlobalRef(BindingsBackend.Host, :VEC)) + Base.delete_method(declaration) + @test restored.max_world < typemax(UInt) + @test_throws GPUCompiler.InvalidIRError Base.invokelatest(ir, BindingsBackend.vec) + + # loading a package that declares an overlay invalidates the code it applies to + import BindingsExtension + @test !cached(BindingsBackend.late) + @test returns(ir(BindingsBackend.late), 1) + @test returns(ir(BindingsBackend.g), 100) + end +end