diff --git a/crates/stela-driver-gpu/src/compiler/air_metadata.c b/crates/stela-driver-gpu/src/compiler/air_metadata.c index cc0ea818e1..72de31b3f1 100644 --- a/crates/stela-driver-gpu/src/compiler/air_metadata.c +++ b/crates/stela-driver-gpu/src/compiler/air_metadata.c @@ -2662,6 +2662,101 @@ entry_stage(struct stela_air_metadata *m, const char *entry, unsigned *stage) return found || fail(m, STELA_AIR_ARGUMENT, "entry is not a listed AIR function"); } +/* Whether `name` is `stem`, or with `suffixed` `stem.` and more. */ +static bool +stitched_read(const char *name, size_t bytes, const char *stem, bool suffixed) +{ + size_t length = strlen(stem); + return suffixed ? bytes > length + 1 && !memcmp(name, stem, length) && name[length] == '.' : + bytes == length && !memcmp(name, stem, length); +} + +/* Appends to the *count arguments of args, which hold AIR_MAX_ARGUMENTS, the + * resources fn binds through air_stitch.c's reads, as a stitched kernel + * does: each binding once, with the access all its reads take. */ +static bool +stitched_arguments(struct stela_air_metadata *m, LLVMValueRef fn, + struct stela_air_argument_info *args, unsigned *count) +{ + const char *texture_metadata = STELA_AIR_STITCH_TEXTURE_METADATA; + unsigned texture_kind = LLVMGetMDKindIDInContext(LLVMGetModuleContext(m->module), + texture_metadata, + (unsigned)strlen(texture_metadata)); + for (LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(fn); block; + block = LLVMGetNextBasicBlock(block)) { + for (LLVMValueRef inst = LLVMGetFirstInstruction(block); inst; + inst = LLVMGetNextInstruction(inst)) { + LLVMValueRef callee = LLVMIsACallInst(inst) ? LLVMGetCalledValue(inst) : NULL; + size_t bytes = 0; + const char *name = + callee && LLVMIsAFunction(callee) ? LLVMGetValueName2(callee, &bytes) : ""; + bool buffer = stitched_read(name, bytes, STELA_AIR_STITCH_BUFFER_ADDRESS_NAME, true); + bool texture = stitched_read(name, bytes, STELA_AIR_STITCH_TEXTURE_NAME, false); + bool sampler = stitched_read(name, bytes, STELA_AIR_STITCH_SAMPLER_NAME, false); + bool threadgroup = stitched_read(name, bytes, STELA_AIR_STITCH_THREADGROUP_NAME, false); + if (!buffer && !texture && !sampler && !threadgroup) + continue; + LLVMValueRef index = LLVMGetNumArgOperands(inst) == 1 ? LLVMGetOperand(inst, 0) : NULL; + if (!index || !LLVMIsAConstantInt(index) || + LLVMGetTypeKind(LLVMTypeOf(inst)) != LLVMPointerTypeKind) + return fail(m, STELA_AIR_INPUT, "a stitched resource of an unknown form"); + unsigned bound = (unsigned)LLVMConstIntGetZExtValue(index); + unsigned space = LLVMGetPointerAddressSpace(LLVMTypeOf(inst)); + /* Metal names none of them. */ + struct stela_air_argument_info read = { + .kind = texture ? 3 : sampler ? 4 : 1, .name = "", .type_name = "", .used = true}; + if (texture) { + /* A texture no texture call takes is never read. */ + LLVMValueRef described = LLVMGetMetadata(inst, texture_kind); + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned field_count; + if (!described) + continue; + if (!stela_air_md_node(m, described, fields, &field_count) || field_count != 4) + return fail(m, STELA_AIR_METADATA, "a stitched texture's description"); + for (unsigned i = 0; i < field_count; i++) { + if (!LLVMIsAConstantInt(fields[i])) + return fail(m, STELA_AIR_METADATA, "a stitched texture's description"); + } + read.texture = (struct stela_air_texture){ + .argument = bound, .index = bound, + .type = (enum stela_air_texture_type)LLVMConstIntGetZExtValue(fields[0]), + .access = (enum stela_air_texture_access)LLVMConstIntGetZExtValue(fields[1]), + .primitive = (enum stela_air_primitive)LLVMConstIntGetZExtValue(fields[2]), + .depth = LLVMConstIntGetZExtValue(fields[3]) != 0}; + } else if (sampler) { + read.sampler = (struct stela_air_sampler){.argument = bound, .index = bound}; + } else { + read.buffer = (struct stela_air_buffer){ + .argument = bound, .index = bound, .address_space = threadgroup ? 3 : space, + .access = space == 2 ? STELA_AIR_READ : STELA_AIR_READ_WRITE}; + } + bool held = false; + for (unsigned i = 0; !held && i < *count; i++) { + struct stela_air_argument_info *earlier = &args[i]; + if (earlier->kind != read.kind) + continue; + if (texture && earlier->texture.index == bound) { + earlier->texture.access |= read.texture.access; + held = true; + } else if (sampler && earlier->sampler.index == bound) { + held = true; + } else if (!texture && !sampler && earlier->buffer.index == bound && + (earlier->buffer.address_space == 3) == threadgroup) { + earlier->buffer.access |= read.buffer.access; + held = true; + } + } + if (held) + continue; + if (*count == AIR_MAX_ARGUMENTS) + return fail(m, STELA_AIR_LIMIT, "a stitched kernel's resources exceed its arguments"); + args[(*count)++] = read; + } + } + return true; +} + static bool inspect(const void *bitcode, size_t size, const struct stela_air_constants *constants, unsigned max_entries, @@ -2816,9 +2911,12 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons .absent = arg->absent, .layout = (const struct stela_air_layout *)arg->layout, }; } + unsigned argument_count = entries[i].kernel.count; + if (!stitched_arguments(&m, entries[i].fn, args, &argument_count)) + goto done; struct stela_air_entry entry = { .name = entries[i].name, .name_bytes = entries[i].name_bytes, - .argument_count = entries[i].kernel.count, .arguments = args, + .argument_count = argument_count, .arguments = args, .reflection_complete = complete_reflection(&m, entries[i].fn, &entries[i].kernel), .max_threads = entries[i].kernel.max_threads, }; diff --git a/crates/stela-driver-gpu/src/compiler/air_metadata.h b/crates/stela-driver-gpu/src/compiler/air_metadata.h index 3316ab6e25..94fe658063 100644 --- a/crates/stela-driver-gpu/src/compiler/air_metadata.h +++ b/crates/stela-driver-gpu/src/compiler/air_metadata.h @@ -418,15 +418,15 @@ enum stela_air_stitch_builtin { STELA_AIR_STITCH_THREAD_POSITION_IN_GRID = 1, STELA_AIR_STITCH_THREAD_POSITION_IN_THREADGROUP = 2, }; -/* The function a stitched function calls for a builtin: it takes nothing and - * returns the builtin as the type of the parameter it feeds, which the kernel - * the stitched function inlines into supplies. */ +/* The function a stitched kernel calls for a builtin: it takes nothing and + * returns the builtin as the type of the parameter it feeds, which the + * kernel's translation supplies. */ #define STELA_AIR_STITCH_THREAD_POSITION_IN_GRID_NAME "stela.thread_position_in_grid" #define STELA_AIR_STITCH_THREAD_POSITION_IN_THREADGROUP_NAME "stela.thread_position_in_threadgroup" -/* The functions a stitched function calls for the address of the buffer the - * function it inlines into binds at a constant index, which that function's - * translation answers: `name.pN`, ptr addrspace(N) (i32 index) for device (1) - * or constant (2) memory. */ +/* The functions a stitched kernel calls for the address of the buffer it + * binds at a constant index, which the kernel's translation answers: + * `name.pN`, ptr addrspace(N) (i32 index) for device (1) or constant (2) + * memory. */ #define STELA_AIR_STITCH_BUFFER_ADDRESS_NAME "stela.buffer_address" /* Likewise the texture, sampler and threadgroup memory bound at a constant * index: ptr addrspace(1), ptr addrspace(2) and ptr addrspace(3), each @@ -434,6 +434,13 @@ enum stela_air_stitch_builtin { #define STELA_AIR_STITCH_TEXTURE_NAME "stela.texture" #define STELA_AIR_STITCH_SAMPLER_NAME "stela.sampler" #define STELA_AIR_STITCH_THREADGROUP_NAME "stela.threadgroup" +/* A texture read's metadata, of this kind, describes the texture as the + * texture calls of the parameters it feeds do: !{i32 type, i32 access, + * i32 primitive, i1 depth}, of enum stela_air_texture_type, + * stela_air_texture_access and stela_air_primitive. Without it no texture + * call takes the texture. A stitched kernel's reflection lists the + * resources its reads bind. */ +#define STELA_AIR_STITCH_TEXTURE_METADATA "stela.texture" /* A node of a stitched function: an input, argument `input` of the function; * a builtin, `input` of enum stela_air_stitch_builtin; a buffer address, * `offset` bytes into the buffer bound at `input`, or with `dereference` the @@ -449,11 +456,15 @@ struct stela_air_stitch_node { bool dereference; uint64_t offset; }; +/* A graph is a visible function's, whose inputs are its arguments, or with + * `kernel` a kernel's, which takes and returns nothing and whose builtins and + * bound resources are the only nodes either kind does not share. */ struct stela_air_stitch_graph { const char *name; const struct stela_air_stitch_node *nodes; uint32_t node_count; uint32_t output; /* The node whose result it returns. */ + bool kernel; }; /* Calls visit with the bitcode of a module of the graphs: air_stitch.c. */ typedef void (*stela_air_visit_bytes)(void *, const void *, size_t); diff --git a/crates/stela-driver-gpu/src/compiler/air_stitch.c b/crates/stela-driver-gpu/src/compiler/air_stitch.c index 341c3ec5f1..692f302f19 100644 --- a/crates/stela-driver-gpu/src/compiler/air_stitch.c +++ b/crates/stela-driver-gpu/src/compiler/air_stitch.c @@ -1,17 +1,19 @@ /* SPDX-License-Identifier: MIT */ /* Stitched functions: MTLFunctionStitchingGraph as a module of visible - * functions, each of whose body calls its nodes' functions in order. The - * functions it calls stay declarations, so a pipeline that links a stitched - * function links their modules too, with their own function constant values. + * functions and kernels, each of whose body calls its nodes' functions in + * order. The functions it calls stay declarations, so a pipeline of or + * linking a stitched function links their modules too, with their own + * function constant values. * * Nodes follow what they use, so calling each once in order keeps every * dependency, control or data. An input becomes an argument of the type and - * metadata of the parameter it feeds, a builtin or buffer address a call of - * the Stela function that the translation of the kernel it inlines into - * answers, an early return a branch to a return, and a stitched function - * returns what its output node's function returns. */ + * metadata of the parameter it feeds, a kernel's builtin or bound resource a + * call of the Stela function that the kernel's translation answers, an early + * return a branch to a return, and a stitched function returns what its + * output node's function returns. */ #define STELA_AIR_METADATA_INTERNAL #include "air_metadata.h" +#include "air_texture.h" #include "llvm-c/Analysis.h" #include "llvm-c/BitReader.h" #include "llvm-c/BitWriter.h" @@ -144,11 +146,12 @@ buffer_address(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleR } /* The texture, sampler or threadgroup memory node's value, read from the - * binding the function the stitched function inlines into has at its index, - * as the `type` of the parameters it feeds. */ + * stitched kernel's binding at its index, as the `type` of the parameters it + * feeds. */ static LLVMValueRef bound_resource(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef out, - LLVMBuilderRef builder, const struct stela_air_stitch_node *node, LLVMTypeRef type) + LLVMBuilderRef builder, const struct stela_air_stitch_node *node, LLVMTypeRef type, + const struct stela_air_texture *texture) { static const struct { uint32_t function; @@ -175,7 +178,33 @@ bound_resource(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleR if (!read) read = LLVMAddFunction(out, kinds[kind].name, LLVMFunctionType(type, &index_type, 1, false)); LLVMValueRef index = LLVMConstInt(index_type, node->input, false); - return LLVMBuildCall2(builder, LLVMGlobalGetValueType(read), read, &index, 1, ""); + LLVMValueRef value = LLVMBuildCall2(builder, LLVMGlobalGetValueType(read), read, &index, 1, ""); + if (node->function == STELA_AIR_STITCH_TEXTURE && texture->type) { + LLVMTypeRef word = LLVMInt32TypeInContext(context); + LLVMValueRef fields[] = { + LLVMConstInt(word, texture->type, false), LLVMConstInt(word, texture->access, false), + LLVMConstInt(word, texture->primitive, false), + LLVMConstInt(LLVMInt1TypeInContext(context), texture->depth, false), + }; + const char *kind = STELA_AIR_STITCH_TEXTURE_METADATA; + LLVMSetMetadata(value, LLVMGetMDKindIDInContext(context, kind, (unsigned)strlen(kind)), + LLVMMDNodeInContext(context, fields, ARRAY_SIZE(fields))); + } + return value; +} + +/* Merges into *texture what the texture calls that take `parameter` say of + * it; a parameter its function passes on says nothing here. */ +static void +describe_texture(LLVMValueRef parameter, struct stela_air_texture *texture) +{ + for (LLVMUseRef use = LLVMGetFirstUse(parameter); use; use = LLVMGetNextUse(use)) { + LLVMValueRef user = LLVMGetUser(use); + struct stela_air_texture merged = *texture; + if (LLVMIsACallInst(user) && LLVMGetOperand(user, 0) == parameter && + stela_air_texture_use(user, &merged)) + *texture = merged; + } } /* Node `index` of graph if it is a call before node `before`. */ @@ -210,13 +239,33 @@ static bool stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef out, const struct source *sources, const struct stela_air_stitch_graph *graph) { + /* As Metal's, a kernel's graph takes no inputs and returns nothing, and + * only it reads builtins and bindings. */ + for (unsigned i = 0; i < graph->node_count; i++) { + uint32_t kind = graph->nodes[i].function; + bool bound = kind == STELA_AIR_STITCH_BUILTIN || kind == STELA_AIR_STITCH_BUFFER_ADDRESS || + kind == STELA_AIR_STITCH_TEXTURE || kind == STELA_AIR_STITCH_SAMPLER || + kind == STELA_AIR_STITCH_THREADGROUP; + if (graph->kernel && kind == STELA_AIR_STITCH_INPUT) + return fail(m, STELA_AIR_INPUT, "a stitched kernel takes an input"); + if (!graph->kernel && bound) + return fail(m, STELA_AIR_INPUT, "a stitched visible function reads a builtin or binding"); + } + if (graph->kernel && graph->output != STELA_AIR_STITCH_NO_OUTPUT) + return fail(m, STELA_AIR_INPUT, "a stitched kernel returns a value"); LLVMTypeRef types[AIR_MAX_METADATA_OPERANDS] = {0}; LLVMValueRef inputs[AIR_MAX_METADATA_OPERANDS] = {0}; unsigned parameters = 0; - /* Each builtin or buffer address node's type, the parameters' it feeds. */ + /* Each builtin or buffer address node's type, the parameters' it feeds, + * and each texture node's texture, as their texture calls take it: zero, + * sampled and of no known type until one does. */ LLVMTypeRef *builtins = calloc(graph->node_count, sizeof(*builtins)); - if (!builtins) + struct stela_air_texture *textures = calloc(graph->node_count, sizeof(*textures)); + if (!builtins || !textures) { + free(builtins); + free(textures); return fail(m, STELA_AIR_ALLOCATION, "stitched nodes"); + } for (unsigned i = 0; i < graph->node_count; i++) { const struct stela_air_stitch_node *node = &graph->nodes[i]; if (node->function == STELA_AIR_STITCH_EARLY_RETURN) { @@ -235,6 +284,7 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef "a stitched early return of no earlier call of the output's type" : NULL; if (refusal) { free(builtins); + free(textures); return fail(m, STELA_AIR_INPUT, refusal); } continue; @@ -244,6 +294,7 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef const struct source *source = &sources[node->function]; if (node->argument_count != LLVMCountParams(source->function)) { free(builtins); + free(textures); return fail(m, STELA_AIR_INPUT, "a stitched call has the wrong number of arguments"); } for (unsigned j = 0; j < node->argument_count; j++) { @@ -251,6 +302,7 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef LLVMTypeRef type = LLVMTypeOf(LLVMGetParam(source->function, j)); if (argument->function == STELA_AIR_STITCH_EARLY_RETURN) { free(builtins); + free(textures); return fail(m, STELA_AIR_INPUT, "a stitched early return is a call's argument"); } if (argument->function == STELA_AIR_STITCH_BUILTIN || @@ -261,9 +313,12 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef LLVMTypeRef *builtin = &builtins[node->arguments[j]]; if (*builtin && *builtin != type) { free(builtins); + free(textures); return fail(m, STELA_AIR_INPUT, "a stitched builtin or resource of two types"); } *builtin = type; + if (argument->function == STELA_AIR_STITCH_TEXTURE) + describe_texture(LLVMGetParam(source->function, j), &textures[node->arguments[j]]); continue; } if (argument->function != STELA_AIR_STITCH_INPUT) @@ -271,6 +326,7 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef unsigned index = argument->input; if (index >= ARRAY_SIZE(types) || (types[index] && types[index] != type)) { free(builtins); + free(textures); return fail(m, STELA_AIR_INPUT, index >= ARRAY_SIZE(types) ? "a stitched function's argument index" : "a stitched argument of two types"); @@ -295,8 +351,6 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef graph->output == STELA_AIR_STITCH_NO_OUTPUT ? NULL : &graph->nodes[graph->output]; if (!refusal && output && output->function == STELA_AIR_STITCH_INPUT) refusal = "a stitched function outputs an input"; - if (!refusal && output && output->function == STELA_AIR_STITCH_BUILTIN) - refusal = "a stitched function outputs a builtin"; if (!refusal && output && output->function >= STELA_AIR_STITCH_CALLS) refusal = "a stitched function outputs what is no call"; if (!refusal && LLVMGetNamedFunction(out, graph->name)) @@ -306,6 +360,7 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef refusal = "stitched nodes", refused = STELA_AIR_ALLOCATION; if (refusal) { free(builtins); + free(textures); return fail(m, refused, refusal); } LLVMTypeRef result = LLVMVoidTypeInContext(context); @@ -352,7 +407,7 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef node->function == STELA_AIR_STITCH_THREADGROUP) { if (!builtins[i]) continue; - values[i] = bound_resource(m, context, out, builder, node, builtins[i]); + values[i] = bound_resource(m, context, out, builder, node, builtins[i], &textures[i]); stitched = values[i] != NULL; continue; } @@ -392,13 +447,14 @@ stitch_graph(struct stela_air_metadata *m, LLVMContextRef context, LLVMModuleRef LLVMDisposeBuilder(builder); free(values); free(builtins); + free(textures); if (!stitched) return false; LLVMValueRef empty = LLVMMDNodeInContext(context, NULL, 0); LLVMValueRef entry[] = {function, output ? sources[output->function].outputs : empty, LLVMMDNodeInContext(context, arguments, parameters)}; - LLVMAddNamedMetadataOperand(out, "air.visible", + LLVMAddNamedMetadataOperand(out, graph->kernel ? "air.kernel" : "air.visible", LLVMMDNodeInContext(context, entry, ARRAY_SIZE(entry))); return true; } diff --git a/crates/stela-driver-gpu/src/compiler/air_to_nir.c b/crates/stela-driver-gpu/src/compiler/air_to_nir.c index f8cb2c5498..375d7d6224 100644 --- a/crates/stela-driver-gpu/src/compiler/air_to_nir.c +++ b/crates/stela-driver-gpu/src/compiler/air_to_nir.c @@ -614,9 +614,9 @@ named_after(const char *name, size_t name_length, const char *stem) return name_length > length + 1 && !memcmp(name, stem, length) && name[length] == '.'; } -/* A stitched function's read of a builtin of the function it inlines into, - * as air_stitch.c declares it: a call of `name.TYPE` that returns the builtin - * as an integer scalar or vector of up to three lanes. */ +/* A stitched kernel's read of its builtin, as air_stitch.c declares it: a + * call of `name.TYPE` that returns the builtin as an integer scalar or vector + * of up to three lanes. */ static bool stitched_builtin_call(struct translator *t, LLVMValueRef call, LLVMValueRef callee, const char *name, size_t name_length, bool *lowered) @@ -720,8 +720,8 @@ stitched_texture(struct translator *t, LLVMValueRef call, unsigned index, bool t return put_resource(t, call, &described, NULL); } -/* The resources the stitched functions inlined into fn read: calls on a - * constant index, bound in the prelude as arguments are. */ +/* The resources stitched kernel fn reads: calls on a constant index, bound + * in the prelude as arguments are. */ static bool stitched_resources(struct translator *t, LLVMValueRef fn) { diff --git a/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c b/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c index 30e2b2b37e..153601d25c 100644 --- a/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c +++ b/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c @@ -1956,45 +1956,82 @@ loops_return_without_return_jumps(void) stela_metal_release(shader); } -static const char *positioning_kernel = - "declare i32 @positioned.MTL_VISIBLE_FN_REF() section \"air.externally_defined\"\n" - "define void @positions(ptr addrspace(1) %data) {\n" - "%v = call i32 @positioned.MTL_VISIBLE_FN_REF()\n" +/* kept(data, v) and its float and float4 forms give a stitched kernel's + * values somewhere to go. */ +static const char *keeps = + "define void @kept(ptr addrspace(1) %data, i32 %v) {\n" "store i32 %v, ptr addrspace(1) %data, align 4\nret void\n}\n" - "!air.kernel = !{!2}\n!air.visible_function_references = !{!5}\n" - "!2 = !{ptr @positions, !3, !4}\n!3 = !{}\n!4 = !{!40}\n" - "!5 = !{!\"air.visible_function_reference\", ptr @positioned.MTL_VISIBLE_FN_REF," - " !\"positioned\"}\n" - "!40 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\"," - " !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\"," - " i32 4, !\"air.arg_type_name\", !\"int\", !\"air.arg_name\", !\"data\"}\n"; + "define void @kept_float(ptr addrspace(1) %data, float %v) {\n" + "store float %v, ptr addrspace(1) %data, align 4\nret void\n}\n" + "define void @kept_float4(ptr addrspace(1) %data, <4 x float> %v) {\n" + "store <4 x float> %v, ptr addrspace(1) %data, align 16\nret void\n}\n" + "!air.visible = !{!1, !4, !5}\n" + "!1 = !{ptr @kept, !2, !3}\n!2 = !{}\n!3 = !{!30, !31}\n" + "!4 = !{ptr @kept_float, !2, !3}\n!5 = !{ptr @kept_float4, !2, !3}\n" + "!30 = !{i32 0, !\"air.visible_input\", !\"air.arg_type_name\", !\"int*\"," + " !\"air.arg_name\", !\"data\"}\n" + "!31 = !{i32 1, !\"air.visible_input\", !\"air.arg_type_name\", !\"int\"," + " !\"air.arg_name\", !\"v\"}\n"; -/* positioned() = doubled(thread_position_in_grid) reads the grid position of - * the kernel it inlines into, as the type of the parameter it feeds. */ -static void -stitched_builtins_read_their_kernels_builtins(void) +/* Stitched kernel `entry` of stitched, linked with the module of source and + * keeps', which its calls name. */ +static nir_shader * +compile_stitched(LLVMMemoryBufferRef stitched, const char *entry, LLVMMemoryBufferRef source, + LLVMMemoryBufferRef kept, const struct stela_metal_threadgroup_length *lengths, + unsigned length_count, struct stela_air_error *error) { - LLVMMemoryBufferRef source = bitcode(calls); - const struct stela_air_stitch_source sources[] = { - {LLVMGetBufferStart(source), LLVMGetBufferSize(source), "doubled"}, - }; - const uint32_t position = 0; - const struct stela_air_stitch_node nodes[] = { - {.function = STELA_AIR_STITCH_BUILTIN, .input = STELA_AIR_STITCH_THREAD_POSITION_IN_GRID}, - {.function = 0, .arguments = &position, .argument_count = 1}, - }; - const struct stela_air_stitch_graph graph = {"positioned", nodes, 2, 1}; - struct stela_air_error error; - LLVMMemoryBufferRef stitched = NULL; - assert(stela_metal_stitch(sources, 1, &graph, 1, keep_stitched, &stitched, &error)); const struct stela_air_module modules[] = { - {LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched)}, {LLVMGetBufferStart(source), LLVMGetBufferSize(source)}, + {LLVMGetBufferStart(kept), LLVMGetBufferSize(kept)}, }; const struct stela_metal_specialization specialization = { .workgroup_size = {64, 1, 1}, .modules = modules, .module_count = 2, + .threadgroup_length_count = length_count, .threadgroup_lengths = lengths, }; - nir_shader *shader = compile(positioning_kernel, "positions", &specialization, &error); + nir_shader *shader = stela_metal_compile(LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched), + entry, &target, &specialization, error); + if (!shader) + fprintf(stderr, "%s: %u %s\n", entry, error->kind, error->detail); + return shader; +} + +static bool +kernel_positioned(void *data, const char *name, size_t name_bytes, + enum stela_metal_function_stage stage) +{ + assert(name_bytes == 10 && !memcmp(name, "positioned", 10) && stage == STELA_METAL_KERNEL); + (*(unsigned *)data)++; + return true; +} + +/* kernel positioned() { kept(buffer 0, doubled(thread_position_in_grid)); } + * reads its own builtins, as the type of the parameter each feeds; only a + * kernel's graph reads builtins, and it takes and returns nothing. */ +static void +stitched_kernels_read_their_builtins(void) +{ + LLVMMemoryBufferRef source = bitcode(calls), kept = bitcode(keeps); + const struct stela_air_stitch_source sources[] = { + {LLVMGetBufferStart(source), LLVMGetBufferSize(source), "doubled"}, + {LLVMGetBufferStart(kept), LLVMGetBufferSize(kept), "kept"}, + }; + const uint32_t position = 0, stored[] = {2, 1}; + const struct stela_air_stitch_node nodes[] = { + {.function = STELA_AIR_STITCH_BUILTIN, .input = STELA_AIR_STITCH_THREAD_POSITION_IN_GRID}, + {.function = 0, .arguments = &position, .argument_count = 1}, + {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 0}, + {.function = 1, .arguments = stored, .argument_count = 2}, + }; + const struct stela_air_stitch_graph graph = {"positioned", nodes, 4, STELA_AIR_STITCH_NO_OUTPUT, + true}; + struct stela_air_error error; + LLVMMemoryBufferRef stitched = NULL; + assert(stela_metal_stitch(sources, 2, &graph, 1, keep_stitched, &stitched, &error)); + unsigned listed = 0; + assert(stela_metal_functions(LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched), + kernel_positioned, &listed, &error)); + assert(listed == 1); + nir_shader *shader = compile_stitched(stitched, "positioned", source, kept, NULL, 0, &error); assert(shader && count_intrinsic(shader, nir_intrinsic_load_workgroup_id) >= 1); stela_metal_release(shader); LLVMDisposeMemoryBuffer(stitched); @@ -2002,77 +2039,87 @@ stitched_builtins_read_their_kernels_builtins(void) /* The position in the threadgroup is the local one. */ const struct stela_air_stitch_node local[] = { {.function = STELA_AIR_STITCH_BUILTIN, .input = STELA_AIR_STITCH_THREAD_POSITION_IN_THREADGROUP}, - nodes[1], + nodes[1], nodes[2], nodes[3], }; - const struct stela_air_stitch_graph locally = {"positioned", local, 2, 1}; - assert(stela_metal_stitch(sources, 1, &locally, 1, keep_stitched, &stitched, &error)); - const struct stela_air_module local_modules[] = { - {LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched)}, modules[1], - }; - const struct stela_metal_specialization local_specialization = { - .workgroup_size = {64, 1, 1}, .modules = local_modules, .module_count = 2, - }; - shader = compile(positioning_kernel, "positions", &local_specialization, &error); + const struct stela_air_stitch_graph locally = {"positioned", local, 4, + STELA_AIR_STITCH_NO_OUTPUT, true}; + assert(stela_metal_stitch(sources, 2, &locally, 1, keep_stitched, &stitched, &error)); + shader = compile_stitched(stitched, "positioned", source, kept, NULL, 0, &error); assert(shader && count_intrinsic(shader, nir_intrinsic_load_local_invocation_id) >= 1); stela_metal_release(shader); LLVMDisposeMemoryBuffer(stitched); - /* A builtin is no output, and only known builtins stitch. */ - const struct stela_air_stitch_graph outputting = {"outputting", nodes, 1, 0}; - assert(!stela_metal_stitch(sources, 1, &outputting, 1, keep_stitched, &stitched, &error) && - strstr(error.detail, "outputs a builtin")); - const struct stela_air_stitch_node unknown[] = { - {.function = STELA_AIR_STITCH_BUILTIN, .input = 0}, - {.function = 0, .arguments = &position, .argument_count = 1}, + /* As Metal's: a visible function's graph reads no builtin, and a + * kernel's takes no input and returns nothing. */ + const struct stela_air_stitch_graph visible = {"visible", nodes, 4, STELA_AIR_STITCH_NO_OUTPUT}; + assert(!stela_metal_stitch(sources, 2, &visible, 1, keep_stitched, &stitched, &error) && + strstr(error.detail, "reads a builtin or binding")); + const struct stela_air_stitch_graph returning = {"returning", nodes, 2, 1, true}; + assert(!stela_metal_stitch(sources, 2, &returning, 1, keep_stitched, &stitched, &error) && + strstr(error.detail, "returns a value")); + const struct stela_air_stitch_node input[] = { + {.function = STELA_AIR_STITCH_INPUT}, nodes[1], }; - const struct stela_air_stitch_graph unknowing = {"unknowing", unknown, 2, 1}; - assert(!stela_metal_stitch(sources, 1, &unknowing, 1, keep_stitched, &stitched, &error) && + const struct stela_air_stitch_graph taking = {"taking", input, 2, STELA_AIR_STITCH_NO_OUTPUT, + true}; + assert(!stela_metal_stitch(sources, 2, &taking, 1, keep_stitched, &stitched, &error) && + strstr(error.detail, "takes an input")); + /* Only known builtins stitch. */ + const struct stela_air_stitch_node unknown[] = { + {.function = STELA_AIR_STITCH_BUILTIN, .input = 0}, nodes[1], nodes[2], nodes[3], + }; + const struct stela_air_stitch_graph unknowing = {"unknowing", unknown, 4, + STELA_AIR_STITCH_NO_OUTPUT, true}; + assert(!stela_metal_stitch(sources, 2, &unknowing, 1, keep_stitched, &stitched, &error) && strstr(error.detail, "does not know")); + LLVMDisposeMemoryBuffer(kept); LLVMDisposeMemoryBuffer(source); } -/* positioned() = doubled(the int 8 bytes into buffer 1) reads the buffer - * the kernel it inlines into binds there, which no argument of it declares. */ +/* kernel positioned() { kept(buffer 0, doubled(the int 8 bytes into buffer + * 1)); } reads the buffers it binds there, which its reflection lists. */ static void stitched_buffer_addresses_read_their_kernels_buffers(void) { - LLVMMemoryBufferRef source = bitcode(calls); + LLVMMemoryBufferRef source = bitcode(calls), kept = bitcode(keeps); const struct stela_air_stitch_source sources[] = { {LLVMGetBufferStart(source), LLVMGetBufferSize(source), "doubled"}, + {LLVMGetBufferStart(kept), LLVMGetBufferSize(kept), "kept"}, }; - const uint32_t address = 0; + const uint32_t address = 0, stored[] = {2, 1}; const struct stela_air_stitch_node nodes[] = { {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 1, .offset = 8, .dereference = true}, {.function = 0, .arguments = &address, .argument_count = 1}, + {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 0}, + {.function = 1, .arguments = stored, .argument_count = 2}, }; - const struct stela_air_stitch_graph graph = {"positioned", nodes, 2, 1}; + const struct stela_air_stitch_graph graph = {"positioned", nodes, 4, STELA_AIR_STITCH_NO_OUTPUT, + true}; struct stela_air_error error; LLVMMemoryBufferRef stitched = NULL; - assert(stela_metal_stitch(sources, 1, &graph, 1, keep_stitched, &stitched, &error)); - const struct stela_air_module modules[] = { - {LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched)}, - {LLVMGetBufferStart(source), LLVMGetBufferSize(source)}, - }; - const struct stela_metal_specialization specialization = { - .workgroup_size = {64, 1, 1}, .modules = modules, .module_count = 2, - }; - nir_shader *shader = compile(positioning_kernel, "positions", &specialization, &error); + assert(stela_metal_stitch(sources, 2, &graph, 1, keep_stitched, &stitched, &error)); + struct stela_metal_reflection reflection; + assert(stela_metal_reflect(LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched), + "positioned", NULL, 0, &reflection, &error)); + assert(reflection.stage == STELA_METAL_KERNEL && reflection.buffer_count == 2); + assert(reflection.buffers[0].index == 1 && reflection.buffers[0].access == STELA_METAL_ACCESS_READ); + assert(reflection.buffers[1].index == 0 && + reflection.buffers[1].access == (STELA_METAL_ACCESS_READ | STELA_METAL_ACCESS_WRITE)); + nir_shader *shader = compile_stitched(stitched, "positioned", source, kept, NULL, 0, &error); /* Both buffers' addresses from the table, and the int. */ assert(shader && count_intrinsic(shader, nir_intrinsic_load_global) == 3); stela_metal_release(shader); LLVMDisposeMemoryBuffer(stitched); - /* An int parameter takes no address, and an address is no output. */ + /* An int parameter takes no address. */ const struct stela_air_stitch_node addressing[] = { - {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 1}, - {.function = 0, .arguments = &address, .argument_count = 1}, + {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 1}, nodes[1], nodes[2], nodes[3], }; - const struct stela_air_stitch_graph pointing = {"pointing", addressing, 2, 1}; - assert(!stela_metal_stitch(sources, 1, &pointing, 1, keep_stitched, &stitched, &error) && + const struct stela_air_stitch_graph pointing = {"pointing", addressing, 4, + STELA_AIR_STITCH_NO_OUTPUT, true}; + assert(!stela_metal_stitch(sources, 2, &pointing, 1, keep_stitched, &stitched, &error) && strstr(error.detail, "no buffer pointer")); - const struct stela_air_stitch_graph outputting = {"outputting", nodes, 1, 0}; - assert(!stela_metal_stitch(sources, 1, &outputting, 1, keep_stitched, &stitched, &error) && - strstr(error.detail, "outputs what is no call")); + LLVMDisposeMemoryBuffer(kept); LLVMDisposeMemoryBuffer(source); } @@ -2195,45 +2242,40 @@ static const char *samples = "!76 = !{i32 1, !\"air.visible_input\", !\"air.arg_type_name\", !\"sampler\"," " !\"air.arg_name\", !\"s\"}\n"; -static const char *sampling_kernel = - "declare <4 x float> @bound.MTL_VISIBLE_FN_REF() section \"air.externally_defined\"\n" - "define void @samples(ptr addrspace(1) %data) {\n" - "%v = call <4 x float> @bound.MTL_VISIBLE_FN_REF()\n" - "store <4 x float> %v, ptr addrspace(1) %data, align 16\nret void\n}\n" - "!air.kernel = !{!2}\n!air.visible_function_references = !{!5}\n" - "!2 = !{ptr @samples, !3, !4}\n!3 = !{}\n!4 = !{!40}\n" - "!5 = !{!\"air.visible_function_reference\", ptr @bound.MTL_VISIBLE_FN_REF, !\"bound\"}\n" - "!40 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\"," - " !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\"," - " i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"data\"}\n"; - -/* bound() = sampled(texture 3, sampler 1) samples what the kernel it inlines - * into binds there, the texture's type as the sample call names it. */ +/* kernel bound() { kept_float4(buffer 0, sampled(texture 3, sampler 1)); } + * samples what it binds there, the texture's type as the sample call names + * it, which its reflection lists as Metal's does. */ static void stitched_textures_and_samplers_read_their_kernels_bindings(void) { - LLVMMemoryBufferRef source = bitcode(samples); + LLVMMemoryBufferRef source = bitcode(samples), kept = bitcode(keeps); const struct stela_air_stitch_source sources[] = { {LLVMGetBufferStart(source), LLVMGetBufferSize(source), "sampled"}, + {LLVMGetBufferStart(kept), LLVMGetBufferSize(kept), "kept_float4"}, }; - const uint32_t resources[] = {0, 1}; + const uint32_t resources[] = {0, 1}, stored[] = {3, 2}; const struct stela_air_stitch_node nodes[] = { {.function = STELA_AIR_STITCH_TEXTURE, .input = 3}, {.function = STELA_AIR_STITCH_SAMPLER, .input = 1}, {.function = 0, .arguments = resources, .argument_count = 2}, + {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 0}, + {.function = 1, .arguments = stored, .argument_count = 2}, }; - const struct stela_air_stitch_graph graph = {"bound", nodes, 3, 2}; + const struct stela_air_stitch_graph graph = {"bound", nodes, 5, STELA_AIR_STITCH_NO_OUTPUT, + true}; struct stela_air_error error; LLVMMemoryBufferRef stitched = NULL; - assert(stela_metal_stitch(sources, 1, &graph, 1, keep_stitched, &stitched, &error)); - const struct stela_air_module modules[] = { - {LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched)}, - {LLVMGetBufferStart(source), LLVMGetBufferSize(source)}, - }; - const struct stela_metal_specialization specialization = { - .workgroup_size = {64, 1, 1}, .modules = modules, .module_count = 2, - }; - nir_shader *shader = compile(sampling_kernel, "samples", &specialization, &error); + assert(stela_metal_stitch(sources, 2, &graph, 1, keep_stitched, &stitched, &error)); + struct stela_metal_reflection reflection; + assert(stela_metal_reflect(LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched), "bound", + NULL, 0, &reflection, &error)); + assert(reflection.texture_count == 1 && reflection.textures[0].index == 3 && + reflection.textures[0].type == STELA_AIR_TEXTURE_2D && + reflection.textures[0].access == STELA_METAL_ACCESS_SAMPLE && + reflection.textures[0].primitive == STELA_AIR_FLOAT); + assert(reflection.sampler_count == 1 && reflection.samplers[0] == 1); + assert(reflection.buffer_count == 1 && reflection.buffers[0].index == 0); + nir_shader *shader = compile_stitched(stitched, "bound", source, kept, NULL, 0, &error); assert(shader); unsigned sampled = 0; nir_foreach_function_impl(impl, shader) { @@ -2250,10 +2292,13 @@ stitched_textures_and_samplers_read_their_kernels_bindings(void) const uint32_t swapped[] = {1, 0}; const struct stela_air_stitch_node crossed[] = { nodes[0], nodes[1], {.function = 0, .arguments = swapped, .argument_count = 2}, + nodes[3], nodes[4], }; - const struct stela_air_stitch_graph crossing = {"crossing", crossed, 3, 2}; - assert(!stela_metal_stitch(sources, 1, &crossing, 1, keep_stitched, &stitched, &error) && + const struct stela_air_stitch_graph crossing = {"crossing", crossed, 5, + STELA_AIR_STITCH_NO_OUTPUT, true}; + assert(!stela_metal_stitch(sources, 2, &crossing, 1, keep_stitched, &stitched, &error) && strstr(error.detail, "no texture")); + LLVMDisposeMemoryBuffer(kept); LLVMDisposeMemoryBuffer(source); } @@ -2267,64 +2312,53 @@ static const char *shares = "!75 = !{i32 0, !\"air.visible_input\", !\"air.arg_type_name\", !\"float\"," " !\"air.arg_name\", !\"m\"}\n"; -static const char *sharing_kernel = - "declare float @bound.MTL_VISIBLE_FN_REF() section \"air.externally_defined\"\n" - "define void @shares(ptr addrspace(1) %data) {\n" - "%v = call float @bound.MTL_VISIBLE_FN_REF()\n" - "store float %v, ptr addrspace(1) %data, align 4\nret void\n}\n" - "!air.kernel = !{!2}\n!air.visible_function_references = !{!5}\n" - "!2 = !{ptr @shares, !3, !4}\n!3 = !{}\n!4 = !{!40}\n" - "!5 = !{!\"air.visible_function_reference\", ptr @bound.MTL_VISIBLE_FN_REF, !\"bound\"}\n" - "!40 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\"," - " !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\"," - " i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"data\"}\n"; - -/* bound() = shared(threadgroup 2) reads and writes the threadgroup memory - * the dispatch of the kernel it inlines into sizes at that index. */ +/* kernel bound() { kept_float(buffer 0, shared(threadgroup 2)); } reads + * and writes the threadgroup memory its dispatch sizes at that index, which + * its reflection lists. */ static void stitched_threadgroup_memory_is_its_kernels(void) { - LLVMMemoryBufferRef source = bitcode(shares); + LLVMMemoryBufferRef source = bitcode(shares), kept = bitcode(keeps); const struct stela_air_stitch_source sources[] = { {LLVMGetBufferStart(source), LLVMGetBufferSize(source), "shared"}, + {LLVMGetBufferStart(kept), LLVMGetBufferSize(kept), "kept_float"}, }; - const uint32_t memory[] = {0}; + const uint32_t memory[] = {0}, stored[] = {2, 1}; const struct stela_air_stitch_node nodes[] = { {.function = STELA_AIR_STITCH_THREADGROUP, .input = 2}, {.function = 0, .arguments = memory, .argument_count = 1}, + {.function = STELA_AIR_STITCH_BUFFER_ADDRESS, .input = 0}, + {.function = 1, .arguments = stored, .argument_count = 2}, }; - const struct stela_air_stitch_graph graph = {"bound", nodes, 2, 1}; + const struct stela_air_stitch_graph graph = {"bound", nodes, 4, STELA_AIR_STITCH_NO_OUTPUT, + true}; struct stela_air_error error; LLVMMemoryBufferRef stitched = NULL; - assert(stela_metal_stitch(sources, 1, &graph, 1, keep_stitched, &stitched, &error)); - const struct stela_air_module modules[] = { - {LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched)}, - {LLVMGetBufferStart(source), LLVMGetBufferSize(source)}, - }; + assert(stela_metal_stitch(sources, 2, &graph, 1, keep_stitched, &stitched, &error)); + struct stela_metal_reflection reflection; + assert(stela_metal_reflect(LLVMGetBufferStart(stitched), LLVMGetBufferSize(stitched), "bound", + NULL, 0, &reflection, &error)); + assert(reflection.threadgroup_count == 1 && reflection.threadgroup[0].index == 2); + assert(reflection.buffer_count == 1 && reflection.buffers[0].index == 0); const struct stela_metal_threadgroup_length lengths[] = {{2, 128}}; - struct stela_metal_specialization specialization = { - .workgroup_size = {64, 1, 1}, .modules = modules, .module_count = 2, - .threadgroup_length_count = 1, .threadgroup_lengths = lengths, - }; - nir_shader *shader = compile(sharing_kernel, "shares", &specialization, &error); - if (!shader) - fprintf(stderr, "shares: %u %s\n", error.kind, error.detail); + nir_shader *shader = compile_stitched(stitched, "bound", source, kept, lengths, 1, &error); assert(shader && shader->info.shared_size >= 128); stela_metal_release(shader); /* Its dispatch sizes it, as a kernel's threadgroup buffer. */ - specialization.threadgroup_length_count = 0; - assert(!compile(sharing_kernel, "shares", &specialization, &error) && + assert(!compile_stitched(stitched, "bound", source, kept, NULL, 0, &error) && strstr(error.detail, "threadgroup buffer 2")); LLVMDisposeMemoryBuffer(stitched); /* Threadgroup memory feeds only a threadgroup pointer. */ const struct stela_air_stitch_node texture[] = { - {.function = STELA_AIR_STITCH_TEXTURE, .input = 2}, nodes[1], + {.function = STELA_AIR_STITCH_TEXTURE, .input = 2}, nodes[1], nodes[2], nodes[3], }; - const struct stela_air_stitch_graph crossing = {"crossing", texture, 2, 1}; - assert(!stela_metal_stitch(sources, 1, &crossing, 1, keep_stitched, &stitched, &error) && + const struct stela_air_stitch_graph crossing = {"crossing", texture, 4, + STELA_AIR_STITCH_NO_OUTPUT, true}; + assert(!stela_metal_stitch(sources, 2, &crossing, 1, keep_stitched, &stitched, &error) && strstr(error.detail, "no texture")); + LLVMDisposeMemoryBuffer(kept); LLVMDisposeMemoryBuffer(source); } @@ -2727,7 +2761,7 @@ main(void) defined_functions_inline_into_their_callers(); unresolved_calls_are_rejected_without_a_call_graph(); stitched_functions_call_their_nodes_in_order(); - stitched_builtins_read_their_kernels_builtins(); + stitched_kernels_read_their_builtins(); stitched_buffer_addresses_read_their_kernels_buffers(); stitched_early_returns_skip_what_follows(); stitched_textures_and_samplers_read_their_kernels_bindings(); diff --git a/crates/stela-driver-gpu/src/metal/compiler.rs b/crates/stela-driver-gpu/src/metal/compiler.rs index 1a1fcf1866..d09e3f5aee 100644 --- a/crates/stela-driver-gpu/src/metal/compiler.rs +++ b/crates/stela-driver-gpu/src/metal/compiler.rs @@ -473,6 +473,7 @@ impl Compiler for AirCompiler { nodes: nodes.as_ptr(), node_count: count(nodes.len())?, output: graph.output.unwrap_or(u32::MAX), + kernel: graph.kernel, }) }) .collect::>>()?; diff --git a/crates/stela-driver-gpu/src/metal/compiler/ffi.rs b/crates/stela-driver-gpu/src/metal/compiler/ffi.rs index da35d5ccb2..48c526f8e5 100644 --- a/crates/stela-driver-gpu/src/metal/compiler/ffi.rs +++ b/crates/stela-driver-gpu/src/metal/compiler/ffi.rs @@ -383,6 +383,7 @@ pub struct StitchGraph { pub(super) nodes: *const StitchNode, pub(super) node_count: u32, pub(super) output: u32, + pub(super) kernel: bool, } /// `stela_air_visit_bytes`. diff --git a/crates/stela-driver-gpu/src/metal/compiler/tests.rs b/crates/stela-driver-gpu/src/metal/compiler/tests.rs index 67f3f1b931..c7bddce8cf 100644 --- a/crates/stela-driver-gpu/src/metal/compiler/tests.rs +++ b/crates/stela-driver-gpu/src/metal/compiler/tests.rs @@ -12,6 +12,7 @@ use crate::metal::{ }, nvidia::{CHIPS, fixture::nvk}, shader::{LinkedFunction, Linking, Patch, PatchDomain}, + stitching::StitchedBuiltin, vertex::{STRIDE_DYNAMIC, StageInputDescriptor, VertexDescriptor}, }; use alloc::vec; @@ -439,6 +440,7 @@ unsafe extern "C" fn stitch( sources.len() as u8, graphs.len() as u8, graphs[0].node_count as u8, + u8::from(graphs[0].kernel), ]; // SAFETY: the callback takes the bytes for the call. unsafe { visit(data, names.as_ptr().cast(), names.len()) }; @@ -1038,10 +1040,29 @@ fn stitching_gives_the_service_each_source_and_graph() { }, ], output: Some(1), + kernel: false, }; assert_eq!( - compiler.stitch(&[(library, "kernel")], &[graph]).unwrap(), - [1, 1, 2] + compiler + .stitch(&[(library, "kernel")], core::slice::from_ref(&graph)) + .unwrap(), + [1, 1, 2, 0] + ); + let kernel = StitchedGraph { + nodes: vec![ + StitchedNode::Builtin(StitchedBuiltin::ThreadPositionInGrid), + StitchedNode::Call { + function: 0, + arguments: vec![0], + }, + ], + output: None, + kernel: true, + ..graph + }; + assert_eq!( + compiler.stitch(&[(library, "kernel")], &[kernel]).unwrap(), + [1, 1, 2, 1] ); assert!(compiler.stitch(&[(library, "absent")], &[]).is_err()); } diff --git a/crates/stela-driver-gpu/src/metal/device/pipelines.rs b/crates/stela-driver-gpu/src/metal/device/pipelines.rs index d936694e42..2edce9fde3 100644 --- a/crates/stela-driver-gpu/src/metal/device/pipelines.rs +++ b/crates/stela-driver-gpu/src/metal/device/pipelines.rs @@ -80,6 +80,10 @@ struct LibraryObject { /// `MTLCompileOptions.libraries` and a stitched library's functions' /// libraries, which it keeps. dependencies: Vec, + /// The dependencies are `MTLCompileOptions.libraries`, which load with + /// whatever links the library's functions; a stitched library's only + /// stay while it does, as `stitched` links their functions. + preloads: bool, /// What a pipeline linking its functions links too: stitched functions' /// calls stay declarations. stitched: Vec, @@ -494,7 +498,9 @@ impl Device { for &id in dependencies { self.pipelines.libraries.get_mut(id.0)?.users.others += 1; } - self.pipelines.libraries.get_mut(library.0)?.dependencies = dependencies.to_vec(); + let held = self.pipelines.libraries.get_mut(library.0)?; + held.dependencies = dependencies.to_vec(); + held.preloads = true; Ok(library) } @@ -534,7 +540,9 @@ impl Device { stitched.extend_from_slice(below); } let library = self.new_source_library(&air, None, &libraries)?; - self.pipelines.libraries.get_mut(library.0)?.stitched = stitched; + let held = self.pipelines.libraries.get_mut(library.0)?; + held.stitched = stitched; + held.preloads = false; Ok(library) } @@ -555,6 +563,7 @@ impl Device { dynamic, install_name, dependencies: Vec::new(), + preloads: false, stitched: Vec::new(), users: Users::CREATED, }); @@ -587,6 +596,7 @@ impl Device { dynamic: held.dynamic, install_name: held.install_name.clone(), dependencies: Vec::new(), + preloads: false, stitched: Vec::new(), users: Users::CREATED, }; @@ -877,12 +887,13 @@ impl Device { let function = self.pipelines.functions.get(id.0)?; let library = self.pipelines.library(function.library)?; let mut linking = specialization.linking; - for &dependency in &self - .pipelines - .libraries - .get(function.library.0)? - .dependencies - { + let held = self.pipelines.libraries.get(function.library.0)?; + let preloaded = if held.preloads { + held.dependencies.as_slice() + } else { + &[] + }; + for &dependency in preloaded { let dependency = self.pipelines.library(dependency)?; if !linking.libraries.contains(&dependency) { linking.libraries.push(dependency); @@ -1329,7 +1340,11 @@ impl Device { Kept::new([function], [&request.linked_functions]).with_archives(&request.archives); self.pipelines.ensure_created(&kept)?; let sources = self.pipelines.sources(&request.archives)?; - let linked = self.link(&request.linked_functions, false)?; + let mut linked = self.link(&request.linked_functions, false)?; + // A stitched kernel's calls link the functions it stitches. + let library = self.pipelines.functions.get(function.0)?.library; + let stitched = &self.pipelines.libraries.get(library.0)?.stitched; + linked.linking.private_functions.extend_from_slice(stitched); let interface = self.pipelines.interface(function)?.clone(); let descriptor = ComputePipelineDescriptor { compute_function: &interface, diff --git a/crates/stela-driver-gpu/src/metal/device/tests.rs b/crates/stela-driver-gpu/src/metal/device/tests.rs index a3c03aedf2..6bd3348658 100644 --- a/crates/stela-driver-gpu/src/metal/device/tests.rs +++ b/crates/stela-driver-gpu/src/metal/device/tests.rs @@ -1060,6 +1060,23 @@ fn a_stitched_function_links_what_it_calls() { }; assert_eq!(libraries(&linking.functions), [2]); assert_eq!(libraries(&linking.private_functions), [1, 0]); + + // A stitched kernel links them as its own calls. + let stitched_kernel = device.new_function(library, "kernel", Some(&[])).unwrap(); + let request = ComputePipelineRequest { + compute_function: stitched_kernel, + linked_functions: LinkedFunctions::default(), + ..request + }; + let pipeline = device.new_compute_pipeline(&request).unwrap(); + device + .compute_variant(u64::from(pipeline.0), &dispatch) + .unwrap(); + let linking = &device.compiler.compiled.last().unwrap().linking; + assert!(linking.functions.is_empty()); + assert_eq!(libraries(&linking.private_functions), [1, 0]); + // The libraries it keeps for them preload nothing. + assert!(linking.libraries.is_empty()); } #[test] diff --git a/crates/stela-driver-gpu/src/metal/service/tests/pipelines.rs b/crates/stela-driver-gpu/src/metal/service/tests/pipelines.rs index 1f72045178..5aac53a3bd 100644 --- a/crates/stela-driver-gpu/src/metal/service/tests/pipelines.rs +++ b/crates/stela-driver-gpu/src/metal/service/tests/pipelines.rs @@ -237,7 +237,7 @@ fn stitched_libraries_take_visible_functions() { }; let (kernel, visible) = (function(library, "kernel"), function(library, "visible")); // `f(a) = visible(a)`. - let words = [1u32, 2, 2, 0x66, 0, 0, 1, 1, 0]; + let words = [1u32, 2, 2, 0, 0x66, 0, 0, 1, 1, 0]; let graphs: alloc::vec::Vec = words.iter().flat_map(|word| word.to_le_bytes()).collect(); let graphs = memory.put(&graphs); let mut stitched = |functions: &[u64], memory: &mut Memory| { diff --git a/crates/stela-driver-gpu/src/metal/stitching.rs b/crates/stela-driver-gpu/src/metal/stitching.rs index 044f6e5337..8033367061 100644 --- a/crates/stela-driver-gpu/src/metal/stitching.rs +++ b/crates/stela-driver-gpu/src/metal/stitching.rs @@ -1,6 +1,7 @@ //! `MTLFunctionStitchingGraph`s, as the frontend's [`decode`] stream carries //! them: little-endian 32-bit words, each graph -//! `[name bytes, node count, output + 1]`, its padded name and its nodes, an +//! `[name bytes, node count, output + 1, kernel]`, its padded name and its +//! nodes, an //! input `[0, argument index]`, a builtin `[u32::MAX, builtin]`, a buffer //! address `[u32::MAX - 1, buffer index, offset low, offset high, dereference]`, //! an early return `[u32::MAX - 2, condition node index, value node index + 1]`, @@ -16,11 +17,11 @@ use alloc::{string::String, vec::Vec}; pub enum StitchedNode { /// The stitched function's argument. Input(u32), - /// A builtin of the function the stitched function inlines into. + /// A builtin of the stitched kernel. Builtin(StitchedBuiltin), /// `MTLFunctionStitchingInputBufferAddress`: `offset` bytes into the - /// buffer the function the stitched function inlines into binds at - /// `index`, or with `dereference` the value there. + /// buffer the stitched kernel binds at `index`, or with `dereference` the + /// value there. BufferAddress { index: u32, offset: u64, @@ -33,8 +34,8 @@ pub enum StitchedNode { condition: u32, value: Option, }, - /// `MTLFunctionStitchingInputTexture`: the texture the function the - /// stitched function inlines into binds at the index. + /// `MTLFunctionStitchingInputTexture`: the texture the stitched kernel + /// binds at the index. Texture(u32), /// `MTLFunctionStitchingInputSampler`: likewise its sampler. Sampler(u32), @@ -75,6 +76,9 @@ pub struct StitchedGraph { pub nodes: Vec, /// The node whose result the function returns. pub output: Option, + /// The graph is a kernel's, as `MTLFunctionStitchingAttributeKernel` + /// makes it, rather than a visible function's. + pub kernel: bool, } const MALFORMED: Error = Error::Invalid("stitched function graph"); @@ -178,6 +182,11 @@ pub fn decode(stream: &[u8], functions: usize) -> Result> { let name_bytes = words.word()? as usize; let count = words.word()? as usize; let output = words.word()?.checked_sub(1); + let kernel = match words.word()? { + 0 => false, + 1 => true, + _ => return Err(MALFORMED), + }; let name = words.name(name_bytes)?; if name.is_empty() || name.contains('\0') { return Err(MALFORMED); @@ -195,6 +204,7 @@ pub fn decode(stream: &[u8], functions: usize) -> Result> { name, nodes, output, + kernel, }); } Ok(graphs) @@ -212,7 +222,7 @@ mod tests { #[test] fn nodes_decode_in_their_order() { // `f(a) = g(g(a))`. - let words = [1, 3, 3, 0x66, 0, 0, 1, 1, 0, 1, 1, 1]; + let words = [1, 3, 3, 0, 0x66, 0, 0, 1, 1, 0, 1, 1, 1]; assert_eq!( decode(&stream(&words), 1).unwrap(), [StitchedGraph { @@ -229,16 +239,19 @@ mod tests { }, ], output: Some(2), + kernel: false, }] ); } #[test] fn builtins_decode_and_unknown_ones_are_refused() { - // `f() = g(thread_position_in_grid)`. - let words = [1, 2, 2, 0x66, u32::MAX, 1, 1, 1, 0]; + // `kernel f() { g(thread_position_in_grid); }`. + let words = [1, 2, 0, 1, 0x66, u32::MAX, 1, 1, 1, 0]; + let graph = &decode(&stream(&words), 1).unwrap()[0]; + assert!(graph.kernel); assert_eq!( - decode(&stream(&words), 1).unwrap()[0].nodes, + graph.nodes, [ StitchedNode::Builtin(StitchedBuiltin::ThreadPositionInGrid), StitchedNode::Call { @@ -248,17 +261,18 @@ mod tests { ] ); let mut unknown = words; - unknown[5] = 3; + unknown[6] = 3; assert!(decode(&stream(&unknown), 1).is_err()); } #[test] fn textures_samplers_and_threadgroups_decode_their_indices() { - // `f() = g(texture 3, sampler 1, threadgroup 2)`. + // `kernel f() { g(texture 3, sampler 1, threadgroup 2); }`. let words = [ 1, 4, - 4, + 0, + 1, 0x66, u32::MAX - 3, 3, @@ -284,8 +298,8 @@ mod tests { #[test] fn buffer_addresses_decode_their_offsets() { - // `f() = g(*(buffer 3 + 2^32 + 8))`. - let words = [1, 2, 2, 0x66, u32::MAX - 1, 3, 8, 1, 1, 1, 1, 0]; + // `kernel f() { g(*(buffer 3 + 2^32 + 8)); }`. + let words = [1, 2, 0, 1, 0x66, u32::MAX - 1, 3, 8, 1, 1, 1, 1, 0]; assert_eq!( decode(&stream(&words), 1).unwrap()[0].nodes[0], StitchedNode::BufferAddress { @@ -295,14 +309,14 @@ mod tests { } ); let mut unknown = words; - unknown[8] = 2; + unknown[9] = 2; assert!(decode(&stream(&unknown), 1).is_err()); } #[test] fn early_returns_name_an_earlier_condition() { // `f(a) { if (g(a)) return g(a); }`. - let words = [1, 3, 0, 0x66, 0, 0, 1, 1, 0, u32::MAX - 2, 1, 2]; + let words = [1, 3, 0, 0, 0x66, 0, 0, 1, 1, 0, u32::MAX - 2, 1, 2]; assert_eq!( decode(&stream(&words), 1).unwrap()[0].nodes[2], StitchedNode::EarlyReturn { @@ -311,7 +325,7 @@ mod tests { } ); let mut nothing = words; - nothing[11] = 0; + nothing[12] = 0; assert_eq!( decode(&stream(¬hing), 1).unwrap()[0].nodes[2], StitchedNode::EarlyReturn { @@ -319,7 +333,7 @@ mod tests { value: None, } ); - for (at, later) in [(10, 2), (11, 3)] { + for (at, later) in [(11, 2), (12, 3)] { let mut bad = words; bad[at] = later; assert!(decode(&stream(&bad), 1).is_err(), "{at}"); @@ -328,14 +342,16 @@ mod tests { #[test] fn refuses_what_a_graph_cannot_be() { - let good = [1, 2, 2, 0x66, 0, 0, 1, 1, 0]; + let good = [1, 2, 2, 0, 0x66, 0, 0, 1, 1, 0]; assert!(decode(&stream(&good), 1).is_ok()); for (at, value) in [ - // The function, a later node, an output past the nodes, no name. - (6, 2), - (8, 1), + // The function, a later node, an output past the nodes, no name, + // a kind of graph past the two. + (7, 2), + (9, 1), (2, 3), (0, 0), + (3, 2), // A node count past the stream. (1, u32::MAX), ] { @@ -343,6 +359,6 @@ mod tests { bad[at] = value; assert!(decode(&stream(&bad), 1).is_err(), "{at}"); } - assert!(decode(&stream(&good)[..30], 1).is_err()); + assert!(decode(&stream(&good)[..34], 1).is_err()); } } diff --git a/guest/stela-gpu/bundle/Stitching.m b/guest/stela-gpu/bundle/Stitching.m index c39156106e..51821ac53b 100644 --- a/guest/stela-gpu/bundle/Stitching.m +++ b/guest/stela-gpu/bundle/Stitching.m @@ -1,8 +1,10 @@ /* * MTLFunctionStitchingGraph as the stream `metal/stitching.rs` reads: the nodes * a graph reaches, each after what it uses, whether as an argument or as a - * control dependency. Metal's attributes need nothing, since every call inlines, - * and a builtin node reads the builtin of the kernel the call inlines into. + * control dependency, and whether it is a kernel's. A kernel's graph, which + * MTLFunctionStitchingAttributeKernel or Metal's own SPI graph class makes, + * reads its builtins and bindings; inlining needs no attribute, since every + * call inlines. */ #include "Bundle.h" @@ -11,6 +13,7 @@ - (NSArray *)functionGraphs; - (NSArray *)functions; - (NSArray *)nodes; +- (NSArray *)attributes; - (id)outputNode; - (NSString *)functionName; - (NSString *)name; @@ -240,11 +243,17 @@ static BOOL refuse(StelaFailure *failure, const char *reason) if (output && ![self addNode:output failure:failure]) { return NO; } + BOOL kernel = [graph isKindOfClass:NSClassFromString(@"MTLFunctionStitchingGraphSPI")]; + NSArray *attributes = [graph attributes]; + for (NSUInteger index = 0; !kernel && index < attributes.count; index++) { + kernel = [attributes[index] isKindOfClass:NSClassFromString(@"MTLFunctionStitchingAttributeKernel")]; + } const char *name = [graph functionName].UTF8String; uint32_t header[] = { (uint32_t)strlen(name), (uint32_t)_nodes.count, output ? (uint32_t)[_nodes indexOfObjectIdenticalTo:output] + 1 : 0, + kernel, }; static const uint8_t padding[4]; [_stream appendBytes:header length:sizeof(header)];