diff --git a/src/debug.jl b/src/debug.jl index 3150f174..5f47bd6f 100644 --- a/src/debug.jl +++ b/src/debug.jl @@ -4,8 +4,15 @@ # # this works by looking up the debug information of the instruction, and inspecting the call # sites of the containing function. if there's only one, repeat the process from that call. -# finally, the debug information is converted to a Julia stack trace. +# if there are several, the backtrace ends with a "multiple call sites" frame (`caller_chains` +# lists those calls). finally, the debug information is converted to a Julia stack trace. function backtrace(inst::LLVM.Instruction, bt = StackTraces.StackFrame[]) + trace!(bt, inst) + return bt +end + +# the walk of `backtrace`, returning the function with several call sites it ended at, if any +function trace!(bt, inst::LLVM.Instruction) done = Set{LLVM.Instruction}() while true if in(inst, done) @@ -14,21 +21,7 @@ function backtrace(inst::LLVM.Instruction, bt = StackTraces.StackFrame[]) push!(done, inst) # look up the debug information from the current instruction - loc = inst.debug_location - while loc !== nothing - scope = loc.scope - if scope !== nothing - name = replace(something(scope.name, ""), r";$"=>"") - isempty(name) && (name = "unknown") - file = scope.file - path = file === nothing ? "unknown" : - joinpath(file.directory::Union{Nothing,String}, - file.filename::Union{Nothing,String}) - line = loc.line - push!(bt, StackTraces.StackFrame(name, path, line)) - end - loc = loc.inlined_at - end + push_frames!(bt, inst.debug_location) # move up the call chain f = inst.parent.parent @@ -48,6 +41,7 @@ function backtrace(inst::LLVM.Instruction, bt = StackTraces.StackFrame[]) if length(call_sites) > 1 frame = StackTraces.StackFrame("multiple call sites", "unknown", 0) push!(bt, frame) + return f elseif length(call_sites) == 1 inst = first(call_sites).user::LLVM.CallInst continue @@ -56,5 +50,82 @@ function backtrace(inst::LLVM.Instruction, bt = StackTraces.StackFrame[]) break end + return nothing +end + +# the frames of a debug location, innermost (inlined) first +function push_frames!(bt, loc) + while loc !== nothing + scope = loc.scope + if scope !== nothing + name = replace(something(scope.name, ""), r";$"=>"") + isempty(name) && (name = "unknown") + file = scope.file + path = file === nothing ? "unknown" : + joinpath(file.directory::Union{Nothing,String}, + file.filename::Union{Nothing,String}) + line = loc.line + push!(bt, StackTraces.StackFrame(name, path, line)) + end + loc = loc.inlined_at + end return bt end + +# The paths of direct calls into `f`: for each, the frames of the call, followed by those of a +# call into the function containing it, and so on, innermost first. A path ends at a function +# without calls that have debug information. Calls back into a function already on the path +# are left out, so recursion is not followed. Paths that show the same frames are listed once, +# and at most `limit` of them, in source order. +function caller_chains(f::LLVM.Function, limit::Int) + # the paths into a function are the same however it was reached, unless a call into + # another function on the path was left out: those are not reused. that makes walking + # mutually recursive functions exponential, but they are rare in device code. + memo = Dict{LLVM.Function,Tuple{Vector{StackTraces.StackTrace},Bool}}() + active = Set{LLVM.Function}() + # returns the paths, whether a recursive call was left out, and whether `f` is called at all + function chains(f) + if haskey(memo, f) + result, called = memo[f] + return result, false, called + end + push!(active, f) + result = StackTraces.StackTrace[] + cut = called = false + for use in f.uses + call = use.user + call isa LLVM.CallInst && call.called_operand == f || continue + loc = call.debug_location + loc === nothing && continue + called = true + caller = call.parent.parent + if caller in active + # (a function calling itself is left out wherever it is reached from) + cut |= caller != f + continue + end + frames = push_frames!(StackTraces.StackFrame[], loc) + outer, outer_cut, outer_called = chains(caller) + cut |= outer_cut + if !outer_called + push!(result, frames) + else + # (nothing when every path into the caller is recursive) + append!(result, vcat(frames, chain) for chain in outer) + end + end + delete!(active, f) + normalize_chains!(result, limit) + cut || (memo[f] = (result, called)) + return result, cut, called + end + return first(chains(f)) +end + +function normalize_chains!(chains::Vector{StackTraces.StackTrace}, limit::Int) + key(chain) = [(String(frame.file), frame.line, String(frame.func)) for frame in chain] + unique!(key, chains) + sort!(chains; by=key) + length(chains) > limit && resize!(chains, limit) + return chains +end diff --git a/src/gcn.jl b/src/gcn.jl index 0ce8c34e..edafeec4 100644 --- a/src/gcn.jl +++ b/src/gcn.jl @@ -319,7 +319,8 @@ end # atomics, which only fail when loading the code object, some atomics abort instruction # selection, and the errors it does report don't point at the Julia code. # Validation runs after `lower_syncscopes!`, so the scopes are the ones AMDGPU knows. -function validate_ir(job::CompilerJob{GCNCompilerTarget}, mod::LLVM.Module) +function validate_ir(job::CompilerJob{GCNCompilerTarget}, mod::LLVM.Module, + callers=IRCallers()) errors = IRError[] dl = mod.datalayout for f in mod.functions, bb in f.blocks, inst in bb.instructions @@ -330,7 +331,9 @@ function validate_ir(job::CompilerJob{GCNCompilerTarget}, mod::LLVM.Module) else nothing end - reason === nothing || push!(errors, (reason, backtrace(inst), string(inst))) + reason === nothing && continue + push!(errors, (reason, backtrace(inst), string(inst))) + record_callers!(callers, errors[end], inst) end return errors end diff --git a/src/interface.jl b/src/interface.jl index ac764f5d..91f400e2 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -802,5 +802,7 @@ finish_runtime_intrinsics!(@nospecialize(job::CompilerJob), mod::LLVM.Module) = finish_ir!(@nospecialize(job::CompilerJob), mod::LLVM.Module, entry::LLVM.Function) = entry -# whether an LLVM function is valid for this back-end +# the errors that make a module invalid for this back-end. back-ends can also implement the +# three-argument form, to record the calls that reach an error (see `record_callers!`) validate_ir(@nospecialize(job::CompilerJob), mod::LLVM.Module) = IRError[] +validate_ir(@nospecialize(job::CompilerJob), mod::LLVM.Module, callers) = validate_ir(job, mod) diff --git a/src/metal.jl b/src/metal.jl index 2363f986..fbafec56 100644 --- a/src/metal.jl +++ b/src/metal.jl @@ -389,7 +389,8 @@ function optimize_module!(@nospecialize(job::CompilerJob{MetalCompilerTarget}), return end -function validate_ir(job::CompilerJob{MetalCompilerTarget}, mod::LLVM.Module) +function validate_ir(job::CompilerJob{MetalCompilerTarget}, mod::LLVM.Module, + callers=IRCallers()) errors = IRError[] # Metal does not support double precision, except for logging @@ -414,10 +415,11 @@ function validate_ir(job::CompilerJob{MetalCompilerTarget}, mod::LLVM.Module) return true end - append!(errors, check_ir_values(mod, is_illegal_double, "use of double value")) + append!(errors, + check_ir_values(mod, is_illegal_double, "use of double value"; callers)) # Metal never supports 128-bit integers - append!(errors, check_ir_values(mod, LLVM.IntType(128))) + append!(errors, check_ir_values(mod, LLVM.IntType(128); callers)) # atomics that `lower_atomics!` cannot lower for f in mod.functions, bb in f.blocks, inst in bb.instructions @@ -433,7 +435,9 @@ function validate_ir(job::CompilerJob{MetalCompilerTarget}, mod::LLVM.Module) else nothing end - reason === nothing || push!(errors, (reason, backtrace(inst), string(inst))) + reason === nothing && continue + push!(errors, (reason, backtrace(inst), string(inst))) + record_callers!(callers, errors[end], inst) end errors diff --git a/src/ptx.jl b/src/ptx.jl index f13350db..1f40bd16 100644 --- a/src/ptx.jl +++ b/src/ptx.jl @@ -556,7 +556,8 @@ end # target cannot run: it silently drops a system scope before sm_60, emits PTX that `ptxas` # or the driver reject, or aborts the process. Validation runs after `lower_syncscopes!`, so # the scopes are the ones NVPTX knows. -function validate_ir(job::CompilerJob{PTXCompilerTarget}, mod::LLVM.Module) +function validate_ir(job::CompilerJob{PTXCompilerTarget}, mod::LLVM.Module, + callers=IRCallers()) errors = IRError[] dl = mod.datalayout for f in mod.functions, bb in f.blocks, inst in bb.instructions @@ -567,7 +568,9 @@ function validate_ir(job::CompilerJob{PTXCompilerTarget}, mod::LLVM.Module) else nothing end - reason === nothing || push!(errors, (reason, backtrace(inst), string(inst))) + reason === nothing && continue + push!(errors, (reason, backtrace(inst), string(inst))) + record_callers!(callers, errors[end], inst) end return errors end diff --git a/src/spirv.jl b/src/spirv.jl index 8c5b591c..fc2a6644 100644 --- a/src/spirv.jl +++ b/src/spirv.jl @@ -182,19 +182,20 @@ function finish_module!(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module, return entry end -function validate_ir(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module) +function validate_ir(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module, + callers=IRCallers()) errors = IRError[] # support for half and double depends on the target if !job.config.target.supports_fp16 - append!(errors, check_ir_values(mod, LLVM.HalfType())) + append!(errors, check_ir_values(mod, LLVM.HalfType(); callers)) end if !job.config.target.supports_fp64 - append!(errors, check_ir_values(mod, LLVM.DoubleType())) + append!(errors, check_ir_values(mod, LLVM.DoubleType(); callers)) end bfloat16 = job.config.target.supports_bfloat16 if !bfloat16 - append!(errors, check_ir_values(mod, LLVM.BFloatType())) + append!(errors, check_ir_values(mod, LLVM.BFloatType(); callers)) end # atomics that `lower_atomics!` cannot lower, and `bfloat` operations that @@ -211,7 +212,9 @@ function validate_ir(job::CompilerJob{SPIRVCompilerTarget}, mod::LLVM.Module) else nothing end - reason === nothing || push!(errors, (reason, backtrace(inst), string(inst))) + reason === nothing && continue + push!(errors, (reason, backtrace(inst), string(inst))) + record_callers!(callers, errors[end], inst) end return errors diff --git a/src/validation.jl b/src/validation.jl index d9f5326e..7aa9d131 100644 --- a/src/validation.jl +++ b/src/validation.jl @@ -129,14 +129,40 @@ end const IRError = Tuple{String, StackTraces.StackTrace, Any} # kind, bt, meta +# for errors whose backtrace ends at a function with several call sites, the paths of calls +# into that function (see `record_callers!`) +const IRCallers = Dict{IRError,Vector{StackTraces.StackTrace}} + struct InvalidIRError <: Exception job::CompilerJob errors::Vector{IRError} # the Julia code that errors were traced back to (see `explain_error`) explanations::Dict{IRError,Any} + callers::IRCallers end InvalidIRError(job::CompilerJob, errors::Vector{IRError}) = InvalidIRError(job, errors, Dict{IRError,Any}()) +InvalidIRError(job::CompilerJob, errors, explanations) = + InvalidIRError(job, errors, explanations, IRCallers()) + +# how many paths into a function with several call sites to show +const MAX_CALLERS = 4 + +# Record the calls through which `error`, raised for `inst`, can be reached, if its backtrace +# ends at a function with several call sites. Only possible while the module is alive. +function record_callers!(callers::IRCallers, error::IRError, inst::LLVM.Instruction) + f = trace!(StackTraces.StackFrame[], inst) + f === nothing && return callers + # one more than is shown, to tell whether there are more + chains = caller_chains(f, MAX_CALLERS + 1) + isempty(chains) && return callers + # identical errors raised for different instructions are reported once + if haskey(callers, error) + chains = normalize_chains!(vcat(callers[error], chains), MAX_CALLERS + 1) + end + callers[error] = chains + return callers +end const RUNTIME_FUNCTION = "call to the Julia runtime" const UNKNOWN_FUNCTION = "call to an unknown function" @@ -182,7 +208,24 @@ function show_reason(io::IO, err::InvalidIRError, error::IRError) print(io, "\nJulia code (one of): ", join(code, "; ")) end end - Base.show_backtrace(io, bt) + chains = get(err.callers, error, nothing) + if chains === nothing + Base.show_backtrace(io, bt) + else + marker = Symbol("multiple call sites") + Base.show_backtrace(io, filter(frame -> frame.func !== marker, bt)) + # each path continues the backtrace above (unnumbered, as Base's numbering of + # repeated frames differs between Julia versions) + print(io, length(chains) == 1 ? "\nCalled from:" : "\nCalled from several places:") + for (i, chain) in enumerate(chains[1:min(end, MAX_CALLERS)]) + i > 1 && print(io, "\nor") + for frame in chain + print(io, "\n ", frame.func, "\n @ ", + Base.contractuser(String(frame.file)), ":", frame.line) + end + end + length(chains) > MAX_CALLERS && print(io, "\nor elsewhere") + end end # Calls that codegen emits into Julia's runtime support on its own, e.g., for exception @@ -285,30 +328,31 @@ function check_ir(job, mod::LLVM.Module, relocs::Relocations=Relocations(); comp explanation === nothing || (explanations[error] = explanation) end end - errors = check_ir!(job, IRError[], mod, relocs, explain) + callers = IRCallers() + errors = check_ir!(job, IRError[], mod, relocs, explain, callers) unique!(errors) if !isempty(errors) - throw(InvalidIRError(job, errors, explanations)) + throw(InvalidIRError(job, errors, explanations, callers)) end return end function check_ir!(job, errors::Vector{IRError}, mod::LLVM.Module, relocs::Relocations, - explain=nothing) + explain=nothing, callers::IRCallers=IRCallers()) for f in mod.functions - check_ir!(job, errors, f, relocs, explain) + check_ir!(job, errors, f, relocs, explain, callers) end - check_constants!(job, errors, mod, relocs) + check_constants!(job, errors, mod, relocs, callers) # custom validation - append!(errors, validate_ir(job, mod)) + append!(errors, validate_ir(job, mod, callers)) return errors end function check_ir!(job, errors::Vector{IRError}, f::LLVM.Function, relocs::Relocations, - explain=nothing) + explain=nothing, callers::IRCallers=IRCallers()) dl = f.parent.datalayout for bb in f.blocks, inst in bb.instructions nerrors = length(errors) @@ -327,10 +371,9 @@ function check_ir!(job, errors::Vector{IRError}, f::LLVM.Function, relocs::Reloc push!(errors, (global_access_error(job, gr), backtrace(inst), gr)) end end - if explain !== nothing - for i in nerrors+1:length(errors) - explain(inst, errors[i]) - end + for i in nerrors+1:length(errors) + record_callers!(callers, errors[i], inst) + explain === nothing || explain(inst, errors[i]) end end @@ -346,7 +389,8 @@ end is_device_constant(@nospecialize(value)) = isbits(value) || value isa Symbol || value isa Type function check_constants!(@nospecialize(job::CompilerJob), errors::Vector{IRError}, - mod::LLVM.Module, relocs::Relocations) + mod::LLVM.Module, relocs::Relocations, + callers::IRCallers=IRCallers()) uses_julia_runtime(job) && return errors for rec in relocs.records rec.kind === SlotSite && rec.target isa JuliaValueRef || continue @@ -358,7 +402,9 @@ function check_constants!(@nospecialize(job::CompilerJob), errors::Vector{IRErro gv === nothing && continue inst = constant_use(job, gv) inst === nothing && continue - push!(errors, (UNSUPPORTED_CONSTANT, backtrace(inst), typeof(value))) + error = (UNSUPPORTED_CONSTANT, backtrace(inst), typeof(value)) + push!(errors, error) + record_callers!(callers, error, inst) end return errors end @@ -849,7 +895,8 @@ function describe_call(src::CodeInfo, mi::MethodInstance, pc::Int, @nospecialize end # helper function to check for illegal values in an LLVM module -function check_ir_values(mod::LLVM.Module, predicate, msg="value") +function check_ir_values(mod::LLVM.Module, predicate, msg="value"; + callers::IRCallers=IRCallers()) errors = IRError[] for fun in mod.functions, bb in fun.blocks, inst in bb.instructions if predicate(inst) || any(predicate, inst.operands) @@ -857,11 +904,13 @@ function check_ir_values(mod::LLVM.Module, predicate, msg="value") # snapshot to a string: the error may outlive the module, and showing a # disposed LLVM value segfaults push!(errors, (msg, bt, string(inst))) + record_callers!(callers, errors[end], inst) end end return errors end ## shorthand to check for illegal value types -function check_ir_values(mod::LLVM.Module, T_bad::LLVMType) - check_ir_values(mod, val -> val.value_type == T_bad, "use of $(string(T_bad)) value") +function check_ir_values(mod::LLVM.Module, T_bad::LLVMType; callers::IRCallers=IRCallers()) + check_ir_values(mod, val -> val.value_type == T_bad, "use of $(string(T_bad)) value"; + callers) end diff --git a/test/native.jl b/test/native.jl index 380c96aa..68226ffd 100644 --- a/test/native.jl +++ b/test/native.jl @@ -3072,6 +3072,101 @@ end @test any(GPUCompiler.is_runtime_call, err.errors) end +@testset "errors in functions with several callers" begin + function dynamic_call_error(kernel) + err = try + Native.code_execution(kernel, Tuple{Ptr{Float64},Float64}) + nothing + catch err + err + end + @test err isa InvalidIRError + error = only(filter(error -> error[1] == GPUCompiler.DYNAMIC_CALL, err.errors)) + return err, error + end + paths(err, error) = [[(frame.func, frame.line) for frame in chain] + for chain in err.callers[error]] + + # each path is followed to the kernel, also when they share the call in `mid` + mod = @eval module $(gensym()) + @noinline helper(x) = Base.inferencebarrier(sin)(x)::Float64 + @noinline function mid(p, x) + unsafe_store!(p, helper(x)) + return + end + function kernel(p, x) + unsafe_store!(p, helper(x)) + unsafe_store!(p, helper(x + 1)) + mid(p, x) + mid(p, x + 1) + return + end + end + mid = first(methods(mod.mid)).line + kernel = first(methods(mod.kernel)).line + err, error = dynamic_call_error(mod.kernel) + @test paths(err, error) == [[(:mid, mid + 1), (:kernel, kernel + 3)], + [(:mid, mid + 1), (:kernel, kernel + 4)], + [(:kernel, kernel + 1)], + [(:kernel, kernel + 2)]] + msg = sprint(showerror, err) + @test count("Reason: unsupported $(GPUCompiler.DYNAMIC_CALL)", msg) == 1 + @test occursin("Called from several places:", msg) + @test count(r"\nor\n", msg) == 3 + @test !occursin("multiple call sites", msg) + @test !occursin("or elsewhere", msg) + + # recursive calls are left out + mod = @eval module $(gensym()) + @noinline helper(x, n) = + n <= 0 ? Base.inferencebarrier(sin)(x)::Float64 : helper(x, n - 1) + 1 + function kernel(p, x) + unsafe_store!(p, helper(x, 1)) + unsafe_store!(p, helper(x, 2)) + return + end + end + kernel = first(methods(mod.kernel)).line + err, error = dynamic_call_error(mod.kernel) + @test paths(err, error) == [[(:kernel, kernel + 1)], [(:kernel, kernel + 2)]] + + # paths through mutually recursive functions do not depend on the order they are found + mod = @eval module $(gensym()) + @noinline f(x) = Base.inferencebarrier(sin)(x)::Float64 + @noinline a(x, n) = f(x) + (n > 0 ? c(x, n - 1) : 0.0) + @noinline b(x, n) = 2 * f(x) + @noinline c(x, n) = a(x, n) + b(x, n) + function kernel(p, x) + unsafe_store!(p, a(x, 2)) + return + end + end + line(f) = first(methods(f)).line + err, error = dynamic_call_error(mod.kernel) + @test paths(err, error) == [[(:a, line(mod.a)), (:kernel, line(mod.kernel) + 1)], + [(:b, line(mod.b)), (:c, line(mod.c)), (:a, line(mod.a)), + (:kernel, line(mod.kernel) + 1)]] + + # only a few paths are kept, and fewer are shown + mod = @eval module $(gensym()) + @noinline helper(x) = Base.inferencebarrier(sin)(x)::Float64 + function kernel(p, x) + unsafe_store!(p, helper(x)) + unsafe_store!(p, helper(x + 1)) + unsafe_store!(p, helper(x + 2)) + unsafe_store!(p, helper(x + 3)) + unsafe_store!(p, helper(x + 4)) + unsafe_store!(p, helper(x + 5)) + return + end + end + err, error = dynamic_call_error(mod.kernel) + @test length(err.callers[error]) == 5 + msg = sprint(showerror, err) + @test count(r"\nor\n", msg) == 3 + @test occursin("or elsewhere", msg) +end + @testset "explanations in Julia code" begin mod = @eval module $(gensym()) f(x) = x + 1 diff --git a/test/ptx.jl b/test/ptx.jl index e7cf84c2..ae1af4fd 100644 --- a/test/ptx.jl +++ b/test/ptx.jl @@ -1107,6 +1107,29 @@ end system_atomics=false)) do msg occursin("Reason: unsupported system-scope atomic operation (not supported on this platform", msg) end + + # in a function with several callers, they are listed too + shared = @eval module $(gensym()) + @noinline function add(p::Ptr{Int}) + Base.llvmcall("""%ptr = inttoptr i64 %0 to i64* + %old = atomicrmw add i64* %ptr, i64 1 monotonic, align 8 + ret void""", Cvoid, Tuple{Ptr{Int}}, p) + return + end + function kernel(p::Ptr{Int}) + add(p) + add(p + 8) + return + end + end + @test_throws_message(InvalidIRError, + PTX.code_execution(shared.kernel, Tuple{Ptr{Int}}; + backend, cap=v"5.2")) do msg + occursin("Reason: unsupported system-scope atomic operation", msg) && + occursin("Called from several places:", msg) && + count("\n kernel\n", msg) == 2 + end + # (libNVVM doesn't support sm_61) if backend === :nvptx asm, _ = PTX.code_execution(mod.kernel, Tuple{Ptr{Int}}; backend, cap=v"6.1")