machdocs
Home Ecosystem Changelog

GPU shaders

A spirv target compiles ordinary mach into a finished SPIR-V module. A shader is written in the same language as the rest of the project (the same records, the same vectors, the same comptime) and a small set of gpu.* decorators say which functions are pipeline stages and which module-scope variables the pipeline binds.

Note

Every decorator on this page is accepted on every target, because which target a module is built for is not a property of its source. Only a target that forms pipeline stages acts on them: on a machine target a staged function is compiled normally and the interface variables are ordinary globals. v6 spelled the set without the gpu. prefix and intrinsic as op. Each v6 spelling is refused naming its replacement, which mach migrate writes.

The target

The shader target is vulkan-spirv: sys = "vulkan", arch = "spirv" and abi = "shader". Its env names the Vulkan version the module is consumed by, vulkan1.0 to vulkan1.3, which fixes the SPIR-V version and the capabilities the module may hold. Without env a module is SPIR-V 1.6 and holds what vulkan1.3 selects. mach info targets lists it, beside opencl-spirv for kernels.

[target.gpu]
arch = "spirv"
sys  = "vulkan"
abi  = "shader"
env  = "vulkan1.3"

[artifact.shader]
kind = "module"
entry = "shader.mach"
out = "{project.work}/shader.spv"
targets = ["gpu"]

A shader artifact's kind is module. Every source module the artifact holds, its dependencies' included, compiles as one unit into one SPIR-V module, and the link writes it at the artifact's out:

$ mach build . -t gpu
     built  shader  gpu  debug
            ./out/gpu/debug/shader.spv   784 B   1 module   22ms

A module artifact is a shader module: it carries the entry point of every stage and no external linkage at all, since a Vulkan consumer refuses a module carrying linkage, and a module that holds no stage is refused. An object artifact is a library module, which keeps the Linkage capability and publishes each function as a linkage export for a later link. Which of the two a build makes is the artifact's kind, not the source's, so one source set can build both. mach test builds a finished-module target and runs nothing, since it links no test executable. See Manifest.

gpu.stage(str): a pipeline stage

Marks a function as the entry point of a graphics or compute pipeline stage. The value set is closed ("vertex", "fragment", "compute") and an unrecognized value is a compile error, not a module that quietly forms no stage.

#[gpu.stage("vertex")]
fun vertex_main() {}

#[gpu.stage("fragment")]
fun fragment_main() {}

A staged function takes no parameters and returns nothing. A pipeline stage has no caller: its inputs arrive through input interface variables and its results leave through output ones. A staged function with either is rejected.

The entry point's name, as a pipeline-creation call looks it up, is the function's bare source name. A shader module has no linker symbols to mangle.

gpu.workgroup(x, y, z)

Sizes the workgroup of a #[gpu.stage("compute")] function. It requires that stage on the same function, since without one it would silently mean nothing.

#[gpu.stage("compute")]
#[gpu.workgroup(64, 1, 1)]
fun compute_main() {}

Omitted, a compute stage takes the single-invocation default (1, 1, 1). Any dimension may instead name a #[gpu.spec] var of type u32 or i32, which the host sets when it creates the pipeline.

The interface

A stage reads and writes module-scope variables that the pipeline binds. These decorators say which kind each variable is. They apply only to module-level val / var bindings, and a variable carries exactly one of them.

#[handle("spirv", "image", f32, "2D", 0, 0, 0, 1, "Unknown")]
pub def Texture2D;

#[handle("spirv", "sampled_image", Texture2D)]
pub def Sampler2D;

#[gpu.input(0)]            var in_position: f32x4;
#[gpu.output(0)]           var out_colour:  f32x4;
#[gpu.builtin("position")] var position:    f32x4;

rec Camera { view: f32x4; proj: f32x4; }
#[gpu.uniform(0, 0)] var camera: Camera;

rec Particles { pos: [64]f32x4; }
#[gpu.storage(0, 1)] var particles: Particles;

#[gpu.sampler(1, 0)] var albedo: Sampler2D;

rec Params { tint: f32x4; count: u32; }
#[gpu.push] var params: Params;

gpu.input and gpu.output number a varying with a location, which is how one stage's outputs line up with the next stage's inputs: the producer's #[gpu.output(0)] feeds the consumer's #[gpu.input(0)]. An input, a binding and a push block take no initializer, since the pipeline or the host supplies the value. An output may have one, which is the value it starts at.

gpu.builtin(str)

Names a value the pipeline supplies or consumes instead of one a location carries. The set is closed.

