From cb0c9bc23dcb18b27ba3c965e9aed0a610600651 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Wed, 18 Nov 2026 23:53:59 +0100 Subject: [PATCH 1/2] Don't combine instructions after target finalization `prepare_execution!` ran InstCombine after lowering relocations, i.e. after `finish_ir!`, so it could undo what target finalization prepares for the back-end, e.g. widen narrowed index arithmetic again. Back-ends worked around this by doing such rewrites in `mcgen` instead. Only simplify instructions there now (InstSimplify replaces them with existing values or constants, which folds the loads from baked relocation slots), and drop dead globals without running GlobalOpt. Two things relied on the late InstCombine: loads through a `select` or `phi` of baked slots, which are now folded by selecting between the slots' values, and the cleanup of dead references to boxed constants that SPIR-V and Metal cannot refer to, which now runs during finalization, on the functions those constants are copied into (or, for SPIR-V before LLVM 17, where they are not, on the functions using them). A new test adds an InstCombine canary at the end of `finish_ir!` for every GPU target, and checks that it reaches `mcgen` unchanged. --- src/mcgen.jl | 23 +++++---- src/relocation.jl | 115 +++++++++++++++++++++++++++++++++++++++++++ src/spirv.jl | 18 ++++--- test/finalization.jl | 100 +++++++++++++++++++++++++++++++++++++ test/metal.jl | 5 -- test/native.jl | 64 ++++++++++++++++++++++++ test/spirv.jl | 44 +++++++++++++++-- 7 files changed, 344 insertions(+), 25 deletions(-) create mode 100644 test/finalization.jl diff --git a/src/mcgen.jl b/src/mcgen.jl index d63165f1..f039f4bd 100644 --- a/src/mcgen.jl +++ b/src/mcgen.jl @@ -3,23 +3,25 @@ # Finalize the module for backend emission by collecting and lowering all live relocations. function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module, relocs::Relocations=Relocations()) - # Clean up first so only live relocations get lowered. - function cleanup(; fold_instructions=false) + # This runs after target finalization (`finish_ir!`), whose output must reach the back-end + # as it is: e.g. Metal loads pointers as words, and index narrowing would be undone by + # InstCombine widening the arithmetic again. So only fold the loads from relocation slots + # (see `fold_merged_constant_loads!`), simplify instructions to existing values or + # constants, and drop what is dead; nothing combines or canonicalizes instructions here. + function cleanup(; simplify=false) @dispose pb=PassBuilder() begin - if fold_instructions + if simplify add!(pb, FunctionPassManager()) do fpm - add!(fpm, instcombine_pass(job)) + add!(fpm, InstSimplifyPass()) end end - add!(pb, RecomputeGlobalsAAPass()) - add!(pb, GlobalOptPass()) add!(pb, GlobalDCEPass()) add!(pb, StripDeadPrototypesPass()) - with_llvm_machine(job.config.target) do tm - run!(pb, mod, tm) - end + run!(pb, mod) end end + + # Clean up first so only live relocations get lowered. cleanup() prune_dead_relocations!(mod, relocs) @@ -43,7 +45,8 @@ function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module, freeze!(relocs) # Fold constants exposed by eager lowering, and drop globals the lowering left dead. - cleanup(; fold_instructions=true) + fold_merged_constant_loads!(mod) + cleanup(; simplify=true) has_unresolved_cglobal_loads(mod, relocs) && error("Unresolved cglobal load after relocation lowering") diff --git a/src/relocation.jl b/src/relocation.jl index 46c87c80..5c076ae5 100644 --- a/src/relocation.jl +++ b/src/relocation.jl @@ -585,13 +585,44 @@ function demote_boxed_constants!(@nospecialize(job::CompilerJob), mod::LLVM.Modu can only be kept on the stack of a kernel.""") box_alloca!(f, gv) end + demoted = Set{LLVM.Function}() for gv in boxes slots = Dict{LLVM.Function, LLVM.Value}() replace_global_with_local!(gv, f -> get!(() -> slot(f, gv), slots, f)) + union!(demoted, keys(slots)) end + + # A copy often only feeds the pointer half of an isbits union whose selector says it is + # unused, which back-ends then reject as a reference to a dead stack slot. Fold those + # away here, as nothing combines instructions after target finalization. This runs once: + # there are no boxes left for a later `finish_ir!` of another entry point. + combine_instructions!(job, demoted) return true end +# Fold away the references to boxed constants that are dead, e.g. in the pointer half of an +# isbits union whose selector says it is unused, for back-ends that cannot refer to them but +# where `demote_boxed_constants!` does not work (SPIR-V before LLVM 17). +function fold_dead_box_references!(@nospecialize(job::CompilerJob), mod::LLVM.Module) + users = Set{LLVM.Function}() + for gv in boxed_constants(mod) + using_functions!(users, gv) + end + combine_instructions!(job, users) + return +end + +function combine_instructions!(@nospecialize(job::CompilerJob), fns) + isempty(fns) && return + @dispose pb=PassBuilder() begin + add!(pb, instcombine_pass(job)) + for f in fns + run!(pb, f) + end + end + return +end + # Return the byte offset added by a constant cast or GEP, or `nothing` if it is not static. function constexpr_byte_offset(ce::LLVM.ConstantExpr, dl::LLVM.DataLayout) op = ce.opcode @@ -851,6 +882,90 @@ function bake_relocations!(mod::LLVM.Module, relocs::Relocations) return end +# Fold the loads from constant globals that go through a `select` or `phi` of their addresses, +# as of relocation slots that `bake_relocations!` resolved, by selecting between the values. +# InstSimplify only folds loads that are direct; this runs after target finalization, where +# InstCombine (which would fold them all) must not, and back-ends cannot always take the +# loaded globals (e.g., the Khronos translator rejects private globals in address space 0). +function fold_merged_constant_loads!(mod::LLVM.Module) + changed = false + @dispose builder=IRBuilder() begin + for f in mod.functions, bb in f.blocks, inst in collect(bb.instructions) + inst isa LLVM.LoadInst && !inst.volatile || continue + T = inst.value_type + addr = inst.pointer_operand + addr isa LLVM.Instruction && forwarded_addresses(addr) !== nothing || continue + # (check everything first, so that nothing needs to be undone) + folds_to_constants(T, addr) || continue + value = merged_constant_value!(builder, T, addr, Dict{LLVM.Value,LLVM.Value}()) + replace_uses!(inst, value) + erase!(inst) + changed = true + end + end + return changed +end + +# The constant a load of type `T` from `gv` yields, if `gv` has an initializer that cannot +# be overridden (like a baked relocation slot), and holds a word of that type. +function constant_word(T::LLVMType, gv::LLVM.GlobalVariable) + gv.constant && !isdeclaration(gv) && !gv.externally_initialized || return nothing + gv.linkage in (LLVM.Linkage.Private, LLVM.Linkage.Internal) || return nothing + init = gv.initializer + S = init.value_type + S == T && is_word_type(T) && return init + if T isa LLVM.PointerType && S isa LLVM.IntegerType && is_word_type(S) + return const_inttoptr(init, T) + elseif T isa LLVM.IntegerType && S isa LLVM.PointerType && is_word_type(T) + return const_ptrtoint(init, T) + end + return nothing +end + +# Whether every address that `addr` picks from is such a global. +function folds_to_constants(T::LLVMType, @nospecialize(addr), seen=Set{LLVM.Value}()) + addr in seen && return true + push!(seen, addr) + if addr isa LLVM.ConstantExpr + addr.opcode in (LLVM.Opcode.BitCast, LLVM.Opcode.AddrSpaceCast) || return false + return folds_to_constants(T, addr.operands[1], seen) + elseif addr isa LLVM.GlobalVariable + return constant_word(T, addr) !== nothing + elseif addr isa LLVM.Instruction + forwarded = forwarded_addresses(addr) + forwarded === nothing && return false + return all(a -> folds_to_constants(T, a, seen), forwarded) + end + return false +end + +# The value of type `T` loaded from `addr`, built with `select`s and `phi`s next to those of +# the addresses. Requires `folds_to_constants(T, addr)`. +function merged_constant_value!(builder::IRBuilder, T::LLVMType, @nospecialize(addr), + values::Dict{LLVM.Value,LLVM.Value}) + haskey(values, addr) && return values[addr] + if addr isa LLVM.ConstantExpr || addr isa LLVM.BitCastInst || + addr isa LLVM.AddrSpaceCastInst + return merged_constant_value!(builder, T, addr.operands[1], values) + elseif addr isa LLVM.GlobalVariable + return constant_word(T, addr) + elseif addr isa LLVM.SelectInst + a = merged_constant_value!(builder, T, addr.operands[2], values) + b = merged_constant_value!(builder, T, addr.operands[3], values) + position!(builder, LLVM.after(addr)) + return values[addr] = select!(builder, addr.operands[1], a, b) + elseif addr isa LLVM.PHIInst + # (create the phi first, as loops make it an incoming value of itself) + position!(builder, LLVM.before(addr)) + phi = values[addr] = phi!(builder, T) + for (incoming, block) in addr.incoming + push!(phi.incoming, (merged_constant_value!(builder, T, incoming, values), block)) + end + return phi + end + error("Unexpected address $addr") +end + """ emit_patchable_relocations!(mod, relocs) diff --git a/src/spirv.jl b/src/spirv.jl index c35927f0..20565c2e 100644 --- a/src/spirv.jl +++ b/src/spirv.jl @@ -225,7 +225,11 @@ function finish_ir!(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module, # a module-scope SPIR-V variable cannot live in the address space of the pointers that # refer to Julia's boxed constants (the Function storage class) - LLVM.version() >= v"17" && demote_boxed_constants!(job, mod) + if LLVM.version() >= v"17" + demote_boxed_constants!(job, mod) + else + fold_dead_box_references!(job, mod) + end # SPIR-V cannot express atomic loads and stores of pointers, which is what Julia's # `unordered` heap-reference accesses are (see `demote_unordered_atomics!`) @@ -319,10 +323,10 @@ end format=LLVM.CodeGenFileType.Assembly) target = job.config.target - # (after `prepare_execution!`, whose InstCombine would narrow the widened operations) + # (after the last InstCombine, which would narrow the widened operations) widen_bfloat16!(job, mod) - # (after `prepare_execution!` too, whose InstCombine can form overflow intrinsics) + # (after the last InstCombine too, which can form overflow intrinsics) lower_mul_with_overflow!(mod) # The SPIRV Tools don't handle Julia's debug info, rejecting DW_LANG_Julia... @@ -932,8 +936,8 @@ end # e.g., storing `(flag::Bool, (a, b))` built by inserting `flag`, `a` and `b`, loses `flag` # (intel/intel-graphics-compiler#378, JuliaGPU/OpenCL.jl#502, JuliaGPU/oneAPI.jl#259). # this runs after optimization, where SROA introduces these `insertvalue`s when splitting -# aggregate loads. the InstCombine run in `prepare_execution!` doesn't reconstruct them -# from the flattened form. +# aggregate loads. nothing combines instructions after finalization, which could +# reconstruct them from the flattened form. function flatten_nested_insertvalue!(mod::LLVM.Module) changed = false @tracepoint "flatten nested insertvalue" begin @@ -1160,8 +1164,8 @@ const MUL_HI_TYPES = Dict(8 => ("c", "h"), 16 => ("s", "t"), 32 => ("i", "j"), # which rounding to `bfloat` is correct. # # Julia's `DemoteFloat16` pass widens arithmetic on CPUs, but leaves fast-math instructions, -# intrinsics and conversions alone. This has to run after `prepare_execution!`, whose -# InstCombine narrows `fptrunc(op(fpext x, fpext y))` back to a `bfloat` operation. +# intrinsics and conversions alone. This has to run after the last InstCombine, which +# narrows `fptrunc(op(fpext x, fpext y))` back to a `bfloat` operation. function widen_bfloat16!(@nospecialize(job::CompilerJob{SPIRVCompilerTarget}), mod::LLVM.Module) changed = false diff --git a/test/finalization.jl b/test/finalization.jl new file mode 100644 index 00000000..2eb0ae24 --- /dev/null +++ b/test/finalization.jl @@ -0,0 +1,100 @@ +# Nothing may combine or canonicalize instructions after target finalization (`finish_ir!`), +# as back-ends rely on its output reaching code generation as it is. Check that for every +# GPU target with a canary added at the end of `finish_ir!`, an exported function multiplying +# by two, which InstCombine would turn into a shift: it has to reach `mcgen` unchanged. + +module Finalization + +using GPUCompiler, LLVM, LLVM.IR, LLVM.Build, Test +using NVPTX_LLVM_Backend_jll, AMDGPU_LLVM_Backend_jll +using SPIRV_LLVM_Backend_jll, SPIRV_LLVM_Translator_jll, SPIRV_Tools_jll +import ..TestRuntime + +struct CanaryParams <: AbstractCompilerParams end +GPUCompiler.runtime_module(::CompilerJob{<:Any,CanaryParams}) = TestRuntime + +const canary = "gpucompiler_canary" +const canary_reached_mcgen = Ref(false) + +function add_canary!(mod::LLVM.Module) + context!(context(mod)) do + T = LLVM.Int32Type() + f = LLVM.Function(mod, canary, LLVM.FunctionType(T, [T])) + @dispose builder=IRBuilder() begin + position!(builder, LLVM.at_end(BasicBlock(f, "entry"))) + ret!(builder, mul!(builder, f.parameters[1], ConstantInt(T, 2))) + end + end +end + +has_canary(mod::LLVM.Module) = + haskey(mod.functions, canary) && + any(inst -> LLVM.opcode(inst) == LLVM.Opcode.Mul, + only(mod.functions[canary].blocks).instructions) + +for T in (PTXCompilerTarget, GCNCompilerTarget, SPIRVCompilerTarget, MetalCompilerTarget) + @eval begin + function GPUCompiler.finish_ir!(job::CompilerJob{$T,CanaryParams}, + mod::LLVM.Module, entry::LLVM.Function) + entry = invoke(GPUCompiler.finish_ir!, + Tuple{CompilerJob{$T}, LLVM.Module, LLVM.Function}, + job, mod, entry) + haskey(mod.functions, canary) || add_canary!(mod) + return entry + end + function GPUCompiler.mcgen(job::CompilerJob{$T,CanaryParams}, mod::LLVM.Module, + format) + canary_reached_mcgen[] = has_canary(mod) + invoke(GPUCompiler.mcgen, Tuple{CompilerJob{$T}, LLVM.Module, typeof(format)}, + job, mod, format) + end + end +end + +function kernel(out::Core.LLVMPtr{Int32,1}, x::Int32) + unsafe_store!(out, x) + return +end + +# an isbits union whose boxed constant SPIR-V and Metal demote onto the stack during +# finalization, which then cleans up after itself +@noinline produce(cond::Bool, value::Int32) = cond ? value : 1.5 +function union_kernel(out::Core.LLVMPtr{Int32,1}, cond::Bool, value::Int32) + x = produce(cond, value) + unsafe_store!(out, Int32(x isa Float64)) + return +end + +targets = Pair{String,Any}["Metal" => MetalCompilerTarget(; macos=v"12.2", metal=v"3.0", air=v"3.0")] +NVPTX_LLVM_Backend_jll.is_available() && push!(targets, "PTX" => PTXCompilerTarget(; cap=v"7.0")) +if SPIRV_LLVM_Backend_jll.is_available() && SPIRV_LLVM_Translator_jll.is_available() && + SPIRV_Tools_jll.is_available() + push!(targets, "SPIR-V (LLVM)" => SPIRVCompilerTarget(; backend=:llvm), + "SPIR-V (Khronos)" => SPIRVCompilerTarget(; backend=:khronos)) +end +if AMDGPU_LLVM_Backend_jll.is_available() && !LLVM.is_asserts() + push!(targets, "GCN" => GCNCompilerTarget(; dev_isa="gfx900")) +end + +@testset "$name" for (name, target) in targets, f in (kernel, union_kernel), + optimize in (true, false) + # (Metal rejects boxed constants before LLVM 17, and SPIR-V unoptimized ones) + f === union_kernel && !(LLVM.version() >= v"17" && target isa MetalCompilerTarget || + (optimize || LLVM.version() >= v"17") && + target isa SPIRVCompilerTarget) && + continue + tt = f === kernel ? Tuple{Core.LLVMPtr{Int32,1}, Int32} : + Tuple{Core.LLVMPtr{Int32,1}, Bool, Int32} + source = methodinstance(typeof(f), tt) + # (unoptimized code still contains calls that validation rejects, e.g. on 1.13) + config = CompilerConfig(target, CanaryParams(); kernel=true, optimize, validate=optimize) + job = CompilerJob(source, config) + canary_reached_mcgen[] = false + JuliaContext() do ctx + _, meta = GPUCompiler.compile(:asm, job) + dispose(meta.ir) + end + @test canary_reached_mcgen[] +end + +end diff --git a/test/metal.jl b/test/metal.jl index 89d12f65..ec97d3bd 100644 --- a/test/metal.jl +++ b/test/metal.jl @@ -974,11 +974,6 @@ end air = sprint(io -> Metal.code_native_table(io, mod.kernel, tt; kernel=true)) @test occursin("reloc_table", air) @test !occursin("load ptr, ptr addrspace(1)", air) - # LLVM 20 folds the comparison of the converted words into one of the words - if LLVM.version() >= v"20" - @test occursin("icmp eq i64", air) - @test !occursin("icmp eq ptr", air) - end end end diff --git a/test/native.jl b/test/native.jl index ff61fc49..ee4fb38e 100644 --- a/test/native.jl +++ b/test/native.jl @@ -2134,6 +2134,70 @@ end end end +@testset "merged constant loads" begin + # loads through a select or phi of baked relocation slots are folded to the selected + # values, as nothing else folds them after target finalization + fold(ir) = Context() do ctx + mod = parse(LLVM.Module, ir) + changed = GPUCompiler.fold_merged_constant_loads!(mod) + LLVM.verify(mod) + return changed, string(mod) + end + if !typed_ptrs + slots = """ + @a = private constant i64 1 + @b = private constant i64 2 + """ + changed, ir = fold(slots * """ + define i64 @f(i1 %c, i1 %d) { + entry: + br i1 %d, label %loop, label %exit + loop: + %p = phi ptr [ @a, %entry ], [ %s, %loop ] + %s = select i1 %c, ptr %p, ptr @b + br i1 %c, label %loop, label %exit + exit: + %q = phi ptr [ @a, %entry ], [ %s, %loop ] + %v = load i64, ptr %q + ret i64 %v + }""") + @test changed + @test !occursin("load", ir) + + # not when one of the addresses is something else, also when only reached through + # a loop, or when a global's initializer could be overridden + for (globals, other) in [(slots, "ptr %x"), (slots * "@w = weak constant i64 3\n", "ptr @w")] + changed, ir = fold(globals * """ + define i64 @f(i1 %c, ptr %x) { + entry: + br label %loop + loop: + %p = phi ptr [ @a, %entry ], [ %s, %loop ], [ $(split(other)[2]), %other ] + %s = select i1 %c, ptr %p, ptr @b + br i1 %c, label %loop, label %other + other: + br i1 %c, label %loop, label %exit + exit: + %v = load i64, ptr %s + ret i64 %v + }""") + @test !changed + @test occursin("load i64", ir) + end + + # nor when the loaded type differs from the value's otherwise than integer and pointer + changed, ir = fold(""" + @a = private constant ptr addrspace(1) null + @b = private constant ptr addrspace(1) null + define ptr @f(i1 %c) { + %p = select i1 %c, ptr @a, ptr @b + %v = load ptr, ptr %p + ret ptr %v + }""") + @test !changed + end +end + @testset "cglobal relocation" begin # JIT-private symbols like `jl_get_pgcstack_resolved` (JuliaLang/julia#61527) cannot # be looked up using `jl_cglobal`, so we should only resolve bindings that are diff --git a/test/spirv.jl b/test/spirv.jl index 715f68ea..f75cde55 100644 --- a/test/spirv.jl +++ b/test/spirv.jl @@ -233,6 +233,38 @@ end end end +@testset "merged cglobal relocations" begin + mod = @eval module $(gensym()) + function kernel(out::Core.LLVMPtr{UInt,1}, cond::Bool) + Base.llvmcall((""" + @jl_float32_type = external global ptr + @jl_float64_type = external global ptr + + define void @entry(ptr addrspace(1) %out, i8 %c) { + %cond = trunc i8 %c to i1 + %addr = select i1 %cond, ptr @jl_float32_type, ptr @jl_float64_type + %value = load ptr, ptr %addr + %word = ptrtoint ptr %value to i64 + store i64 %word, ptr addrspace(1) %out + ret void + } + """, "entry"), Nothing, Tuple{Core.LLVMPtr{UInt,1},Bool}, out, cond) + return + end + end + + # baking the slots of a merged load leaves them as private globals in a SPIR-V address + # space they cannot be in, so the load needs to be folded before translation + if VERSION >= v"1.12.0-DEV.225" # (opaque pointers in `llvmcall`) + @test @filecheck begin + @check "OpSelect" + @check_not "OpVariable %_ptr_Function" + SPIRV.code_native(mod.kernel, Tuple{Core.LLVMPtr{UInt,1},Bool}; backend, + kernel=true, optimize=false, validate=false, dump_module=true) + end + end +end + @testset "boxed union constants" begin mod = @eval module $(gensym()) @noinline produce(cond::Bool, a::Int32) = cond ? a : Int64(7) @@ -415,7 +447,7 @@ end end # the flattened form must survive the passes that run between `finish_ir!` and the - # back end (`prepare_execution!` runs InstCombine) + # back end @test @filecheck begin @check "OpFunction" @check_not "OpCompositeInsert {{.*}} {{[0-9]+}} {{[0-9]+}}{{\$}}" @@ -898,8 +930,8 @@ end end end - # InstCombine forms `llvm.umul.with.overflow` from division-based overflow checks, also - # right before code generation (in `prepare_execution!`) when not optimizing + # InstCombine forms `llvm.umul.with.overflow` from division-based overflow checks. That + # doesn't happen after target finalization, so without optimization the division stays. mod = @eval module $(gensym()) overflows(x::UInt64, y::UInt64) = Base.llvmcall(""" %d = udiv i64 -1, %0 @@ -914,6 +946,12 @@ end @test @filecheck begin @check "OpExtInst {{.*}} u_mul_hi" @check_not "MulExtended" + SPIRV.code_native(mod.kernel, Tuple{Ptr{UInt8}, UInt64, UInt64}; backend, + kernel=true) + end + @test @filecheck begin + @check "OpUDiv" + @check_not "MulExtended" SPIRV.code_native(mod.kernel, Tuple{Ptr{UInt8}, UInt64, UInt64}; backend, kernel=true, optimize=false) end From aa4edfc41170cd8318041c7f436b2e2b7b3a4b78 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Thu, 19 Nov 2026 09:38:54 +0100 Subject: [PATCH 2/2] Drop the dead address graphs of folded relocation loads Folding a load through a loop-carried `phi` and `select` of baked slots left those address instructions behind as a dead cycle, which InstSimplify does not remove. The slots then stayed in the module, where the Khronos translator rejects them. Run ADCE after InstSimplify in `prepare_execution!`; it only deletes instructions, so target finalization still reaches the back-end as is. Also create the value `select` before visiting its operands, as was done for `phi`s: a `select` in a cycle got two values, and a cycle of only `select`s, which is valid in unreachable code, recursed without end. The SPIR-V test now covers a `phi` and a loop-carried cycle too, and also looks for leftover slots ahead of the selected value, which is where the LLVM back-end emits them. --- src/mcgen.jl | 10 +++-- src/relocation.jl | 19 +++++---- test/native.jl | 15 +++++++ test/spirv.jl | 103 +++++++++++++++++++++++++++++++++++----------- 4 files changed, 112 insertions(+), 35 deletions(-) diff --git a/src/mcgen.jl b/src/mcgen.jl index f039f4bd..657ccac9 100644 --- a/src/mcgen.jl +++ b/src/mcgen.jl @@ -4,15 +4,17 @@ function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module, relocs::Relocations=Relocations()) # This runs after target finalization (`finish_ir!`), whose output must reach the back-end - # as it is: e.g. Metal loads pointers as words, and index narrowing would be undone by - # InstCombine widening the arithmetic again. So only fold the loads from relocation slots - # (see `fold_merged_constant_loads!`), simplify instructions to existing values or - # constants, and drop what is dead; nothing combines or canonicalizes instructions here. + # as it is: e.g. index narrowing would be undone by InstCombine widening the arithmetic + # again. So only fold the loads from relocation slots (see `fold_merged_constant_loads!`), + # simplify instructions to existing values or constants, and drop what is dead (with ADCE, + # as the address `phi`s and `select`s of folded loads can form dead cycles that would keep + # the slots alive); nothing combines or canonicalizes instructions here. function cleanup(; simplify=false) @dispose pb=PassBuilder() begin if simplify add!(pb, FunctionPassManager()) do fpm add!(fpm, InstSimplifyPass()) + add!(fpm, ADCEPass()) end end add!(pb, GlobalDCEPass()) diff --git a/src/relocation.jl b/src/relocation.jl index 5c076ae5..821bff01 100644 --- a/src/relocation.jl +++ b/src/relocation.jl @@ -602,7 +602,8 @@ end # Fold away the references to boxed constants that are dead, e.g. in the pointer half of an # isbits union whose selector says it is unused, for back-ends that cannot refer to them but -# where `demote_boxed_constants!` does not work (SPIR-V before LLVM 17). +# where `demote_boxed_constants!` does not work (SPIR-V before LLVM 17). The boxes stay in +# the module, so with several entry points this runs again on their users for each. function fold_dead_box_references!(@nospecialize(job::CompilerJob), mod::LLVM.Module) users = Set{LLVM.Function}() for gv in boxed_constants(mod) @@ -950,10 +951,15 @@ function merged_constant_value!(builder::IRBuilder, T::LLVMType, @nospecialize(a elseif addr isa LLVM.GlobalVariable return constant_word(T, addr) elseif addr isa LLVM.SelectInst - a = merged_constant_value!(builder, T, addr.operands[2], values) - b = merged_constant_value!(builder, T, addr.operands[3], values) + # (create the select first, as cycles make it an operand of itself, with a placeholder + # that is not a constant so that the builder cannot fold it away) position!(builder, LLVM.after(addr)) - return values[addr] = select!(builder, addr.operands[1], a, b) + placeholder = LLVM.freeze!(builder, UndefValue(T)) + sel = values[addr] = select!(builder, addr.operands[1], placeholder, placeholder) + sel.operands[2] = merged_constant_value!(builder, T, addr.operands[2], values) + sel.operands[3] = merged_constant_value!(builder, T, addr.operands[3], values) + erase!(placeholder) + return sel elseif addr isa LLVM.PHIInst # (create the phi first, as loops make it an incoming value of itself) position!(builder, LLVM.before(addr)) @@ -1210,9 +1216,8 @@ end # Load the slots' values as the words the table holds. A pointer-typed load would read a # host address as a pointer into the target's default address space, which on Metal is -# thread memory, and shader validation does not preserve such a value's bits. Converting -# the word back with `inttoptr` keeps the IR valid for existing users, while comparisons -# fold to integer ones. +# thread memory, and shader validation does not preserve such a value's bits. The word is +# converted back with `inttoptr`, which keeps the IR valid for existing users. function load_relocation_words!(loads::Vector{LLVM.LoadInst}, T_word::LLVMType) @dispose builder=IRBuilder() begin for load in loads diff --git a/test/native.jl b/test/native.jl index ee4fb38e..9190b26d 100644 --- a/test/native.jl +++ b/test/native.jl @@ -2163,6 +2163,21 @@ end }""") @test changed @test !occursin("load", ir) + @test count("select i1 %c, i64", ir) == 1 # (one value per address) + + # also with a cycle of selects, which is valid IR in an unreachable block + changed, ir = fold(slots * """ + define i64 @f(i1 %c) { + entry: + ret i64 0 + dead: + %s1 = select i1 %c, ptr %s2, ptr @a + %s2 = select i1 %c, ptr %s1, ptr @b + %v = load i64, ptr %s1 + ret i64 %v + }""") + @test changed + @test !occursin("load", ir) # not when one of the addresses is something else, also when only reached through # a loop, or when a global's initializer could be overridden diff --git a/test/spirv.jl b/test/spirv.jl index f75cde55..d4fc2529 100644 --- a/test/spirv.jl +++ b/test/spirv.jl @@ -234,33 +234,88 @@ end end @testset "merged cglobal relocations" begin - mod = @eval module $(gensym()) - function kernel(out::Core.LLVMPtr{UInt,1}, cond::Bool) - Base.llvmcall((""" - @jl_float32_type = external global ptr - @jl_float64_type = external global ptr - - define void @entry(ptr addrspace(1) %out, i8 %c) { - %cond = trunc i8 %c to i1 - %addr = select i1 %cond, ptr @jl_float32_type, ptr @jl_float64_type - %value = load ptr, ptr %addr - %word = ptrtoint ptr %value to i64 - store i64 %word, ptr addrspace(1) %out - ret void - } - """, "entry"), Nothing, Tuple{Core.LLVMPtr{UInt,1},Bool}, out, cond) - return - end - end + globals = """ + @jl_float32_type = external global ptr + @jl_float64_type = external global ptr + """ + # (the instruction that selects the loaded value, and the code that loads it) + entries = [ + # a select of two slots + "OpSelect" => """ + define void @entry(ptr addrspace(1) %out, i8 %c) { + %cond = trunc i8 %c to i1 + %addr = select i1 %cond, ptr @jl_float32_type, ptr @jl_float64_type + %value = load ptr, ptr %addr + %word = ptrtoint ptr %value to i64 + store i64 %word, ptr addrspace(1) %out + ret void + } + """, + # a phi of two slots + "OpPhi" => """ + define void @entry(ptr addrspace(1) %out, i8 %c) { + top: + %cond = trunc i8 %c to i1 + br i1 %cond, label %l, label %r + l: + store i64 1, ptr addrspace(1) %out + br label %m + r: + store i64 2, ptr addrspace(1) %out + br label %m + m: + %addr = phi ptr [ @jl_float32_type, %l ], [ @jl_float64_type, %r ] + %value = load ptr, ptr %addr + %word = ptrtoint ptr %value to i64 + store i64 %word, ptr addrspace(1) %out + ret void + } + """, + # a loop-carried phi and select, which stay behind as a dead cycle once folded + "OpSelect" => """ + define void @entry(ptr addrspace(1) %out, i8 %c) { + top: + %cond = trunc i8 %c to i1 + br label %loop + loop: + %i = phi i64 [ 0, %top ], [ %n, %loop ] + %p = phi ptr [ @jl_float32_type, %top ], [ %s, %loop ] + %s = select i1 %cond, ptr %p, ptr @jl_float64_type + %n = add i64 %i, 1 + store i64 %n, ptr addrspace(1) %out + %done = icmp eq i64 %n, 10 + br i1 %done, label %exit, label %loop + exit: + %value = load ptr, ptr %s + %word = ptrtoint ptr %value to i64 + store i64 %word, ptr addrspace(1) %out + ret void + } + """] # baking the slots of a merged load leaves them as private globals in a SPIR-V address - # space they cannot be in, so the load needs to be folded before translation + # space they cannot be in, so the load needs to be folded, and the slots dropped, + # before translation if VERSION >= v"1.12.0-DEV.225" # (opaque pointers in `llvmcall`) - @test @filecheck begin - @check "OpSelect" - @check_not "OpVariable %_ptr_Function" - SPIRV.code_native(mod.kernel, Tuple{Core.LLVMPtr{UInt,1},Bool}; backend, - kernel=true, optimize=false, validate=false, dump_module=true) + for (op, entry) in entries + ir = globals * entry + mod = @eval module $(gensym()) + function kernel(out::Core.LLVMPtr{UInt,1}, cond::Bool) + Base.llvmcall(($ir, "entry"), Nothing, Tuple{Core.LLVMPtr{UInt,1},Bool}, + out, cond) + return + end + end + # (the LLVM back-end emits a leftover slot as a variable of the function, ahead of + # the instructions) + @test @filecheck begin + @check_not "OpVariable %_ptr_Function" + @check "$op" + @check_not "OpVariable %_ptr_Function" + SPIRV.code_native(mod.kernel, Tuple{Core.LLVMPtr{UInt,1},Bool}; backend, + kernel=true, optimize=false, validate=false, + dump_module=true) + end end end end