diff --git a/src/mcgen.jl b/src/mcgen.jl index d63165f1..657ccac9 100644 --- a/src/mcgen.jl +++ b/src/mcgen.jl @@ -3,23 +3,27 @@ # 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. 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 fold_instructions + if simplify add!(pb, FunctionPassManager()) do fpm - add!(fpm, instcombine_pass(job)) + add!(fpm, InstSimplifyPass()) + add!(fpm, ADCEPass()) 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 +47,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..821bff01 100644 --- a/src/relocation.jl +++ b/src/relocation.jl @@ -585,13 +585,45 @@ 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). 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) + 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 +883,95 @@ 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 + # (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)) + 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)) + 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) @@ -1095,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/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..9190b26d 100644 --- a/test/native.jl +++ b/test/native.jl @@ -2134,6 +2134,85 @@ 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) + @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 + 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..d4fc2529 100644 --- a/test/spirv.jl +++ b/test/spirv.jl @@ -233,6 +233,93 @@ end end end +@testset "merged cglobal relocations" begin + 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, and the slots dropped, + # before translation + if VERSION >= v"1.12.0-DEV.225" # (opaque pointers in `llvmcall`) + 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 + @testset "boxed union constants" begin mod = @eval module $(gensym()) @noinline produce(cond::Bool, a::Int32) = cond ? a : Int64(7) @@ -415,7 +502,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 +985,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 +1001,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