Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,19 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i
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.
- A read past an array's end (or below 0) gives 0 on the GPU, and stops the program the same way:

```
tslang gpu: the kernel 'k' read past the end of an array: element 4 of 4 (GPU thread 3)
```

A neighbour's element at the last index (`a[i + 1]`), a field of an element, a typed array's view past its own
length: each is a read of no element of the array, which on a GPU reads its memory past the array, whatever is
there, or stops the driver. `a[i] += v` past the end is said as its read, the first thing it does. The CPU does
not check a read past the end (the same kernel called there reads what is in the memory), and in a kernel that
waits at `gpuBarrier` such a read gives 0, silently, as its threads past `n` read their tiles (below). The
check costs nothing measurable on NVIDIA; on Intel's integrated GPU a matrix * vector kernel, two reads and a
multiply each step, takes 1.65 times as long.
- `gpuLaunch`, `gpuReduce` and `gpuBatch` need the default memory model (`-mm=gc`).

## The GPU's `Math` library
Expand Down
22 changes: 13 additions & 9 deletions tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c
Original file line number Diff line number Diff line change
Expand Up @@ -717,21 +717,24 @@ 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
// ---- a kernel's fault: a write or a read 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.
// On the GPU such a write is not made (there is no growing an array there) and such a read gives 0: 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. A read past the end, which the CPU
// does not check, is an error on the GPU too: it reads no array's element.
typedef struct
{
int32_t flag; // 1: a fault is recorded
int32_t flag; // a fault is recorded: GPU_FAULT_WRITE or GPU_FAULT_READ
int32_t thread; // the GPU thread that made it (its x)
int64_t index; // the element written
int64_t index; // the element written or read
int64_t length; // the array's length
} GpuFault;

#define GPU_FAULT_GLOBAL "__tslang_gpu_fault"
#define GPU_FAULT_WRITE 1
#define GPU_FAULT_READ 2

static struct
{
Expand Down Expand Up @@ -799,8 +802,9 @@ static int gpuFaultReport(GpuDriver *driver, const char *entry)

// 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);
fprintf(stderr, "tslang gpu: %s %s past the end of an array: element %lld of %lld (GPU thread %d)\n",
which, fault.flag == GPU_FAULT_READ ? "read" : "wrote", (long long)fault.index,
(long long)fault.length, fault.thread);
fflush(stderr);
return 1;
}
Expand Down
7 changes: 5 additions & 2 deletions tslang/test/gpu/faults/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
# 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):
Each program here has a kernel write or read past the end of an array, in one way or another, on the GPU. Such a
write is not made, such a read gives 0, 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 <index> of <length> (GPU thread <x>)
tslang gpu: the kernel 'k' read past the end of an array: element <index> of <length> (GPU thread <x>)

The `read*.ts` ones read; `add_assign.ts` (`a[i] += v`) is said as its read, which comes first.

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:
Expand Down
13 changes: 13 additions & 0 deletions tslang/test/gpu/faults/read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// a read past the end (a neighbour's element, at the last index): it gives 0 and is reported, as a write is
@kernel
function k(i: int, a: number[], b: number[]) {
b[i] = a[i] + a[i + 1];
}

function main() {
const a: number[] = [1, 2, 3, 4];
const b: number[] = [0, 0, 0, 0];
print("before");
gpuLaunch(k, 4, a, b);
print("after");
}
13 changes: 13 additions & 0 deletions tslang/test/gpu/faults/read_field.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// a field of an object element read past the end
@kernel
function k(i: int, ps: { x: number, y: number }[], out: number[]) {
out[i] = ps[i + 2].x;
}

function main() {
const ps: { x: number, y: number }[] = [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }];
const out: number[] = [0, 0, 0];
print("before");
gpuLaunch(k, 3, ps, out);
print("after");
}
13 changes: 13 additions & 0 deletions tslang/test/gpu/faults/read_typed_array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// a typed array's view read past its end, inside the buffer: the view's length is the one checked
@kernel
function k(i: int, a: Float32Array, out: Float32Array) {
out[i] = a[i + 1];
}