ValueMeaningTypeDirectionStage
"position"clip-space vertex positionf32x4writtenvertex
"point_size"rasterized point sizef32writtenvertex
"vertex_index"index of the current vertexu32readvertex
"instance_index"index of the current instanceu32readvertex
"frag_coord"fragment window coordinatef32x4readfragment
"global_invocation"compute global invocation idu32x3readcompute
"local_invocation"compute local invocation idu32x3readcompute
"workgroup_id"compute workgroup idu32x3readcompute
"num_workgroups"compute workgroup count of a dispatchu32x3readcompute
"local_invocation_index"compute local invocation id, flattenedu32readcompute
"subgroup_size"invocations in a subgroupu32readevery
"subgroup_invocation"the invocation's index in its subgroupu32readevery
"subgroup_id"the subgroup's index in its workgroupu32readcompute
"num_subgroups"subgroups in the workgroupu32readcompute

The direction, the type and the stage are properties of the built-in, not something you restate. Declaring a built-in at any other type is a compile error naming both the declared type and the required one, and a stage that uses a built-in outside its row is an error naming the built-in and both stages. The integer rows accept i32 as well as u32, since the emitted type is sign-less either way.

gpu.uniform, gpu.storage and gpu.push blocks

gpu.uniform binds a read-only block by descriptor set and binding, gpu.storage a read-write buffer the same way, and gpu.push a push-constant block the host supplies with the command, which takes no arguments. Each type must be a rec, and each is emitted with its Block decoration and an explicit byte offset on every member, taken from the same layout the rest of the compiler uses, so what the shader reads is what the host wrote. A push block is read-only, and Vulkan admits one per entry point.

A block keeps mach's own layout, and the layout is held to the rules Vulkan holds its class to, refused where it breaks them rather than silently repacked. A storage buffer and a push block follow std430-shaped rules, which use the element's natural stride. Under vulkan1.0 and vulkan1.1 a uniform block follows std140-shaped rules, under which an array's stride is rounded up to 16, so [8]f32 is refused in a uniform block there. Under vulkan1.2, vulkan1.3 and with no env a uniform block follows the std430-shaped rules too.

A compute stage's data path is gpu.storage: Vulkan forbids the Output storage class in a compute execution model, so a compute shader reads and writes buffers rather than varyings.

Memory qualifiers

gpu.storage takes memory qualifiers after the descriptor pair, in any order: "readonly", "writeonly" and "coherent".

rec Palette { columns: [512]f32x4; }
#[gpu.storage(0, 3, "readonly")] var palette: Palette;

rec Frame { texels: [4096]f32x4; }
#[gpu.storage(0, 4, "writeonly")] var frame: Frame;

rec Counters { done: u32; }
#[gpu.storage(0, 5, "coherent")] var counters: Counters;

#[gpu.builtin("global_invocation")] var gid: u32x3;

#[gpu.stage("compute")]
#[gpu.workgroup(64, 1, 1)]
fun copy_palette() {
    frame.texels[gid[0]] = palette.columns[gid[0] % 512];
}

The inference is one-sided on purpose: anything the compiler cannot follow counts as a write, so a missing decoration is possible and a wrong one is not.

gpu.spec(id): specialization constants

A specialization constant is a value the host supplies when it creates the pipeline. It is declared as a module-level var carrying the constant's id, and its initializer, which is required, is the default the pipeline keeps when the host supplies nothing.

#[gpu.spec(0)] var tile: u32 = 64;
#[gpu.spec(1)] var gain: f32 = 0.5;

#[gpu.stage("compute")]
#[gpu.workgroup(tile, 1, 1)]
fun compute_main() {}

It is never a compile-time value, the optimizer never folds it to its initializer, and a store to it or its address is refused. The type must be a scalar integer or float, so a flag is an integer the host sets with the same 4 bytes as a VkBool32.

gpu.shared: workgroup memory

gpu.shared declares one instance per workgroup of a compute stage, which every invocation of that workgroup reads and writes. It applies to a var only and takes no arguments.

#[gpu.builtin("local_invocation")] var local_id: u32x3;
#[gpu.shared] var tile: [256]f32;

#[gpu.stage("compute")]
#[gpu.workgroup(64, 1, 1)]
fun blur() { tile[local_id[0]] = 1.0; }

A #[gpu.shared] variable is zero when a compute stage starts, so it takes no initializer. Under vulkan1.3 the consumer zeroes it, and on an earlier environment the compiler zeroes it at the start of each compute stage that uses it. Using one from a vertex or fragment stage is a compile error naming the stage.

Textures and samplers

gpu.sampler binds a handle by descriptor set and binding. A handle type is a bodyless def carrying #[handle(target, constructor, operands...)]: the owning target mints it and the pipeline binds it. A handle cannot be a local binding, a record field, or sit inside an array. A storage image, an image handle whose Sampled operand is 2, binds through gpu.storage instead, and a subpass input states its input attachment with #[gpu.attachment(index)] beside its gpu.storage.

Sampling is an #[intrinsic(...)] declaration rather than a language form, because a sample is one SPIR-V instruction, exactly as sqrt and dot are. The separately bound form declares the instruction that combines an image and a sampler beside it:

#[handle("spirv", "image", f32, "2D", 0, 0, 0, 1, "Unknown")]
pub def Texture2D;

