From b9898f041764c1affabd43d007dd349b277df540 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 14:53:31 +0000 Subject: [PATCH] GPU: a kernel's write past an array's end is reported by name, on every GPU, instead of a bare driver error A trap made it "running the kernel failed (719 unspecified launch failure)" on NVIDIA and AMD, and undefined on Intel. Now each element write in a kernel that does not wait at a barrier (a store, +=, Atomics, a tuple's field or whole element, in the kernel or a function it calls) is made only inside the array; the first one past the end is recorded in the module's __tslang_gpu_fault (a cmpxchg on its flag, then thread, index, length), and the runtime reads it where it waits for the kernel (the launch's own sync, gpuWait, the program's end) and stops: "tslang gpu: the kernel 'k' wrote past the end of an array: element 1000 of 1000 (GPU thread 995)", exit 1. The compiler's own check before a write goes only where that write is guarded; any other stays a trap. Drivers look the record up with cuModuleGetGlobal_v2 / hipModuleGetGlobal / zeModuleGetGlobalPointer, optional (missing: no report, the driver still runs). Barrier kernels keep dropping such writes silently. The write costs the one comparison it had; a launch's time is unchanged (0.066 ms median either way). tslang/test/gpu/faults/ has a program per way of writing: all 11 report right on the RTX 5080, JIT and exe. Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 20 +- .../lib/TypeScriptAsyncRuntime/GpuRuntime.c | 153 ++++++++- tslang/test/gpu/CMakeLists.txt | 30 ++ tslang/test/gpu/compile/faults.ts | 23 ++ tslang/test/gpu/faults/README.md | 11 + tslang/test/gpu/faults/add_assign.ts | 13 + tslang/test/gpu/faults/atomics.ts | 12 + tslang/test/gpu/faults/batch.ts | 14 + tslang/test/gpu/faults/element.ts | 12 + tslang/test/gpu/faults/field.ts | 12 + tslang/test/gpu/faults/gpu_array_end.ts | 12 + tslang/test/gpu/faults/gpu_array_read.ts | 14 + tslang/test/gpu/faults/helper.ts | 17 + tslang/test/gpu/faults/negative.ts | 12 + tslang/test/gpu/faults/store.ts | 13 + tslang/test/gpu/faults/typed_array.ts | 12 + tslang/tslang/gpu.cpp | 293 +++++++++++++++--- 17 files changed, 622 insertions(+), 51 deletions(-) create mode 100644 tslang/test/gpu/compile/faults.ts create mode 100644 tslang/test/gpu/faults/README.md create mode 100644 tslang/test/gpu/faults/add_assign.ts create mode 100644 tslang/test/gpu/faults/atomics.ts create mode 100644 tslang/test/gpu/faults/batch.ts create mode 100644 tslang/test/gpu/faults/element.ts create mode 100644 tslang/test/gpu/faults/field.ts create mode 100644 tslang/test/gpu/faults/gpu_array_end.ts create mode 100644 tslang/test/gpu/faults/gpu_array_read.ts create mode 100644 tslang/test/gpu/faults/helper.ts create mode 100644 tslang/test/gpu/faults/negative.ts create mode 100644 tslang/test/gpu/faults/store.ts create mode 100644 tslang/test/gpu/faults/typed_array.ts diff --git a/docs/gpu.md b/docs/gpu.md index 3f2d19806..77e8042b6 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -77,10 +77,22 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i error: gpuLaunch: a kernel reads the program's variable 'scale', which the GPU does not share: pass it to the kernel as an argument ``` -- A write past an array's end, which would grow it on the CPU, stops the kernel with a trap on NVIDIA and AMD. - On Intel it is undefined. In a kernel that waits at `gpuBarrier` it does nothing instead (below). A kernel - called on the CPU does not grow the array either: the write stops the program (`a kernel called on the CPU - wrote past the end of an array`). +- A write past an array's end (or below 0), which would grow the array on the CPU, is not made on the GPU: the + kernel records the first one and goes on, and after it has run the program stops, saying where: + + ``` + tslang gpu: the kernel 'k' wrote past the end of an array: element 1000 of 1000 (GPU thread 995) + ``` + + with exit code 1. That is every way of writing an element: `a[i] = v`, `a[i] += v`, an `Atomics`, a field of a + tuple element (`ps[i].y = v`), a whole element, in the kernel or in a function it calls, on any GPU. The + thread is its `x` among the launch's threads (`i` for `gpuLaunch(k, n, ...)`). A launch that does not wait for + its kernel (its arrays are all `GpuArray`s, or inside `gpuBatch`) reports it where the runtime next waits: + `gpuRead`, `gpuWrite`, `gpuFree`, the batch's end, or the program's end. The check is the one the CPU makes + before such a write anyway, a comparison per write. In a kernel that waits at `gpuBarrier` such a write does + nothing instead, silently (below). A kernel called on the CPU does not grow the array either: the write stops + the program (`a kernel called on the CPU wrote past the end of an array`). `tslang/test/gpu/faults/` has a + program for each way. - `gpuLaunch`, `gpuReduce` and `gpuBatch` need the default memory model (`-mm=gc`). ## The GPU's `Math` library diff --git a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c index cd3f413a0..20de901a7 100644 --- a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c +++ b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c @@ -92,6 +92,9 @@ typedef struct GpuResult (*synchronize)(void); const char *(*errorText)(GpuResult result); GpuResult (*makeCurrent)(void); // before a launch from this thread (CUDA's context); may be NULL + // where a module's global variable is on the GPU, and its bytes; NULL when the driver has no such entry point + // (then a kernel's faults are not reported by name: gpuFaultWatch) + GpuResult (*getGlobal)(void *module, const char *name, GpuPtr *ptr, size_t *bytes); } GpuDriver; static void gpuFail(GpuDriver *driver, const char *what, GpuResult r) @@ -160,6 +163,7 @@ static struct void **, void **); GpuResult (*cuCtxSynchronize)(void); GpuResult (*cuGetErrorString)(GpuResult, const char **); + GpuResult (*cuModuleGetGlobal)(GpuPtr *, size_t *, void *, const char *); void *ctx; } cu; @@ -194,9 +198,13 @@ static const char *cudaErrorText(GpuResult r) return text; } static GpuResult cudaMakeCurrent(void) { return cu.cuCtxSetCurrent(cu.ctx); } +static GpuResult cudaGetGlobal(void *module, const char *name, GpuPtr *ptr, size_t *bytes) +{ + return cu.cuModuleGetGlobal(ptr, bytes, module, name); +} static GpuDriver cudaDriver = {"cuda", 0, "", cudaLoadModule, cudaGetFunction, cudaAlloc, cudaFree, cudaToDevice, - cudaToHost, cudaLaunch, cudaSynchronize, cudaErrorText, cudaMakeCurrent}; + cudaToHost, cudaLaunch, cudaSynchronize, cudaErrorText, cudaMakeCurrent, NULL}; static GpuDriver *cudaInit(void) { @@ -217,6 +225,9 @@ static GpuDriver *cudaInit(void) GPU_SYM(driver, lib, cu.cuLaunchKernel, "cuLaunchKernel"); GPU_SYM(driver, lib, cu.cuCtxSynchronize, "cuCtxSynchronize"); GPU_SYM(driver, lib, cu.cuGetErrorString, "cuGetErrorString"); + // optional: without it the driver still runs kernels, only not reporting their faults by name + if ((*(void **)&cu.cuModuleGetGlobal = gpuSym(lib, "cuModuleGetGlobal_v2"))) + driver->getGlobal = cudaGetGlobal; int dev; GpuResult r = cu.cuInit(0); if (r != 0) @@ -247,6 +258,7 @@ static struct void *, void **, void **); GpuResult (*hipDeviceSynchronize)(void); const char *(*hipGetErrorString)(GpuResult); + GpuResult (*hipModuleGetGlobal)(void **, size_t *, void *, const char *); } hip; static void *hipLoadModule(const void *code, size_t size, char *log, size_t logSize, GpuResult *result) @@ -286,9 +298,16 @@ static GpuResult hipLaunch(void *fn, const unsigned *grid, const unsigned *block static GpuResult hipSynchronize(void) { return hip.hipDeviceSynchronize(); } static const char *hipErrorText(GpuResult r) { return hip.hipGetErrorString ? hip.hipGetErrorString(r) : ""; } static GpuResult hipMakeCurrent(void) { return hip.hipSetDevice(0); } +static GpuResult hipGetGlobal(void *module, const char *name, GpuPtr *ptr, size_t *bytes) +{ + void *p = NULL; + GpuResult r = hip.hipModuleGetGlobal(&p, bytes, module, name); + *ptr = (GpuPtr)(uintptr_t)p; + return r; +} static GpuDriver hipDriver = {"hip", 0, "", hipLoadModule, hipGetFunction, hipAlloc, hipFreeBuffer, hipToDevice, - hipToHost, hipLaunch, hipSynchronize, hipErrorText, hipMakeCurrent}; + hipToHost, hipLaunch, hipSynchronize, hipErrorText, hipMakeCurrent, NULL}; static GpuDriver *hipInitDriver(void) { @@ -307,6 +326,8 @@ static GpuDriver *hipInitDriver(void) GPU_SYM(driver, lib, hip.hipModuleLaunchKernel, "hipModuleLaunchKernel"); GPU_SYM(driver, lib, hip.hipDeviceSynchronize, "hipDeviceSynchronize"); GPU_SYM(driver, lib, hip.hipGetErrorString, "hipGetErrorString"); + if ((*(void **)&hip.hipModuleGetGlobal = gpuSym(lib, "hipModuleGetGlobal"))) + driver->getGlobal = hipGetGlobal; GpuResult r = hip.hipInit(0); if (r != 0) return gpuUnusable(driver, "hipInit failed: no AMD GPU", r); @@ -413,6 +434,7 @@ static struct GpuResult (*zeKernelSetIndirectAccess)(void *, uint32_t); GpuResult (*zeCommandListAppendLaunchKernel)(void *, void *, const ze_group_count_t *, void *, uint32_t, void **); GpuResult (*zeDriverGetLastErrorDescription)(void *, const char **); // since 1.6; may be missing + GpuResult (*zeModuleGetGlobalPointer)(void *, const char *, size_t *, void **); void *driver; void *device; void *context; @@ -510,9 +532,17 @@ static const char *levelZeroErrorText(GpuResult r) return text; } +static GpuResult levelZeroGetGlobal(void *module, const char *name, GpuPtr *ptr, size_t *bytes) +{ + void *p = NULL; + GpuResult r = ze.zeModuleGetGlobalPointer(module, name, bytes, &p); + *ptr = (GpuPtr)(uintptr_t)p; + return r; +} + static GpuDriver levelZeroDriver = {"level zero", 0, "", levelZeroLoadModule, levelZeroGetFunction, levelZeroAlloc, levelZeroFree, levelZeroToDevice, levelZeroToHost, - levelZeroLaunch, levelZeroSynchronize, levelZeroErrorText, NULL}; + levelZeroLaunch, levelZeroSynchronize, levelZeroErrorText, NULL, NULL}; static GpuDriver *levelZeroInit(void) { @@ -539,6 +569,8 @@ static GpuDriver *levelZeroInit(void) GPU_SYM(driver, lib, ze.zeKernelSetIndirectAccess, "zeKernelSetIndirectAccess"); GPU_SYM(driver, lib, ze.zeCommandListAppendLaunchKernel, "zeCommandListAppendLaunchKernel"); *(void **)&ze.zeDriverGetLastErrorDescription = gpuSym(lib, "zeDriverGetLastErrorDescription"); + if ((*(void **)&ze.zeModuleGetGlobalPointer = gpuSym(lib, "zeModuleGetGlobalPointer"))) + driver->getGlobal = levelZeroGetGlobal; // GPU drivers only (not the NPU's), and of their devices the first GPU if (ze.zeInit(ZE_INIT_FLAG_GPU_ONLY) == 0) @@ -684,6 +716,97 @@ static void gpuAppend(char *text, size_t size, const char *line) snprintf(text + used, size - used, " %s\n", line); } +// ---- a kernel's fault: a write past an array's end +// +// On the GPU such a write is not made (there is no growing an array there): the kernel records the first one in +// its module's global `__tslang_gpu_fault` (tslang/gpu.cpp's recordKernelFaults) and goes on. After the kernel has +// run, wherever the runtime waits for it, the record is read, and a fault stops the program, as the same write +// past the end does in a kernel called on the CPU. +typedef struct +{ + int32_t flag; // 1: a fault is recorded + int32_t thread; // the GPU thread that made it (its x) + int64_t index; // the element written + int64_t length; // the array's length +} GpuFault; + +#define GPU_FAULT_GLOBAL "__tslang_gpu_fault" + +static struct +{ + GpuDriver *driver; + GpuPtr record; +} gpuFaults[16]; +static int gpuFaultCount; + +// a kernel queued without waiting for it (gpuLaunched): the last one's name, and how many since the last wait +static const char *gpuQueuedKernel; +static int gpuQueuedCount; + +static void gpuFaultWatch(GpuDriver *driver, void *module) +{ + GpuPtr record = 0; + size_t bytes = 0; + if (!driver->getGlobal || gpuFaultCount >= 16 || + driver->getGlobal(module, GPU_FAULT_GLOBAL, &record, &bytes) != 0 || !record || bytes < sizeof(GpuFault)) + return; + gpuFaults[gpuFaultCount].driver = driver; + gpuFaults[gpuFaultCount++].record = record; +} + +// the program's name of a kernel's entry: __gpu_k, __gpu_k_2d, __gpu_reduce_k are k's +static void gpuKernelName(const char *entry, char *name, size_t size) +{ + const char *start = entry; + if (strncmp(start, "__gpu_reduce_", 13) == 0) + start += 13; + else if (strncmp(start, "__gpu_", 6) == 0) + start += 6; + size_t length = strlen(start); + if (length > 3 && start[length - 3] == '_' && (start[length - 2] == '2' || start[length - 2] == '3') && + start[length - 1] == 'd') + length -= 3; + snprintf(name, size, "%.*s", (int)length, start); +} + +// After `driver` has run its kernels: 1 when one of them recorded a fault, said on stderr. `entry` is the kernel +// waited for, or NULL for those queued since the last wait. +static int gpuFaultReport(GpuDriver *driver, const char *entry) +{ + for (int i = 0; i < gpuFaultCount; i++) + { + GpuFault fault; + if (gpuFaults[i].driver != driver || driver->toHost(&fault, gpuFaults[i].record, sizeof(fault)) != 0 || + !fault.flag) + continue; + + char name[256]; + char which[512]; + if (!entry && gpuQueuedCount == 1) + entry = gpuQueuedKernel; + if (entry) + { + gpuKernelName(entry, name, sizeof(name)); + snprintf(which, sizeof(which), "the kernel '%s'", name); + } + else + { + gpuKernelName(gpuQueuedKernel ? gpuQueuedKernel : "?", name, sizeof(name)); + snprintf(which, sizeof(which), + "a kernel launched since the last wait (the last was '%s'; TSLANG_GPU_SYNC=1 says which)", name); + } + + // what the program printed comes first + fflush(stdout); + fprintf(stderr, "tslang gpu: %s wrote past the end of an array: element %lld of %lld (GPU thread %d)\n", + which, (long long)fault.index, (long long)fault.length, fault.thread); + fflush(stderr); + return 1; + } + + return 0; +} + static GpuDriver *gpuChoose(const TsGpuImage *images, int32_t imageCount, void **module) { for (int i = 0; i < gpuChosenCount; i++) @@ -728,6 +851,7 @@ static GpuDriver *gpuChoose(const TsGpuImage *images, int32_t imageCount, void * if (getenv("TSLANG_GPU_VERBOSE")) fprintf(stderr, "tslang gpu: running the kernels through %s (%s)\n", driver->name, images[i].arch); + gpuFaultWatch(driver, loaded); if (gpuChosenCount < 16) { gpuChosen[gpuChosenCount].images = images; @@ -822,6 +946,9 @@ static void gpuWait(void) if (driver->makeCurrent) GPU(driver, driver->makeCurrent(), "making the GPU current"); GPU(driver, driver->synchronize(), "running a kernel (an earlier launch's: TSLANG_GPU_SYNC=1 says which)"); + if (gpuFaultReport(driver, NULL)) + exit(1); + gpuQueuedCount = 0; } // At the program's end: the launches still running finish, and an error of theirs is reported. 0, or 1 when a @@ -837,7 +964,7 @@ TSLANG_GPU_EXPORT int __tslang_gpu_finish(void) if (r == 0) r = driver->synchronize(); if (r == 0) - return 0; + return gpuFaultReport(driver, NULL); // what the program printed comes first fflush(stdout); const char *text = driver->errorText ? driver->errorText(r) : ""; @@ -856,7 +983,7 @@ static void gpuWaitAtExit(void) } } -static void gpuLaunched(GpuDriver *driver) +static void gpuLaunched(GpuDriver *driver, const char *entry) { static int atExit; if (!atExit) @@ -868,6 +995,8 @@ static void gpuLaunched(GpuDriver *driver) if (gpuPending && gpuPending != driver) gpuWait(); gpuPending = driver; + gpuQueuedKernel = entry; + gpuQueuedCount++; } // ---- gpuBatch: arrays that stay on the GPU between launches @@ -1478,12 +1607,24 @@ TSLANG_GPU_EXPORT void __tslang_gpu_run(const TsGpuImage *images, int32_t imageC if (copied || gpuSyncEachLaunch()) { GPU(driver, driver->synchronize(), "running the kernel"); + // the kernels queued before it ran too: a fault is this one's, or one of theirs + int queued = gpuPending == driver && gpuQueuedCount > 0; + if (queued) + { + gpuQueuedKernel = kernelName; + gpuQueuedCount++; + } + if (gpuFaultReport(driver, queued ? NULL : kernelName)) + exit(1); if (gpuPending == driver) + { gpuPending = NULL; + gpuQueuedCount = 0; + } } else { - gpuLaunched(driver); + gpuLaunched(driver, kernelName); } double ran = profile ? gpuNow() : 0; diff --git a/tslang/test/gpu/CMakeLists.txt b/tslang/test/gpu/CMakeLists.txt index 62774cfd7..ab27b200b 100644 --- a/tslang/test/gpu/CMakeLists.txt +++ b/tslang/test/gpu/CMakeLists.txt @@ -456,6 +456,36 @@ if (gpu_any_backend) FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) endif() + # a kernel's writes past an array's end are recorded, not trapped: every way of writing an element is guarded + # (6 calls of the record, no trap left), and the record is the module's own for the runtime to find; for every + # GPU, Intel's SPIR-V valid + set(gpu_faults_pass "call void @__tslang_gpu_run") + if ("NVPTX" IN_LIST LLVM_TARGETS_TO_BUILD) + # (CMake's expressions have no {6}) + set(gpu_faults_call ".*call\\.uni __tslang_gpu_fault_record") + set(gpu_faults_pass "\\.visible \\.global \\.align 8 \\.b8 __tslang_gpu_fault\\[24\\]${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}") + endif() + add_test(NAME test-gpu-compile-faults + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/faults.ts" -o -) + set_tests_properties(test-gpu-compile-faults PROPERTIES + PASS_REGULAR_EXPRESSION "${gpu_faults_pass}" + FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR|trap;" + TIMEOUT 120) + set(gpu_faults_environment "") + if (TSLANG_GPU_LLD AND gpu_lld_result EQUAL 0) + list(APPEND gpu_faults_environment "TSLANG_LLD=${TSLANG_GPU_LLD}") + endif() + if (TSLANG_SPIRV_VAL) + list(APPEND gpu_faults_environment "TSLANG_GPU_DUMP=${CMAKE_CURRENT_BINARY_DIR}/faults") + set_tests_properties(test-gpu-compile-faults PROPERTIES FIXTURES_SETUP gpu-intel-faults) + add_test(NAME test-gpu-spirv-val-faults + COMMAND "${TSLANG_SPIRV_VAL}" --target-env opencl2.2 "${CMAKE_CURRENT_BINARY_DIR}/faults.intel") + set_tests_properties(test-gpu-spirv-val-faults PROPERTIES FIXTURES_REQUIRED gpu-intel-faults TIMEOUT 60) + endif() + if (gpu_faults_environment) + set_tests_properties(test-gpu-compile-faults PROPERTIES ENVIRONMENT "${gpu_faults_environment}") + endif() + # arrays of tuples and object types: each element's bytes as LLVM lays them out (Mixed 32 with its padding, # [number, int] 16 and only read, 0x10000), for every GPU; Intel's SPIR-V valid add_test(NAME test-gpu-compile-structs diff --git a/tslang/test/gpu/compile/faults.ts b/tslang/test/gpu/compile/faults.ts new file mode 100644 index 000000000..f75031b69 --- /dev/null +++ b/tslang/test/gpu/compile/faults.ts @@ -0,0 +1,23 @@ +// every way a kernel writes an element is guarded and recorded, so no trap is left: a store, `+=`, an Atomics, a +// tuple's field, a whole element, a helper's write (a typed array's: faults/typed_array.ts) +function put(a: number[], at: int, v: number) { + a[at] = v; +} + +@kernel +function k(i: int, a: number[], counts: int[], ps: { x: number, y: number }[], ts: [number, int][]) { + a[i + 1] = i; + counts[i] += 2; + Atomics.add(counts, i, 1); + ps[i].y = 3; + ts[i] = [i, i]; + put(a, i + 2, 1); +} + +function main() { + const a: number[] = [0]; + const counts: int[] = [0]; + const ps: { x: number, y: number }[] = [{ x: 0, y: 0 }]; + const ts: [number, int][] = [[0, 0]]; + gpuLaunch(k, 1, a, counts, ps, ts); +} diff --git a/tslang/test/gpu/faults/README.md b/tslang/test/gpu/faults/README.md new file mode 100644 index 000000000..73a763c79 --- /dev/null +++ b/tslang/test/gpu/faults/README.md @@ -0,0 +1,11 @@ +# Kernel faults + +Each program here has a kernel write past the end of an array, in one way or another, on the GPU. That write is not +made, and the program stops after the kernel with (on stderr, exit code 1): + + tslang gpu: the kernel 'k' wrote past the end of an array: element of (GPU thread ) + +Each prints `before` first, and never `after`. They need a GPU and its driver, so they are not part of the test +suite; run each under the JIT and as an executable: + + for f in tslang/test/gpu/faults/*.ts; do tslang --emit=jit $f; echo "exit $?"; done diff --git a/tslang/test/gpu/faults/add_assign.ts b/tslang/test/gpu/faults/add_assign.ts new file mode 100644 index 000000000..80b192070 --- /dev/null +++ b/tslang/test/gpu/faults/add_assign.ts @@ -0,0 +1,13 @@ +// `+=` past the end (a read and a write) +@kernel +function k(i: int, a: int[]) { + a[i * 2] += 1; +} + +function main() { + const a: int[] = []; + for (let i = 0; i < 100; i++) a.push(0); + print("before"); + gpuLaunch(k, 100, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/atomics.ts b/tslang/test/gpu/faults/atomics.ts new file mode 100644 index 000000000..e91d96a84 --- /dev/null +++ b/tslang/test/gpu/faults/atomics.ts @@ -0,0 +1,12 @@ +// an Atomics past the end +@kernel +function k(i: int, counts: int[]) { + Atomics.add(counts, i, 1); +} + +function main() { + const counts: int[] = [0, 0, 0]; + print("before"); + gpuLaunch(k, 64, counts); + print("after"); +} diff --git a/tslang/test/gpu/faults/batch.ts b/tslang/test/gpu/faults/batch.ts new file mode 100644 index 000000000..1ca1b89fb --- /dev/null +++ b/tslang/test/gpu/faults/batch.ts @@ -0,0 +1,14 @@ +// inside gpuBatch: reported at the batch's end, where its arrays are copied back +@kernel +function k(i: int, a: number[]) { + a[i + 2] = i; +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + print("before"); + gpuBatch(() => { + gpuLaunch(k, 4, a); + }); + print("after"); +} diff --git a/tslang/test/gpu/faults/element.ts b/tslang/test/gpu/faults/element.ts new file mode 100644 index 000000000..22c470cd1 --- /dev/null +++ b/tslang/test/gpu/faults/element.ts @@ -0,0 +1,12 @@ +// a whole tuple element past the end +@kernel +function k(i: int, ps: [number, int][]) { + ps[i + 3] = [i, i]; +} + +function main() { + const ps: [number, int][] = [[0, 0], [0, 0], [0, 0]]; + print("before"); + gpuLaunch(k, 3, ps); + print("after"); +} diff --git a/tslang/test/gpu/faults/field.ts b/tslang/test/gpu/faults/field.ts new file mode 100644 index 000000000..180d836f8 --- /dev/null +++ b/tslang/test/gpu/faults/field.ts @@ -0,0 +1,12 @@ +// a field of a tuple element past the end +@kernel +function k(i: int, ps: { x: number, y: number }[]) { + ps[i + 1].y = i; +} + +function main() { + const ps: { x: number, y: number }[] = [{ x: 0, y: 0 }, { x: 0, y: 0 }]; + print("before"); + gpuLaunch(k, 2, ps); + print("after"); +} diff --git a/tslang/test/gpu/faults/gpu_array_end.ts b/tslang/test/gpu/faults/gpu_array_end.ts new file mode 100644 index 000000000..ed4a519b0 --- /dev/null +++ b/tslang/test/gpu/faults/gpu_array_end.ts @@ -0,0 +1,12 @@ +// a launch on a GpuArray nothing waits for: its fault is reported when the program ends +@kernel +function k(i: int, a: number[]) { + a[i + 1] = i; +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + const onGpu = gpuArray(a); + gpuLaunch(k, 4, onGpu); + print("before"); +} diff --git a/tslang/test/gpu/faults/gpu_array_read.ts b/tslang/test/gpu/faults/gpu_array_read.ts new file mode 100644 index 000000000..098f7f94b --- /dev/null +++ b/tslang/test/gpu/faults/gpu_array_read.ts @@ -0,0 +1,14 @@ +// a launch on a GpuArray does not wait for the kernel: its fault is reported at gpuRead, which waits +@kernel +function k(i: int, a: number[]) { + a[i + 1] = i; +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + const onGpu = gpuArray(a); + gpuLaunch(k, 4, onGpu); + print("before"); + gpuRead(onGpu, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/helper.ts b/tslang/test/gpu/faults/helper.ts new file mode 100644 index 000000000..6763427a4 --- /dev/null +++ b/tslang/test/gpu/faults/helper.ts @@ -0,0 +1,17 @@ +// a write past the end in a function the kernel calls (not a kernel itself: its write would grow the array on the +// CPU) +function put(a: number[], at: int, v: number) { + a[at] = v; +} + +@kernel +function k(i: int, a: number[]) { + put(a, i + 1, i); +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + print("before"); + gpuLaunch(k, 4, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/negative.ts b/tslang/test/gpu/faults/negative.ts new file mode 100644 index 000000000..425952e55 --- /dev/null +++ b/tslang/test/gpu/faults/negative.ts @@ -0,0 +1,12 @@ +// an index below 0 is past the end too +@kernel +function k(i: int, a: number[]) { + a[i - 1] = i; +} + +function main() { + const a: number[] = [0, 0, 0]; + print("before"); + gpuLaunch(k, 3, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/store.ts b/tslang/test/gpu/faults/store.ts new file mode 100644 index 000000000..90f3aede9 --- /dev/null +++ b/tslang/test/gpu/faults/store.ts @@ -0,0 +1,13 @@ +// a plain store past the end, by the last five threads +@kernel +function k(i: int, a: number[]) { + a[i + 5] = i; +} + +function main() { + const a: number[] = []; + for (let i = 0; i < 1000; i++) a.push(0); + print("before"); + gpuLaunch(k, 1000, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/typed_array.ts b/tslang/test/gpu/faults/typed_array.ts new file mode 100644 index 000000000..4f83cc34f --- /dev/null +++ b/tslang/test/gpu/faults/typed_array.ts @@ -0,0 +1,12 @@ +// a typed array's view: past its end, not past the buffer's (the elements after the subarray are not touched) +@kernel +function k(i: int, a: Float32Array) { + a[i + 1] = 7; +} + +function main() { + const big = new Float32Array(10); + print("before"); + gpuLaunch(k, 5, big.subarray(0, 5)); + print("after"); +} diff --git a/tslang/tslang/gpu.cpp b/tslang/tslang/gpu.cpp index 8f440b9eb..b93536144 100644 --- a/tslang/tslang/gpu.cpp +++ b/tslang/tslang/gpu.cpp @@ -145,6 +145,11 @@ constexpr int32_t gpuBlockThreads = 256; // barrier kernel's mark, whose last parameter is whether the thread runs for an index below n #define IS_SHARED_STUB "__tslang_gpu_is_shared" #define ACTIVE_ATTR "tslang.gpu_active" +// a kernel's first write past an array's end (recordKernelFaults), which GpuRuntime.c reads after the kernel ran: +// { i32 flag, i32 thread, i64 index, i64 length }; the thread (its x) is the GPU's to say +#define FAULT_GLOBAL "__tslang_gpu_fault" +#define FAULT_RECORD_FUNCTION "__tslang_gpu_fault_record" +#define FAULT_THREAD_STUB "__tslang_gpu_fault_thread" // What a warp's threads share (MLIRGenImpl::mlirGenGpuWarpBuiltin; docs/gpu.md): its lanes run together, and a // kernel that uses these runs like a barrier kernel, on every thread of its blocks (reachesBarrier), so that no // lane of a warp is left out by the `i < n` check. gpuShuffle's stubs are @@ -204,7 +209,8 @@ bool isBlockBuiltin(llvm::StringRef name) { auto stub = blockBuiltinOf(name).first; return stub == THREAD_INDEX_STUB || stub == BLOCK_INDEX_STUB || stub == BLOCK_SIZE_STUB || name == BARRIER_STUB || - name.starts_with(SHARED_STUB_PREFIX) || name == IS_SHARED_STUB || name.starts_with(WARP_STUB_PREFIX); + name.starts_with(SHARED_STUB_PREFIX) || name == IS_SHARED_STUB || name.starts_with(WARP_STUB_PREFIX) || + name == FAULT_THREAD_STUB; } BlockShape kernelBlock(const llvm::Function *kernel) @@ -1361,6 +1367,60 @@ std::set reachedFrom(llvm::ArrayRef roots) return reached; } +// an array's { data, length, capacity } header, as LowerToLLVM makes it +bool isArrayHeader(llvm::Type *type) +{ + auto structType = llvm::dyn_cast(type); + return structType && structType->getNumElements() == 3 && structType->getElementType(0)->isPointerTy() && + structType->getElementType(1)->isIntegerTy(64) && structType->getElementType(2)->isIntegerTy(64); +} + +// An element of an array (or a field of one) that `pointer` points at, as LowerToLLVM makes the access: `gep T, +// data, index`, data loaded from the header's first field (`load (gep { ptr, i64, i64 }, header, 0, 0)`), and a +// tuple element's field `gep S, element, 0, field` (fields of fields too). The header, the data and the element. +struct ElementAccess +{ + llvm::Value *header; + llvm::LoadInst *data; + llvm::GetElementPtrInst *element; +}; + +std::optional matchElementAccess(llvm::Value *pointer) +{ + while (auto field = llvm::dyn_cast(pointer)) + { + auto first = field->getNumIndices() >= 2 ? llvm::dyn_cast(*field->idx_begin()) : nullptr; + if (!first || !first->isZero() || !field->getSourceElementType()->isStructTy() || + isArrayHeader(field->getSourceElementType())) + { + break; + } + + pointer = field->getPointerOperand(); + } + + auto element = llvm::dyn_cast(pointer); + if (!element || element->getNumIndices() != 1) + { + return std::nullopt; + } + + auto data = llvm::dyn_cast(element->getPointerOperand()); + if (!data || !data->getType()->isPointerTy()) + { + return std::nullopt; + } + + auto dataField = llvm::dyn_cast(data->getPointerOperand()); + if (!dataField || !isArrayHeader(dataField->getSourceElementType()) || dataField->getNumIndices() != 2 || + !dataField->hasAllZeroIndices()) + { + return std::nullopt; + } + + return ElementAccess{dataField->getPointerOperand(), data, element}; +} + // A kernel that waits at gpuBarrier runs on every thread of its blocks, the last block's past n too (a barrier is // reached by all of a block's threads, or it waits for ever). So that it need not check i < n itself, its array // accesses are guarded, in it and in what it calls (docs/gpu.md): @@ -1497,12 +1557,6 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern } } - auto isHeader = [&](llvm::Type *type) { - auto structType = llvm::dyn_cast(type); - return structType && structType->getNumElements() == 3 && structType->getElementType(0)->isPointerTy() && - structType->getElementType(1)->isIntegerTy(64) && structType->getElementType(2)->isIntegerTy(64); - }; - for (auto [original, function] : guarded) { auto active = function->getArg(function->arg_size() - 1); @@ -1539,41 +1593,13 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern : llvm::cast(access)->getPointerOperand(); } - // a field of a tuple element (`ps[i].x`): gep S, element, 0, field (fields of fields too) - while (auto field = llvm::dyn_cast(pointer)) - { - auto first = field->getNumIndices() >= 2 ? llvm::dyn_cast(*field->idx_begin()) - : nullptr; - if (!first || !first->isZero() || !field->getSourceElementType()->isStructTy() || - isHeader(field->getSourceElementType())) - { - break; - } - - pointer = field->getPointerOperand(); - } - - // gep T, data, index; data = load (gep { ptr, i64, i64 }, header, 0, 0) - auto element = llvm::dyn_cast(pointer); - if (!element || element->getNumIndices() != 1) + auto matched = matchElementAccess(pointer); + if (!matched) { continue; } - auto data = llvm::dyn_cast(element->getPointerOperand()); - if (!data || !data->getType()->isPointerTy()) - { - continue; - } - - auto dataField = llvm::dyn_cast(data->getPointerOperand()); - if (!dataField || !isHeader(dataField->getSourceElementType()) || dataField->getNumIndices() != 2 || - !dataField->hasAllZeroIndices()) - { - continue; - } - - auto header = dataField->getPointerOperand(); + auto [header, data, element] = *matched; auto writes = !llvm::isa(access); llvm::IRBuilder<> builder(access); @@ -1602,6 +1628,174 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern } } +// an index as it was before it was widened or narrowed for a comparison or an address +llvm::Value *stripIndexCasts(llvm::Value *value) +{ + while (llvm::isa(value)) + { + value = llvm::cast(value)->getOperand(0); + } + + return value; +} + +// A write past an array's end grows the array on the CPU; a GPU cannot (its memory is not the heap). In the +// kernels that do not wait at a barrier (whose guard drops such writes: guardBarrierKernels), and what they call, +// each write of an array's element (a store, an Atomics; a field of a tuple element too) is made only inside the +// array: past its end it is not made, and the first such write is recorded in FAULT_GLOBAL, which the runtime +// reads after the kernel and stops the program with (GpuRuntime.c's gpuFaultReport). The compiler's own check +// before such a write (the CPU's grow, or in a @kernel __tslang_gpu_past_end) goes when the write it is for is +// guarded here; one whose write is not recognized stays a trap, so that no write past the end is made unseen. +void recordKernelFaults(llvm::Module &device, const std::set &kernelNames) +{ + llvm::SmallVector kernels; + for (auto &kernelName : kernelNames) + { + if (auto kernel = device.getFunction(kernelName); kernel && !kernel->hasFnAttribute(ACTIVE_ATTR)) + { + kernels.push_back(kernel); + } + } + + if (kernels.empty()) + { + return; + } + + auto &context = device.getContext(); + auto i32 = llvm::Type::getInt32Ty(context); + auto i64 = llvm::Type::getInt64Ty(context); + auto ptr = llvm::PointerType::get(context, 0); + auto headerType = llvm::StructType::get(context, {ptr, i64, i64}); + auto faultType = llvm::StructType::get(context, {i32, i32, i64, i64}); + auto fault = device.getGlobalVariable(FAULT_GLOBAL); + if (!fault) + { + fault = new llvm::GlobalVariable(device, faultType, false, llvm::GlobalValue::ExternalLinkage, + llvm::ConstantAggregateZero::get(faultType), FAULT_GLOBAL); + fault->setAlignment(llvm::Align(8)); + } + + // the record: the first fault's thread, index and length (the flag taken by one thread only) + auto record = device.getFunction(FAULT_RECORD_FUNCTION); + if (!record) + { + record = llvm::Function::Create(llvm::FunctionType::get(llvm::Type::getVoidTy(context), {i64, i64}, false), + llvm::GlobalValue::InternalLinkage, FAULT_RECORD_FUNCTION, device); + record->addFnAttr(llvm::Attribute::Cold); + record->addFnAttr(llvm::Attribute::NoInline); + auto entry = llvm::BasicBlock::Create(context, "entry", record); + auto write = llvm::BasicBlock::Create(context, "write", record); + auto done = llvm::BasicBlock::Create(context, "done", record); + llvm::IRBuilder<> builder(entry); + auto exchange = builder.CreateAtomicCmpXchg(builder.CreateStructGEP(faultType, fault, 0), builder.getInt32(0), + builder.getInt32(1), llvm::MaybeAlign(4), + llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Monotonic); + builder.CreateCondBr(builder.CreateExtractValue(exchange, 1), write, done); + builder.SetInsertPoint(write); + auto thread = builder.CreateCall(device.getOrInsertFunction(FAULT_THREAD_STUB, llvm::FunctionType::get(i32, false))); + builder.CreateStore(thread, builder.CreateStructGEP(faultType, fault, 1)); + builder.CreateStore(record->getArg(0), builder.CreateStructGEP(faultType, fault, 2)); + builder.CreateStore(record->getArg(1), builder.CreateStructGEP(faultType, fault, 3)); + builder.CreateBr(done); + builder.SetInsertPoint(done); + builder.CreateRetVoid(); + } + + for (auto function : reachedFrom(kernels)) + { + if (function == record || function->getName().starts_with(".array_grow.")) + { + continue; + } + + llvm::SmallVector writes; + llvm::SmallVector checks; + for (auto &instruction : llvm::instructions(*function)) + { + if (llvm::isa(&instruction)) + { + writes.push_back(&instruction); + } + else if (auto call = llvm::dyn_cast(&instruction)) + { + if (auto callee = call->getCalledFunction(); + callee && (callee->getName().starts_with(".array_grow.") || callee->getName() == "__tslang_gpu_past_end")) + { + checks.push_back(call); + } + } + } + + // the indices whose writes are guarded + llvm::SmallPtrSet guarded; + for (auto access : writes) + { + auto pointer = llvm::getLoadStorePointerOperand(access); + if (!pointer) + { + pointer = llvm::isa(access) + ? llvm::cast(access)->getPointerOperand() + : llvm::cast(access)->getPointerOperand(); + } + + auto matched = matchElementAccess(pointer); + if (!matched) + { + continue; + } + + auto [header, data, element] = *matched; + llvm::IRBuilder<> builder(access); + auto length = builder.CreateLoad(i64, builder.CreateStructGEP(headerType, header, 1), "gpu.length"); + auto index = builder.CreateSExtOrTrunc(*element->idx_begin(), i64); + // unsigned: a negative index is past the end too + auto inside = builder.CreateICmpULT(index, length, "gpu.inside"); + llvm::Instruction *thenTerminator = nullptr; + llvm::Instruction *elseTerminator = nullptr; + llvm::SplitBlockAndInsertIfThenElse(inside, access->getIterator(), &thenTerminator, &elseTerminator); + auto tail = access->getParent(); + access->moveBefore(thenTerminator->getIterator()); + llvm::IRBuilder<> faultBuilder(elseTerminator); + faultBuilder.CreateCall(record, {index, length}); + if (!access->getType()->isVoidTy()) + { + // what the skipped Atomics gives: 0 + auto phi = llvm::PHINode::Create(access->getType(), 2, "gpu.written", tail->begin()); + access->replaceAllUsesWith(phi); + phi->addIncoming(access, thenTerminator->getParent()); + phi->addIncoming(llvm::Constant::getNullValue(access->getType()), elseTerminator->getParent()); + } + + guarded.insert(stripIndexCasts(*element->idx_begin())); + } + + // the compiler's check before a write: `br (index >= length), check, write` + for (auto call : checks) + { + auto covered = false; + if (auto before = call->getParent()->getSinglePredecessor()) + { + if (auto branch = llvm::dyn_cast(before->getTerminator())) + { + if (auto compare = llvm::dyn_cast(branch->getCondition())) + { + covered = guarded.count(stripIndexCasts(compare->getOperand(0))) > 0; + } + } + } + + if (!covered) + { + llvm::IRBuilder<> builder(call); + builder.CreateIntrinsic(llvm::Intrinsic::trap, {}); + } + + call->eraseFromParent(); + } + } +} + // the device module, whatever the GPU: the kernels and what they reach, or an error for what cannot run on one llvm::Expected> prepareDeviceModule(llvm::Module &hostModule, const std::set &kernelNames) @@ -1622,7 +1816,11 @@ llvm::Expected> prepareDeviceModule(llvm::Module & // a kernel that waits at gpuBarrier: its array accesses guarded, as it runs past n guardBarrierKernels(*device, kernelNames); - // a write past an array's end grows it on the CPU (the heap): on the GPU it traps + // the other kernels: a write past an array's end is not made, and recorded for the runtime to report + recordKernelFaults(*device, kernelNames); + + // a write past an array's end that is left (not recognized above) grows it on the CPU (the heap): on the GPU + // it traps llvm::SmallVector growCalls; for (auto &function : *device) { @@ -1694,7 +1892,8 @@ llvm::Expected> prepareDeviceModule(llvm::Module & for (auto &global : device->globals()) { - if (!global.isDeclaration()) + // the fault record stays the module's own, for the runtime to find by name + if (!global.isDeclaration() && global.getName() != FAULT_GLOBAL) { global.setLinkage(llvm::GlobalValue::InternalLinkage); } @@ -1747,7 +1946,7 @@ llvm::Expected> prepareDeviceModule(llvm::Module & // a variable of the program is set when it runs (its initializer is the startup code's, which the GPU // does not run): on the GPU it would stay as it was compiled, and reading it as the program sees it // would be wrong, silently. Only constants (literal text, tables) go to the GPU. - if (!global.isConstant() && !global.use_empty()) + if (!global.isConstant() && !global.use_empty() && global.getName() != FAULT_GLOBAL) { return makeError("a kernel reads the program's variable '" + global.getName() + "', which the GPU does not share: pass it to the kernel as an argument"); @@ -1980,6 +2179,13 @@ llvm::Error lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target, un builder.CreateIntrinsic(llvm::Intrinsic::nvvm_barrier_cta_sync_all, {builder.getInt32(0)}); } } + else if (name == FAULT_THREAD_STUB) + { + // the thread's x among all the launch's threads + result = builder.CreateAdd(builder.CreateMul(blockValue(builder, target, BlockValue::Block, 0), + blockValue(builder, target, BlockValue::Size, 0)), + blockValue(builder, target, BlockValue::Thread, 0)); + } else if (name == WARP_LANE_STUB) { result = warpLane(builder, target); @@ -2152,6 +2358,11 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, if (target.amd()) { moveToAmdAddressSpaces(*device); + // the fault record, as HIP's own device variables are: protected, found by name (hipModuleGetGlobal) + if (auto fault = device->getGlobalVariable(FAULT_GLOBAL)) + { + fault->setVisibility(llvm::GlobalValue::ProtectedVisibility); + } // code object v5 (ROCm 5.0 and newer load it), not LLVM's newer default v6, which older ROCm refuses; a // family's (gfx11-generic) needs v6 device->addModuleFlag(llvm::Module::Error, "amdhsa_code_object_version",