function main() {
const big = new Float32Array(10);
const out = new Float32Array(5);
print("before");
gpuLaunch(k, 5, big.subarray(0, 5), out);
print("after");
}
81 changes: 72 additions & 9 deletions tslang/tslang/gpu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
Expand Down Expand Up @@ -148,10 +149,15 @@ constexpr int32_t gpuBlockThreads = 256;
// the lanes of an Intel kernel's subgroup (a warp), pinned so that every kernel has the same
#define INTEL_SUBGROUP_SIZE 16
#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:
// a kernel's first write or read past an array's end (recordKernelFaults), which GpuRuntime.c reads after it 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"
// the record's flag: what the fault was (GpuRuntime.c's GPU_FAULT_WRITE and GPU_FAULT_READ)
#define FAULT_WRITE 1
#define FAULT_READ 2
// the zeroes a read past an array's end reads instead (recordKernelFaults): an element of at most this many bytes
#define ZERO_SLOT_BYTES 64
#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
Expand Down Expand Up @@ -1715,7 +1721,8 @@ llvm::Value *stripIndexCasts(llvm::Value *value)
// 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
// reads after the kernel and stops the program with (GpuRuntime.c's gpuFaultReport). A read of an element is
// guarded the same way: past the end it gives 0 and is recorded (FAULT_READ; the CPU does not check one). 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<std::string> &kernelNames)
Expand Down Expand Up @@ -1752,7 +1759,7 @@ void recordKernelFaults(llvm::Module &device, const std::set<std::string> &kerne
auto record = device.getFunction(FAULT_RECORD_FUNCTION);
if (!record)
{
record = llvm::Function::Create(llvm::FunctionType::get(llvm::Type::getVoidTy(context), {i64, i64}, false),
record = llvm::Function::Create(llvm::FunctionType::get(llvm::Type::getVoidTy(context), {i64, i64, i32}, false),
llvm::GlobalValue::InternalLinkage, FAULT_RECORD_FUNCTION, device);
record->addFnAttr(llvm::Attribute::Cold);
record->addFnAttr(llvm::Attribute::NoInline);
Expand All @@ -1761,7 +1768,7 @@ void recordKernelFaults(llvm::Module &device, const std::set<std::string> &kerne
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),
record->getArg(2), llvm::MaybeAlign(4),
llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Monotonic);
builder.CreateCondBr(builder.CreateExtractValue(exchange, 1), write, done);
builder.SetInsertPoint(write);
Expand All @@ -1774,6 +1781,18 @@ void recordKernelFaults(llvm::Module &device, const std::set<std::string> &kerne
builder.CreateRetVoid();
}

// the record writes FAULT_GLOBAL only, never an array's header: said as an alias scope of its own, so that a
// header's data and length are still read once before a loop, not at each access (to LLVM the record's call in
// the loop could write anything)
llvm::MDBuilder metadata(context);
auto faultScope = metadata.createAnonymousAliasScope(metadata.createAnonymousAliasScopeDomain("tslang.gpu.fault"));
auto faultScopes = llvm::MDNode::get(context, {faultScope});
llvm::GlobalVariable *zeroSlot = device.getGlobalVariable("__tslang_gpu_zeroes", true);
auto notFault = [&](llvm::Instruction *access) {
access->setMetadata(llvm::LLVMContext::MD_noalias,
llvm::MDNode::concatenate(access->getMetadata(llvm::LLVMContext::MD_noalias), faultScopes));
};

for (auto function : reachedFrom(kernels))
{
if (function == record || function->getName().starts_with(".array_grow."))
Expand All @@ -1782,13 +1801,18 @@ void recordKernelFaults(llvm::Module &device, const std::set<std::string> &kerne
}

llvm::SmallVector<llvm::Instruction *> writes;
llvm::SmallVector<llvm::LoadInst *> reads;
llvm::SmallVector<llvm::CallInst *> checks;
for (auto &instruction : llvm::instructions(*function))
{
if (llvm::isa<llvm::StoreInst, llvm::AtomicRMWInst, llvm::AtomicCmpXchgInst>(&instruction))
{
writes.push_back(&instruction);
}
else if (auto load = llvm::dyn_cast<llvm::LoadInst>(&instruction))
{
reads.push_back(load);
}
else if (auto call = llvm::dyn_cast<llvm::CallInst>(&instruction))
{
if (auto callee = call->getCalledFunction();
Expand All @@ -1801,8 +1825,11 @@ void recordKernelFaults(llvm::Module &device, const std::set<std::string> &kerne

// the indices whose writes are guarded
llvm::SmallPtrSet<llvm::Value *, 8> guarded;
for (auto access : writes)
llvm::SmallVector<llvm::Instruction *> accesses(writes.begin(), writes.end());
accesses.append(reads.begin(), reads.end());
for (auto access : accesses)
{
auto isRead = llvm::isa<llvm::LoadInst>(access);
auto pointer = llvm::getLoadStorePointerOperand(access);
if (!pointer)
{
Expand All @@ -1820,26 +1847,62 @@ void recordKernelFaults(llvm::Module &device, const std::set<std::string> &kerne
auto [header, data, element] = *matched;
llvm::IRBuilder<> builder(access);
auto length = builder.CreateLoad(i64, builder.CreateStructGEP(headerType, header, 1), "gpu.length");
notFault(length);
if (data)
{
notFault(data);
}
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");
if (isRead && device.getDataLayout().getTypeStoreSize(access->getType()) <= ZERO_SLOT_BYTES)
{
// a read is made always, of the element or past the end of zeroes, and only the record is
// branched to: the data's load, used on the way the loop always goes, is then made once before
// the loop (in a branch around the read it was made at each one: a matrix * vector kernel ran 1.6
// times as long on NVIDIA, 2.1 times on Intel)
if (!zeroSlot)
{
auto slotType = llvm::ArrayType::get(llvm::Type::getInt8Ty(context), ZERO_SLOT_BYTES);
zeroSlot = new llvm::GlobalVariable(device, slotType, true, llvm::GlobalValue::InternalLinkage,
llvm::ConstantAggregateZero::get(slotType), "__tslang_gpu_zeroes");
zeroSlot->setAlignment(llvm::Align(16));
}

auto read = llvm::cast<llvm::LoadInst>(access);
read->setOperand(read->getPointerOperandIndex(),
builder.CreateSelect(inside, pointer, zeroSlot, "gpu.read.from"));
auto recordTerminator =
llvm::SplitBlockAndInsertIfThen(builder.CreateNot(inside), std::next(read->getIterator()), false);
llvm::IRBuilder<> faultBuilder(recordTerminator);
faultBuilder.CreateCall(record, {index, length, faultBuilder.getInt32(FAULT_READ)})
->setMetadata(llvm::LLVMContext::MD_alias_scope, faultScopes);
continue;
}

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});
auto recorded =
faultBuilder.CreateCall(record, {index, length, builder.getInt32(isRead ? FAULT_READ : FAULT_WRITE)});
recorded->setMetadata(llvm::LLVMContext::MD_alias_scope, faultScopes);
if (!access->getType()->isVoidTy())
{
// what the skipped Atomics gives: 0
auto phi = llvm::PHINode::Create(access->getType(), 2, "gpu.written", tail->begin());
// what the skipped read or Atomics gives: 0
auto phi = llvm::PHINode::Create(access->getType(), 2, isRead ? "gpu.read" : "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()));
if (!isRead)
{
guarded.insert(stripIndexCasts(*element->idx_begin()));
}
}

// the compiler's check before a write: `br (index >= length), check, write`
Expand Down
Loading