diff --git a/Project.toml b/Project.toml index 8d2cd51c..5641e891 100644 --- a/Project.toml +++ b/Project.toml @@ -41,7 +41,7 @@ Adapt = "4" CEnum = "0.5, 1" Crayons = "4" GPUArrays = "12.1" -GPUCompiler = "2.18" +GPUCompiler = "2.23" GPUToolbox = "3.5" IntelITT = "0.2" KernelAbstractions = "0.10" diff --git a/docs/src/api/kernels.md b/docs/src/api/kernels.md index 2c3d6478..3adbbc1c 100644 --- a/docs/src/api/kernels.md +++ b/docs/src/api/kernels.md @@ -34,8 +34,8 @@ launches the kernel on the GPU. ### `KernelException` Thrown when synchronizing a stream on which a kernel threw an exception. It carries the -exception's `name` and `reason` (from debug level 1), and the `work_item` and `work_group` -that threw it along with a `backtrace` (from debug level 2). +`work_item` and `work_group` that threw it, the exception's `name` and `reason` (from debug +level 1), and a `backtrace` (from debug level 2). ### `zefunction(f, tt; kwargs...)` diff --git a/docs/src/kernels.md b/docs/src/kernels.md index 7c187f53..9599b0ce 100644 --- a/docs/src/kernels.md +++ b/docs/src/kernels.md @@ -102,14 +102,14 @@ julia> a = oneArray{Int}(undef, 1); julia> @oneapi kernel(a) julia> synchronize() -ERROR: KernelException: A BoundsError was thrown on Intel(R) Arc(TM) A770 Graphics: Out-of-bounds array access +ERROR: KernelException: A BoundsError was thrown by work-item 1×1×1 in work-group 1×1×1 on Intel(R) Arc(TM) A770 Graphics: Out-of-bounds array access For more details, run Julia with `-g2`, or launch the kernel with `@oneapi debug_level=2`. ``` The amount of detail depends on the debug level the kernel is compiled with, which defaults -to Julia's `-g` level. At level 0 only the fact that an exception was thrown is reported; at -level 1 (the default) also its type and reason; at level 2 also the work-item that threw it -and a backtrace. Only one exception is reported per synchronization. If the task that +to Julia's `-g` level. At level 0 only the fact that an exception was thrown, and by which +work-item, is reported; at level 1 (the default) also its type and reason; at level 2 also a +backtrace. Only one exception is reported per synchronization. If the task that launched the kernel finishes without synchronizing, the exception is reported by the next `synchronize()` of another task, unless something waited for the kernel's results first. Exceptions in kernels launched on an explicitly created `ZeCommandQueue` are not reported. diff --git a/lib/level-zero/module.jl b/lib/level-zero/module.jl index d75831ff..e8d958c2 100644 --- a/lib/level-zero/module.jl +++ b/lib/level-zero/module.jl @@ -91,13 +91,16 @@ mutable struct ZeKernel # MAX_GROUP_SIZE extension. Read on every KernelInterface launch. max_group_size::Int + # the throw sites of the kernel's code, which the exceptions it reports refer to + exception_sites::Vector{ExceptionSite} + function ZeKernel(mod, name) GC.@preserve name begin desc_ref = Ref(ze_kernel_desc_t(; pKernelName=pointer(name))) handle_ref = Ref{ze_kernel_handle_t}() zeKernelCreate(mod, desc_ref, handle_ref) end - obj = new(mod, handle_ref[], ReentrantLock(), -1, -1) + obj = new(mod, handle_ref[], ReentrantLock(), -1, -1, ExceptionSite[]) finalizer(obj) do obj zeKernelDestroy(obj) diff --git a/lib/level-zero/oneL0.jl b/lib/level-zero/oneL0.jl index d654abd7..02849f09 100644 --- a/lib/level-zero/oneL0.jl +++ b/lib/level-zero/oneL0.jl @@ -8,6 +8,8 @@ using Printf using Libdl +using GPUCompiler: ExceptionSite + if Sys.iswindows() const libze_loader = "ze_loader" else diff --git a/src/compiler/compilation.jl b/src/compiler/compilation.jl index ef456c87..49d48bde 100644 --- a/src/compiler/compilation.jl +++ b/src/compiler/compilation.jl @@ -12,9 +12,10 @@ const oneAPICompilerJob = CompilerJob{SPIRVCompilerTarget,oneAPICompilerParams} Cached compilation results for a oneAPI kernel job, managed by `GPUCompiler.cached_results`. Fields are populated through the compile pipeline: -`image` (SPIR-V bytes) + `entry` after codegen, and `kernels` after the session-local -link onto a Level Zero module. The first two are session-portable (cached through -precompilation); `kernels` is session-local and never populated during precompilation. +`image` (SPIR-V bytes), `entry` and `exception_sites` after codegen, and `kernels` after the +session-local link onto a Level Zero module. The first three are session-portable (cached +through precompilation); `kernels` is session-local and never populated during +precompilation. `image === nothing` identifies a job that has not been compiled yet. `kernels` is a small linear cache of `(ZeContext, ZeDevice, ZeKernel)` tuples. The cache @@ -27,11 +28,14 @@ workload that bounces between a handful of contexts or devices. mutable struct oneAPIResults image::Union{Nothing, Vector{UInt8}} # SPIR-V binary entry::Union{Nothing, String} + exception_sites::Vector{GPUCompiler.ExceptionSite} kernels::Vector{Tuple{ZeContext, ZeDevice, ZeKernel}} # session-local; linear-scanned - oneAPIResults() = new(nothing, nothing, Tuple{ZeContext, ZeDevice, ZeKernel}[]) + oneAPIResults() = new(nothing, nothing, GPUCompiler.ExceptionSite[], + Tuple{ZeContext, ZeDevice, ZeKernel}[]) end GPUCompiler.runtime_module(::oneAPICompilerJob) = oneAPI +GPUCompiler.uses_exception_sites(::oneAPICompilerJob) = true GPUCompiler.kernel_state_type(::oneAPICompilerJob) = KernelState @@ -249,23 +253,26 @@ end CompilerConfig(target, params; kernel, name, always_inline, debug_level) end -# run inference + LLVM codegen + SPIR-V emission. returns `(image, entry)`, both -# session-portable so they survive precompilation when stored on a cached `CodeInstance`. +# run inference + LLVM codegen + SPIR-V emission. returns `(image, entry, exception_sites)`, +# all session-portable so they survive precompilation when stored on a cached `CodeInstance`. function compile_to_obj(@nospecialize(job::CompilerJob)) # TODO: on 1.9, this actually creates a context. cache those. return JuliaContext() do ctx asm, meta = GPUCompiler.compile(:obj, job) # the IR belongs to us: dispose of it, or it leaks along with the context @dispose ir = meta.ir begin - (image = asm, entry = meta.entry.name) + (image = asm, entry = meta.entry.name, meta.exception_sites) end end end # link the SPIR-V bytes into a session-local `ZeKernel` on the given context and device. -function link_kernel(image::Vector{UInt8}, entry::String, ctx::ZeContext, dev::ZeDevice) +function link_kernel(image::Vector{UInt8}, entry::String, + exception_sites::Vector{GPUCompiler.ExceptionSite}, + ctx::ZeContext, dev::ZeDevice) mod = ZeModule(ctx, dev, image) kernel = kernels(mod)[entry] + kernel.exception_sites = exception_sites # Kernels receive their arrays as `oneDeviceArray` structs, so to Level Zero every USM # pointer they dereference is an indirect access. Without declaring that, the driver diff --git a/src/compiler/exceptions.jl b/src/compiler/exceptions.jl index a6f0f012..67f97f87 100644 --- a/src/compiler/exceptions.jl +++ b/src/compiler/exceptions.jl @@ -8,15 +8,14 @@ export KernelException An exception thrown by a kernel on device `dev`, reported when synchronizing the stream it was launched on (e.g. by `synchronize()`, or a copy to the host such as `Array(x)`). -What is known about the exception depends on the debug level the kernel was compiled with -(Julia's `-g` level, or `@oneapi debug_level=...`): +The position of the work-item that threw is always known (`work_item` is its local id, +`work_group` the id of its work-group). What else is known depends on the debug level the +kernel was compiled with (Julia's `-g` level, or `@oneapi debug_level=...`): - `0`: only that an exception was thrown; - `1`: also the `name` of its type and the `reason`, for exceptions thrown by Julia's runtime (e.g. bounds errors, or domain errors in math functions); -- `2`: also the position of the work-item that threw (`work_item` is its local id, - `work_group` the id of its work-group), and its `backtrace` as `(function, file, line)` - tuples. +- `2`: also the `backtrace` of the throw, as `(function, file, line)` tuples. Fields that were not recorded are empty, or zero. Only one exception is reported per synchronization, and the other work-items of the kernel keep running. @@ -41,7 +40,7 @@ function Base.showerror(io::IO, err::KernelException) end print(io, " on ", oneL0.properties(err.dev).name) isempty(err.reason) || print(io, ": ", err.reason) - if err.work_item == (0, 0, 0) + if isempty(err.backtrace) print(io, "\nFor more details, run Julia with `-g2`, or launch the kernel with `@oneapi debug_level=2`.") else print(io, "\nStacktrace:") @@ -52,55 +51,6 @@ function Base.showerror(io::IO, err::KernelException) end end -const EXCEPTION_STRING_MAX = 4096 - -# buffers that copies may still be writing to, as their list could not be synchronized -const unsynchronized_string_buffers = Any[] -const unsynchronized_string_buffers_lock = ReentrantLock() - -# Read the strings at `addresses`, as reported by a kernel, returning a dictionary that maps -# the addresses that could be read to their contents. The addresses come from memory the -# kernel could have corrupted, so they are only read if they fall within an allocation, -# such as a module's constants, and only up to the end of it. Freed modules are not read. -function read_device_strings(list, ctx::ZeContext, addresses) - buffers = Dict{UInt64, Vector{UInt8}}() - for address in addresses - (address == 0 || haskey(buffers, address)) && continue - base = Ref{Ptr{Cvoid}}() - size = Ref{Csize_t}() - res = oneL0.unchecked_zeMemGetAddressRange(ctx, Ptr{Cvoid}(address), base, size) - res == oneL0.RESULT_SUCCESS || continue - available = UInt64(UInt(base[]) + size[]) - address - available > 0 || continue - buffers[address] = Vector{UInt8}(undef, min(available, EXCEPTION_STRING_MAX)) - end - isempty(buffers) && return Dict{UInt64, String}() - copied = false - GC.@preserve buffers try - for (address, buffer) in buffers - append_copy!(list, pointer(buffer), ZePtr{UInt8}(address), length(buffer)) - end - copied = true - catch err - bt = catch_backtrace() - @error "Failed to read the strings of a kernel exception" exception=(err, bt) - finally - # copies appended before a failure still write to the buffers - if oneL0.unchecked_zeCommandListHostSynchronize(list, typemax(UInt64)) != - oneL0.RESULT_SUCCESS - @lock unsynchronized_string_buffers_lock begin - push!(unsynchronized_string_buffers, buffers) - end - copied = false - end - end - copied || return Dict{UInt64, String}() - return Dict(address => String(buffer[1:something(findfirst(iszero, buffer), - length(buffer) + 1) - 1]) - for (address, buffer) in buffers) -end - - ## per-stream report # Reports are carved out of slabs shared by a device's streams, as kernels access memory @@ -109,10 +59,24 @@ const REPORTS_PER_SLAB = 64 const free_report_slots = Dict{Tuple{ZeContext, ZeDevice}, Vector{ReportSlot}}() -KernelState(s::oneStream) = KernelState(UInt(s.exceptions.report) % UInt64, - UInt(s.exceptions.claim) % UInt64) +KernelState(s::oneStream, kernel::ZeKernel) = + KernelState(UInt(s.exceptions.report) % UInt64, UInt(s.exceptions.claim) % UInt64, + kernel_id(kernel)) # explicitly created queues have no report -KernelState(::ZeCommandQueue) = KernelState() +KernelState(::ZeCommandQueue, ::ZeKernel) = KernelState() + +# how a launch identifies its kernel in the report. the stream keeps the kernels it launched +# alive until it has checked the report (see `note_launch!`), so the id is not reused. +kernel_id(kernel::ZeKernel) = UInt(pointer_from_objref(kernel)) % UInt64 + +# Remember that `kernel` was launched on `s`, to look up the exceptions it reports. The +# caller must hold `s.lock`. +@inline function note_launch!(s::oneStream, kernel::ZeKernel) + s.last_launched === kernel && return + push!(s.launched, kernel) + s.last_launched = kernel + return +end # the pattern resetting a claim; a global, as Level Zero does not specify how long a fill's # pattern has to remain valid @@ -185,23 +149,47 @@ end # The caller must hold `s.lock`, and have checked that the stream is idle. function check_exception!(s::oneStream) slot = s.exceptions - unsafe_load(convert(Ptr{Int32}, slot.report)) == 0 && return nothing # `status` + if unsafe_load(convert(Ptr{Int32}, slot.report)) == 0 # `status` + forget_launches!(s) + return nothing + end report = unsafe_load(slot.report) # reset the claim first: if that fails, the exception is still reported later reset_claim!(s.immediate, slot) clear_report!(slot) - nframes = clamp(Int(report.num_frames), 0, EXCEPTION_MAX_FRAMES) - frames = report.frames[1:nframes] - strings = read_device_strings(s.immediate, s.ctx, - [report.name; report.reason; - [frame.func for frame in frames]; - [frame.file for frame in frames]]) - str(address) = get(strings, address, "") - backtrace = Tuple{String, String, Int}[(str(frame.func), str(frame.file), - Int(frame.line)) for frame in frames] - return KernelException(s.dev, str(report.name), str(report.reason), + # the report was written by the device, so it is only trusted to identify a kernel + # launched since the last check, and a site in that kernel's table + kernel = nothing + for k in s.launched + if kernel_id(k) == report.kernel + kernel = k + break + end + end + forget_launches!(s) + sites = kernel === nothing ? GPUCompiler.ExceptionSite[] : kernel.exception_sites + site = get(sites, Int(report.site), nothing) + name, reason, backtrace = if site === nothing + "", "", Tuple{String, String, Int}[] + else + site.name, site.reason, + Tuple{String, String, Int}[(frame.func, frame.file, frame.line) + for frame in site.frames] + end + return KernelException(s.dev, name, reason, Int.(report.work_item[1:3]), Int.(report.work_group[1:3]), backtrace) end + +# Forget the kernels launched on `s`, once the report was checked, unless some may still +# execute: those recorded in a batch, or in batches that failed to submit. The caller must +# hold `s.lock`, and have checked that the stream is idle. +function forget_launches!(s::oneStream) + if s.batch === nothing && isempty(s.failed) + empty!(s.launched) + s.last_launched = nothing + end + return +end diff --git a/src/compiler/execution.jl b/src/compiler/execution.jl index 9c0a3cf5..50f86caf 100644 --- a/src/compiler/execution.jl +++ b/src/compiler/execution.jl @@ -231,7 +231,7 @@ function call_arguments(@nospecialize(F), @nospecialize(TT), nargs::Int) # Add GPUCompiler's hidden state argument here so `onecall` can also call foreign kernels. call_t = Type[KernelState] - call_args = Any[:(KernelState(queue))] + call_args = Any[:(KernelState(queue, kernel.fun))] for (dt, ex) in zip(params, exprs) # filter out ghost arguments that shouldn't be passed @@ -369,7 +369,8 @@ function zefunction_link(source::Core.MethodInstance; kwargs...) end end if fun === nothing - fun = link_kernel(res.image::Vector{UInt8}, res.entry::String, ctx, dev) + fun = link_kernel(res.image::Vector{UInt8}, res.entry::String, + res.exception_sites, ctx, dev) # Don't cache session-local kernel handles while precompiling: the results # struct is serialized into the package image along with its CodeInstance, # and the handles would come back dangling. @@ -399,6 +400,7 @@ end res = @something res GPUCompiler.cached_results(oneAPIResults, job) res.image = compiled.image res.entry = compiled.entry + res.exception_sites = compiled.exception_sites end return res end @@ -442,6 +444,7 @@ end direct |= !s.batching || s.idle || oneL0.sync_each_submission() batch = direct ? nothing : open_batch!(s) register_pending!(s) + note_launch!(s, kernel) if batch === nothing flush_batch!(s) append_launch!(s.immediate, kernel, groups) diff --git a/src/context.jl b/src/context.jl index 245e3546..e42056b5 100644 --- a/src/context.jl +++ b/src/context.jl @@ -296,8 +296,11 @@ mutable struct oneStream scratch_hwm::Int const priority::oneL0.ze_command_queue_priority_t - # where kernels report exceptions, see `check_exception!` + # where kernels report exceptions, and the kernels launched since it was last checked, + # which identify the exception (see `check_exception!`), protected by `lock` const exceptions::ReportSlot + const launched::Base.IdSet{ZeKernel} + last_launched::Union{Nothing, ZeKernel} end function create_stream(ctx::ZeContext, dev::ZeDevice, @@ -324,7 +327,8 @@ function create_stream(ctx::ZeContext, dev::ZeDevice, slot = allocate_report_slot(ctx, dev, list) s = oneStream(ctx, dev, list, ReentrantLock(), batching, nothing, Batch[], Batch[], 0, nothing, true, nothing, DataRef[], - Batch[], nothing, nothing, false, 0, priority, slot) + Batch[], nothing, nothing, false, 0, priority, slot, + Base.IdSet{ZeKernel}(), nothing) finalizer(release_report_slot, s) return register_stream!(ctx, dev, s) end diff --git a/src/device/runtime.jl b/src/device/runtime.jl index b8eb9db1..48110904 100644 --- a/src/device/runtime.jl +++ b/src/device/runtime.jl @@ -9,15 +9,18 @@ struct KernelState heap::LLVMPtr{UInt8, AS.Function} # Addresses of the launching stream's exception report and claim word, or zero when - # exceptions are not reported. Integers, as SPIR-V validation rejects pointer fields in - # by-value kernel arguments. + # exceptions are not reported, and how the host identifies the launched kernel in the + # report (see `check_exception!`). Integers, as SPIR-V validation rejects pointer fields + # in by-value kernel arguments. exception_report::UInt64 exception_claim::UInt64 + exception_kernel::UInt64 end -KernelState(exception_report::UInt64=UInt64(0), exception_claim::UInt64=UInt64(0)) = +KernelState(exception_report::UInt64=UInt64(0), exception_claim::UInt64=UInt64(0), + exception_kernel::UInt64=UInt64(0)) = KernelState(reinterpret(LLVMPtr{UInt8, AS.Function}, C_NULL), - exception_report, exception_claim) + exception_report, exception_claim, exception_kernel) @device_function @inline @generated kernel_state() = GPUCompiler.kernel_state_value(KernelState) @@ -79,142 +82,47 @@ end # # No per-work-item state is kept, as reserving private memory slows down every kernel. # -# What is reported depends on the debug level: at 0 only that an exception was thrown, at 1 -# also the exception's name and reason, and at 2 also the position of the work-item and a -# backtrace. -# -# Strings are reported by the address of the constant holding them, and read by the host. -# Copying them here would put a loop in every reporting function, which GPUCompiler calls -# for every frame of every throw site, and makes IGC generate many times more code. - -const EXCEPTION_MAX_FRAMES = 16 +# A throw only reports the id of its site (see `GPUCompiler.uses_exception_sites`), which +# the host looks up in the table of the kernel that threw. So the report also identifies the +# kernel, as passed by the host in the `KernelState`. -# String fields are addresses of NUL-terminated strings in device memory, or zero. -struct ExceptionFrame - func::UInt64 - file::UInt64 - line::Int32 -end +using GPUCompiler: @gputhrow struct ExceptionReport status::Int32 - num_frames::Int32 + site::Int32 + kernel::UInt64 # Four components, as narrowing or merging adjacent three-component accesses can # produce six-wide vectors, which SPIR-V does not support. work_item::NTuple{4, UInt64} work_group::NTuple{4, UInt64} - name::UInt64 - reason::UInt64 - frames::NTuple{EXCEPTION_MAX_FRAMES, ExceptionFrame} end # Offsets are computed when generating the code, as inference does not always constant-fold -# `fieldoffset` in the code `@gputhrow` reaches, and are added as `UInt64`, as mixing in an -# `Int` would be a checked conversion. +# `fieldoffset` here, and are added as `UInt64`, as mixing in an `Int` would be a checked +# conversion. @generated function report_field(::Val{field}) where {field} T = fieldtype(ExceptionReport, field) offset = fieldoffset(ExceptionReport, Base.fieldindex(ExceptionReport, field)) % UInt64 :(reinterpret(LLVMPtr{$T, AS.CrossWorkgroup}, kernel_state().exception_report + $offset)) end -@generated function frame_field(idx, ::Val{field}) where {field} - T = fieldtype(ExceptionFrame, field) - offset = (fieldoffset(ExceptionReport, Base.fieldindex(ExceptionReport, :frames)) + - fieldoffset(ExceptionFrame, Base.fieldindex(ExceptionFrame, field))) % UInt64 - stride = sizeof(ExceptionFrame) % UInt64 - quote - frame = (idx - 1) % UInt64 * $stride - reinterpret(LLVMPtr{$T, AS.CrossWorkgroup}, - kernel_state().exception_report + frame + $offset) - end -end - -const CString = LLVMPtr{Cchar, AS.CrossWorkgroup} - -@llvmgenerated builder function string_pointer(::Val{str})::CString where {str} - globalstring_ptr!(builder, String(str); addrspace=AS.CrossWorkgroup) -end - -# throw a device-side exception of type `name`, which is reported together with `reason` -macro gputhrow(name::String, reason::String) - # without line numbers, so that backtraces start at the caller - Base.remove_linenums!(quote - if kernel_debug_level() >= 1 - reporting_call(record_exception!, string_pointer($(Val(Symbol(name)))), - string_pointer($(Val(Symbol(reason))))) - end - throw(nothing) - end) -end - -# The work-item's id in the claim word, where zero means unclaimed. Ids repeat beyond 2^32-1 -# work-items, in which case two throwing work-items could both write the report. -@inline function work_item_id() - id = get_global_linear_id() % UInt32 - return id == 0 ? 1 % UInt32 : id -end - -# Claim the report, returning whether this work-item owns it. Idempotent, so that every -# reporting function can check ownership with it. The owner sets the report's status before -# exiting, which keeps work-items with the same id in later kernels from claiming it too. -@device_function @inline function claim_report!() +# Nothing reachable from here may throw, not even a checked conversion. +@device_function function exception_site(site::Int32) claim = kernel_state().exception_claim - claim == 0 && return false + claim == 0 && return # A relaxed claim suffices: the host only reads the report once the kernel has completed. claim_ptr = reinterpret(LLVMPtr{UInt32, AS.CrossWorkgroup}, claim) - id = work_item_id() - old = SPIRVIntrinsics.atomic_cmpxchg!(claim_ptr, 0 % UInt32, id) - old == 0 && return true - return old == id && unsafe_load(report_field(Val(:status))) == 0 -end - -# GPUCompiler inlines throwing functions into every call site, where reporting is kept out -# of line, as it slows down kernels otherwise. Except at -g2, where every frame of every -# throw site is reported too: IGC compiles that faster inlined than as calls. -@inline reporting_call(f, args...) = - kernel_debug_level() >= 2 ? f(args...) : out_of_line(f, args...) -@noinline out_of_line(f, args...) = f(args...) - -string_address(str::CString) = reinterpret(UInt64, str) - -# Record the exception's name and reason, unless one was recorded already: `@gputhrow` comes -# first, and knows a more specific name than GPUCompiler derives from the throw. -@device_function @inline function record_exception!(name::CString, reason::Union{CString, Nothing}=nothing) - reporting_call(claim_report!) || return false - name_ptr = report_field(Val(:name)) - if unsafe_load(name_ptr) == 0 - unsafe_store!(name_ptr, string_address(name)) - reason === nothing || - unsafe_store!(report_field(Val(:reason)), string_address(reason)) + if SPIRVIntrinsics.atomic_xchg!(claim_ptr, 1 % UInt32) == 0 + unsafe_store!(report_field(Val(:site)), site) + unsafe_store!(report_field(Val(:kernel)), kernel_state().exception_kernel) + unsafe_store!(report_field(Val(:work_item)), + (get_local_id(1) % UInt64, get_local_id(2) % UInt64, + get_local_id(3) % UInt64, 0 % UInt64)) + unsafe_store!(report_field(Val(:work_group)), + (get_group_id(1) % UInt64, get_group_id(2) % UInt64, + get_group_id(3) % UInt64, 0 % UInt64)) + unsafe_store!(report_field(Val(:status)), 1 % Int32) end - return true -end - -report_exception(ex) = (reporting_call(record_exception!, ex); return) - -function report_exception_name(ex) - record_exception!(ex) || return - unsafe_store!(report_field(Val(:work_item)), - (get_local_id(1) % UInt64, get_local_id(2) % UInt64, - get_local_id(3) % UInt64, 0 % UInt64)) - unsafe_store!(report_field(Val(:work_group)), - (get_group_id(1) % UInt64, get_group_id(2) % UInt64, - get_group_id(3) % UInt64, 0 % UInt64)) - return -end - -function report_exception_frame(idx, func, file, line) - claim_report!() || return - 1 <= idx <= EXCEPTION_MAX_FRAMES || return - unsafe_store!(frame_field(idx, Val(:func)), string_address(func)) - unsafe_store!(frame_field(idx, Val(:file)), string_address(file)) - unsafe_store!(frame_field(idx, Val(:line)), line % Int32) - unsafe_store!(report_field(Val(:num_frames)), idx % Int32) - return -end - -@device_function function signal_exception() - # At debug level 0 this is the only reporting function, and claims the report. - reporting_call(claim_report!) && unsafe_store!(report_field(Val(:status)), 1 % Int32) return end diff --git a/test/execution.jl b/test/execution.jl index 8747869a..76ac0813 100644 --- a/test/execution.jl +++ b/test/execution.jl @@ -65,11 +65,10 @@ end @testset "debug level" begin T = Tuple{oneDeviceVector{Int, oneAPI.AS.CrossWorkgroup}, Int} - ir(level) = sprint(io -> oneAPI.code_llvm(io, store_checked, T; kernel = true, - debug_level = level)) - @test !occursin("report_exception", ir(0)) - @test occursin("report_exception", ir(1)) && !occursin("report_exception_frame", ir(1)) - @test occursin("report_exception_frame", ir(2)) + sites(level) = zefunction(store_checked, T; debug_level = level).fun.exception_sites + @test isempty(sites(0)) + @test !isempty(sites(1)) && all(site -> isempty(site.frames), sites(1)) + @test !isempty(sites(2)) && all(site -> !isempty(site.frames), sites(2)) end @@ -1382,27 +1381,37 @@ end @testset "exceptions" begin a = oneArray([0]) - # at debug level 0, only that an exception was thrown - @oneapi debug_level=0 store_checked(a, 2) + # at debug level 0, only that an exception was thrown, and by which work-item + @oneapi debug_level=0 items=4 groups=3 store_checked(a, 2) err = kernel_exception() @test err isa KernelException @test err.name == "" && err.reason == "" && isempty(err.backtrace) - @test err.work_item == err.work_group == (0, 0, 0) + @test all(1 .<= err.work_item .<= (4, 1, 1)) + @test all(1 .<= err.work_group .<= (3, 1, 1)) @test kernel_exception() === nothing # at level 1, also the exception's type and reason, as passed to `@gputhrow` - @oneapi debug_level=1 store_checked(a, 2) + @oneapi debug_level=1 items=4 groups=3 store_checked(a, 2) err = kernel_exception() @test err.name == "BoundsError" @test err.reason == "Out-of-bounds array access" - @test err.work_item == (0, 0, 0) && isempty(err.backtrace) - @test occursin("A BoundsError was thrown on", sprint(showerror, err)) + @test all(1 .<= err.work_item .<= (4, 1, 1)) + @test all(1 .<= err.work_group .<= (3, 1, 1)) + @test isempty(err.backtrace) + @test occursin(r"A BoundsError was thrown by work-item \d×1×1 in work-group \d×1×1 on .*: Out-of-bounds array access\nFor more details", + sprint(showerror, err)) # or as derived by GPUCompiler @oneapi debug_level=1 div_kernel(a, 0) err = kernel_exception() @test err.name == "exception" && err.reason == "" + # looked up in the table of the kernel that threw, of all those launched + @oneapi debug_level=1 store_checked(a, 1) + @oneapi debug_level=1 div_kernel(a, 0) + @oneapi debug_level=1 store_checked(a, 1) + err = kernel_exception() + @test err.name == "exception" - # at level 2, also the position of the work-item, and a backtrace + # at level 2, also a backtrace @oneapi debug_level=2 items=4 groups=3 store_checked(a, 2) err = kernel_exception() @test err.name == "BoundsError" @@ -1417,21 +1426,19 @@ end @test err.name == "exception" @test err.backtrace[end][1] == "div_kernel" - # strings are reported by address, which the host only reads if it is valid + # the host only trusts the report to identify a kernel it launched, and a site of it stream = oneAPI.global_stream(context(), device()) - @oneapi debug_level=2 store_checked(a, 2) - oneAPI.flush!(stream) - oneL0.synchronize(stream.immediate) report = convert(Ptr{UInt8}, stream.exceptions.report) field(T, name) = report + fieldoffset(T, Base.fieldindex(T, name)) - unsafe_store!(convert(Ptr{UInt64}, field(oneAPI.ExceptionReport, :name)), - 0x00000deadbeef000) - unsafe_store!(convert(Ptr{UInt64}, field(oneAPI.ExceptionReport, :frames)), - typemax(UInt64)) - err = kernel_exception() - @test err.name == "" && err.reason == "Out-of-bounds array access" - @test err.backtrace[1][1] == "" && err.backtrace[end][1] == "store_checked" - @test kernel_exception() === nothing + for (name, T, val) in ((:kernel, UInt64, 0x00000deadbeef000), (:site, Int32, Int32(1000))) + @oneapi debug_level=2 store_checked(a, 2) + oneAPI.flush!(stream) + oneL0.synchronize(stream.immediate) + unsafe_store!(convert(Ptr{T}, field(oneAPI.ExceptionReport, name)), val) + err = kernel_exception() + @test err.name == "" && isempty(err.backtrace) + @test kernel_exception() === nothing + end # the stream remains usable, and other work-items keep running function partially_oob_kernel(a)