#[handle("spirv", "sampled_image", Texture2D)]
pub def Sampler2D;

#[handle("spirv", "sampler")]
pub def Sampler;

#[intrinsic("spirv", "core", "OpImageSampleImplicitLod")]
fun sample(s: Sampler2D, uv: f32x2) f32x4;

#[intrinsic("spirv", "core", "OpSampledImage")]
fun combine(t: Texture2D, s: Sampler) Sampler2D;

#[gpu.input(0)]        var in_uv:      f32x2;
#[gpu.output(0)]       var out_colour: f32x4;
#[gpu.sampler(1, 0)]   var albedo:     Sampler2D;
#[gpu.sampler(1, 1)]   var base_tex:   Texture2D;
#[gpu.sampler(1, 2)]   var base_smp:   Sampler;

#[gpu.stage("fragment")]
fun frag_main() {
    out_colour = sample(albedo, in_uv);
}

#[gpu.stage("fragment")]
fun frag_sep() {
    out_colour = sample(combine(base_tex, base_smp), in_uv);
}

The combined value is handed straight to the sample rather than named: SPIR-V requires an OpSampledImage result be consumed in the block that produced it, which is the same rule that makes a handle-typed local a compile error.

intrinsic(target, set, name): a function that is an instruction

A shader needs sqrt, normalize, dot, barriers and atomics. None of them is an operator, and none of them is a call SPIR-V can make: each is one instruction. This decorator says which one a function is, so that on a spirv target a call to it becomes that instruction, inline, rather than a call.

#[intrinsic("spirv", "GLSL.std.450", "Sqrt")]
pub fun sqrt(x: f32) f32;

#[intrinsic("spirv", "GLSL.std.450", "Normalize")]
pub fun normalize(v: f32x4) f32x4;

#[intrinsic("spirv", "core", "OpDot")]
pub fun dot(a: f32x4, b: f32x4) f32;

#[intrinsic("spirv", "core", "OpControlBarrier")]
pub fun barrier(execution: u32, memory: u32, semantics: u32);

#[intrinsic("spirv", "core", "OpAtomicIAdd")]
pub fun atomic_add(p: *u32, scope: u32, semantics: u32, v: u32) u32;

The first argument names the target, the ISA name the manifest selects with, the second the instruction set, and the third the instruction within it. The instruction set and name are checked when the named target is the one selected, and the parameter count is held to the instruction's own operand count. A declaration for any other target is inert.

SetMeaning
"core"the core opcode space, which needs no import
"GLSL.std.450"the standard extended set, imported once per module on use

The substitution is uniform: the emitted instruction's result type is the function's declared return type and its operands are the function's parameters in declaration order. A pointer operand takes its storage class from the call site, so atomic_add(?counters.n, ...) points into the storage buffer. On its target a decorated function is the instruction and never its body, and the optimizer treats it as reading and writing all memory.

#[intrinsic("spirv", "GLSL.std.450", "Sqrt")]
pub fun sqrt(x: f32) f32;

#[intrinsic("spirv", "GLSL.std.450", "Normalize")]
pub fun normalize(v: f32x4) f32x4;

#[intrinsic("spirv", "core", "OpDot")]
pub fun dot(a: f32x4, b: f32x4) f32;

#[intrinsic("spirv", "core", "OpAtomicIAdd")]
pub fun atomic_add(p: *u32, scope: u32, semantics: u32, v: u32) u32;

rec Counters { n: u32; }
#[gpu.storage(0, 0)] var counters: Counters;
#[gpu.input(0)] var normal: f32x4;
#[gpu.output(0)] var out_colour: f32x4;

#[gpu.stage("fragment")]
fun shade() {
    val n: f32x4 = normalize(normal);
    val l: f32   = sqrt(dot(n, n));
    out_colour = f32x4{l, l, l, 1.0};
    val old: u32 = atomic_add(?counters.n, 1, 0, 1);
}
Check the specification, not GLSL

dot is core OpDot, not a GLSL.std.450 instruction, even though GLSL spells it beside normalize and length. Check each function against the SPIR-V specification rather than against GLSL's surface.

On every other target a decorated function is an ordinary function. A bodyless one is then an undefined symbol, so a CPU build that calls it fails at link naming the symbol. A decorated function may have a body, and if it does, that body is what every other target runs.

Shaders across modules

A shader can call a function defined in another module and can use an interface variable one declares, so a shared library may own a whole descriptor set. A stage's interface is what it reaches, directly or through the functions it calls, not what its modules declare. The compiler does not refuse two bindings at one (set, binding) pair: two variables there are well-formed SPIR-V, and the conflict is with the pipeline layout, which is not in the module.

What a stage may not do

See also

  • Types - handle types, and the SIMD vectors a stage computes over
  • Decorators - the full decorator set and where each applies
  • Manifest - declaring a spirv target and what its build delivers