diff --git a/.agents/vk.md b/.agents/vk.md index 3fa1a4a..17f65bf 100644 --- a/.agents/vk.md +++ b/.agents/vk.md @@ -98,6 +98,14 @@ app -> Vulkan loader (Debian libvulkan1) -> /usr/lib/kw/libvulkan_kw.so (vk/icd) on integers and booleans, scalar and vector; Select, FConvert, QuantizeToF16 and the composite operations on floats: vkQuake), isinf/isnan become bit tests and an `int[1]` gl_SampleMask(In) a u32. + GLSL.std.450's integer min, max, clamp, abs, sign and MSB get operands + and results of the other signedness bitcast to the opcode's (spv-in takes + it from the operands): naga's own writer, as wgpu uses it, emits its + bounds checks as UMin on i32 values (FilmCraft), and glslang findMSB(uint) + as FindUMsb with an int result. OpLogicalAnd/OpLogicalOr on bool vectors, + which spv-in types as scalars only, become OpSelect with an all-false or + all-true vector (naga's writer guards integer vector divisions with them: + egui-wgpu 0.37's fragment shaders). Compute helpers that read num_workgroups or workgroup_id through spv-in's private copies get them as arguments (`src/builtins.rs`), and a workgroup over the device's limits that shares memory or has barriers diff --git a/vk/naga/src/lib.rs b/vk/naga/src/lib.rs index c298d3f..3dac06c 100644 --- a/vk/naga/src/lib.rs +++ b/vk/naga/src/lib.rs @@ -228,6 +228,8 @@ fn translate(spv: &[u8], o: &Opts) -> Result { _ => words, }; let words = spirv::lower_umul_extended(words); + let words = spirv::int_ext_inst_signedness(words); + let words = spirv::select_vector_logical_ops(words); let words = spirv::lower_isinf_isnan(words); let words = spirv::output_sample_mask(words); let words = spirv::localize_subgroup_operands(words); diff --git a/vk/naga/src/spirv.rs b/vk/naga/src/spirv.rs index 307e131..10f0e42 100644 --- a/vk/naga/src/spirv.rs +++ b/vk/naga/src/spirv.rs @@ -3101,6 +3101,248 @@ pub fn lower_umul_extended(words: Vec) -> Vec { out } +// GLSL.std.450's integer min, max, clamp, abs, sign and MSB take their +// signedness from the opcode, and their operand and result types may have +// either: naga's own SPIR-V writer, as wgpu uses it on Vulkan, emits its +// bounds checks as UMin with a u32 result on an i32 index and UMin on +// signed image coordinates (FilmCraft's effects, #57). naga's spv-in takes +// the signedness from the operands instead, so mixed operands fail +// validation (min(i32, u32)) and signed ones become a signed min that no +// longer clamps negative values. 32-bit operands of the other signedness +// are bitcast to the opcode's, and the result back to its declared type. +pub fn int_ext_inst_signedness(words: Vec) -> Vec { + const OP_EXT_INST_IMPORT: u32 = 11; + const OP_EXT_INST: u32 = 12; + const OP_TYPE_INT: u32 = 21; + const OP_TYPE_VECTOR: u32 = 23; + const OP_FUNCTION: u32 = 54; + const OP_BITCAST: u32 = 124; + // GLSL.std.450 instruction -> signed + let signed_op = |x: u32| match x { + 5 | 7 | 39 | 42 | 45 | 74 => Some(true), // SAbs SSign SMin SMax SClamp FindSMsb + 38 | 41 | 44 | 75 => Some(false), // UMin UMax UClamp FindUMsb + _ => None, + }; + let mut glsl = None; + let mut ints: HashMap = HashMap::new(); // 32-bit int type -> signed + let mut vectors: HashMap = HashMap::new(); // vector type -> (component, count) + let mut val_ty: HashMap = HashMap::new(); + let mut cands = false; + let mut i = 5; + while i < words.len() { + let n = (words[i] >> 16) as usize; + let o = words[i] & 0xffff; + let a = &words[i + 1..i + n]; + match o { + OP_EXT_INST_IMPORT if read_string(&a[1..]) == "GLSL.std.450" => glsl = Some(a[0]), + OP_TYPE_INT if a.len() == 3 && a[1] == 32 => { + ints.insert(a[0], a[2] != 0); + } + OP_TYPE_VECTOR if a.len() == 3 => { + vectors.insert(a[0], (a[1], a[2])); + } + OP_EXT_INST if a.len() >= 5 && Some(a[2]) == glsl && signed_op(a[3]).is_some() => cands = true, + _ => {} + } + // Result-typed instructions: (type, id) first. + if n >= 3 && !(19..=39).contains(&o) && !matches!(o, 5 | 6 | 7 | 10 | 11 | 15 | 16 | 17 | 71 | 72 | 331 | 332) { + val_ty.insert(a[1], a[0]); + } + i += n; + } + if !cands { + return words; + } + // A 32-bit integer scalar or vector type as (signed, component count). + let shape = |t: u32| -> Option<(bool, u32)> { + if let Some(&s) = ints.get(&t) { + return Some((s, 1)); + } + let &(c, k) = vectors.get(&t)?; + ints.get(&c).map(|&s| (s, k)) + }; + // The instructions to rewrite: (index, signed, count), all operands and + // the result of the same component count. + let mut todo: Vec<(usize, bool, u32)> = Vec::new(); + let mut i = 5; + while i < words.len() { + let n = (words[i] >> 16) as usize; + let a = &words[i + 1..i + n]; + if words[i] & 0xffff == OP_EXT_INST && a.len() >= 5 && Some(a[2]) == glsl { + if let (Some(s), Some((rs, k))) = (signed_op(a[3]), shape(a[0])) { + let ops: Option> = a[4..].iter().map(|x| val_ty.get(x).and_then(|&t| shape(t))).collect(); + if let Some(ops) = ops { + if ops.iter().all(|&(_, ok)| ok == k) && (rs != s || ops.iter().any(|&(os, _)| os != s)) { + todo.push((i, s, k)); + } + } + } + } + i += n; + } + if todo.is_empty() { + return words; + } + // The types the rewrite needs: existing ones, else declared before the + // first function. + let mut bound = words[3]; + let mut decls: Vec = Vec::new(); + let mut scalar: HashMap = HashMap::new(); + for (&t, &s) in &ints { + scalar.entry(s).and_modify(|x| *x = (*x).min(t)).or_insert(t); + } + let mut vector: HashMap<(u32, u32), u32> = HashMap::new(); + for (&t, &key) in &vectors { + vector.entry(key).and_modify(|x| *x = (*x).min(t)).or_insert(t); + } + let mut ty: HashMap<(bool, u32), u32> = HashMap::new(); + for &(_, s, k) in &todo { + if ty.contains_key(&(s, k)) { + continue; + } + let c = *scalar.entry(s).or_insert_with(|| { + bound += 1; + decls.extend(inst(OP_TYPE_INT, &[bound - 1, 32, s as u32])); + bound - 1 + }); + let t = if k == 1 { + c + } else { + *vector.entry((c, k)).or_insert_with(|| { + bound += 1; + decls.extend(inst(OP_TYPE_VECTOR, &[bound - 1, c, k])); + bound - 1 + }) + }; + ty.insert((s, k), t); + } + let mut out: Vec = Vec::with_capacity(words.len() + 8 * todo.len() + decls.len()); + out.extend_from_slice(&words[..5]); + let mut todo = todo.into_iter().peekable(); + let mut first_fn = true; + let mut i = 5; + while i < words.len() { + let n = (words[i] >> 16) as usize; + let a = &words[i + 1..i + n]; + if words[i] & 0xffff == OP_FUNCTION && first_fn { + first_fn = false; + out.extend_from_slice(&decls); + } + match todo.peek() { + Some(&(at, s, k)) if at == i => { + todo.next(); + let t = ty[&(s, k)]; + let mut e = vec![t, a[1], a[2], a[3]]; + for &x in &a[4..] { + if shape(val_ty[&x]).map(|(os, _)| os) == Some(s) { + e.push(x); + } else { + bound += 1; + out.extend(inst(OP_BITCAST, &[t, bound - 1, x])); + e.push(bound - 1); + } + } + if a[0] == t || shape(a[0]).map(|(rs, _)| rs) == Some(s) { + e[0] = a[0]; + out.extend(inst(OP_EXT_INST, &e)); + } else { + bound += 1; + e[1] = bound - 1; + out.extend(inst(OP_EXT_INST, &e)); + out.extend(inst(OP_BITCAST, &[a[0], a[1], bound - 1])); + } + } + _ => out.extend_from_slice(&words[i..i + n]), + } + i += n; + } + out[3] = bound; + out +} + +// OpLogicalAnd and OpLogicalOr on bool vectors, which naga's own SPIR-V +// writer emits (its guard of an integer vector division: divisor == 0 || +// (x == MIN && divisor == -1), FilmCraft) and spv-in's type resolution +// takes on scalars only: as OpSelect(a, b, false) and OpSelect(a, true, b), +// componentwise as the logical ops are (both operands are evaluated). +pub fn select_vector_logical_ops(words: Vec) -> Vec { + const OP_TYPE_BOOL: u32 = 20; + const OP_TYPE_VECTOR: u32 = 23; + const OP_CONSTANT_TRUE: u32 = 41; + const OP_CONSTANT_FALSE: u32 = 42; + const OP_CONSTANT_COMPOSITE: u32 = 44; + const OP_FUNCTION: u32 = 54; + const OP_SELECT: u32 = 169; + const OP_LOGICAL_OR: u32 = 166; + const OP_LOGICAL_AND: u32 = 167; + let mut bools: Vec = Vec::new(); + let mut bvecs: HashMap = HashMap::new(); // bool vector type -> (bool, count) + let mut used: Vec = Vec::new(); // the bool vector types the ops use, in order + let mut i = 5; + while i < words.len() { + let n = (words[i] >> 16) as usize; + let a = &words[i + 1..i + n]; + match words[i] & 0xffff { + OP_TYPE_BOOL => bools.push(a[0]), + OP_TYPE_VECTOR if a.len() == 3 && bools.contains(&a[1]) => { + bvecs.insert(a[0], (a[1], a[2])); + } + OP_LOGICAL_AND | OP_LOGICAL_OR if a.len() == 4 && bvecs.contains_key(&a[0]) && !used.contains(&a[0]) => used.push(a[0]), + _ => {} + } + i += n; + } + if used.is_empty() { + return words; + } + // Per bool vector type: its all-true and all-false constants. + let mut bound = words[3]; + let mut decls: Vec = Vec::new(); + let mut consts: HashMap = HashMap::new(); + let mut scalars: HashMap = HashMap::new(); // bool type -> (true, false) + for &v in &used { + let (b, k) = bvecs[&v]; + let (t, f) = *scalars.entry(b).or_insert_with(|| { + decls.extend(inst(OP_CONSTANT_TRUE, &[b, bound])); + decls.extend(inst(OP_CONSTANT_FALSE, &[b, bound + 1])); + bound += 2; + (bound - 2, bound - 1) + }); + let (vt, vf) = (bound, bound + 1); + bound += 2; + for (id, c) in [(vt, t), (vf, f)] { + let mut ops = vec![v, id]; + ops.extend(std::iter::repeat(c).take(k as usize)); + decls.extend(inst(OP_CONSTANT_COMPOSITE, &ops)); + } + consts.insert(v, (vt, vf)); + } + let mut out: Vec = Vec::with_capacity(words.len() + decls.len()); + out.extend_from_slice(&words[..5]); + let mut first_fn = true; + let mut i = 5; + while i < words.len() { + let n = (words[i] >> 16) as usize; + let o = words[i] & 0xffff; + let a = &words[i + 1..i + n]; + if o == OP_FUNCTION && first_fn { + first_fn = false; + out.extend_from_slice(&decls); + } + let logical = (o == OP_LOGICAL_AND || o == OP_LOGICAL_OR) && a.len() == 4; + match if logical { consts.get(&a[0]) } else { None } { + Some(&(vt, vf)) => { + let (accept, reject) = if o == OP_LOGICAL_AND { (a[3], vf) } else { (vt, a[3]) }; + out.extend(inst(OP_SELECT, &[a[0], a[1], a[2], accept, reject])); + } + None => out.extend_from_slice(&words[i..i + n]), + } + i += n; + } + out[3] = bound; + out +} + // One storage buffer bound through several views (llama.cpp: data_a as // float16_t[] and f16vec2[], data_b as float[] and vec4[]): WGSL allows one // variable per binding. When a binding has a scalar view diff --git a/vk/naga/test/run.ts b/vk/naga/test/run.ts index d25fc21..3b53ce2 100644 --- a/vk/naga/test/run.ts +++ b/vk/naga/test/run.ts @@ -207,6 +207,50 @@ check("drawparams.vert: BaseVertex/BaseInstance/DrawIndex read as 0", !!dp && !/ const fd = run("fastdiv.comp", "fastdiv.comp.spv", { stage: "compute", entryPoint: "main", pushGroup: 1, spec: { 0: 128 } }); check("fastdiv.comp: umulExtended lowered, std430 push array repacked, no inf, spec-sized shared array", !!fd && !/inf/i.test(fd.wgsl) && has(fd, /var \w+: kw_words;/) && has(fd, /array/) && has(fd, /@workgroup_size\(128, 1, 1\)/) && JSON.stringify(fd.requires) === "[]", fd?.wgsl.slice(0, 0)); +// GLSL.std.450 integer ops take their signedness from the opcode (#57): findMSB(uint) has an int +// result, and naga's SPIR-V writer emits UMin on i32 indices (u32 result) and on signed image +// coordinates. The same module with the unsigned ops on the signed values (each OpBitcast's +// source) and SMin as UMin: operands and results of the other signedness are bitcast. +const is = run("intsign.comp", "intsign.comp.spv", { stage: "compute", entryPoint: "main" }); +check("intsign.comp: FindUMsb's int result bitcast", has(is, /bitcast\(firstLeadingBit\(/), is?.wgsl); +{ + const w = new Uint32Array(Uint8Array.from(readFileSync(new URL("intsign.comp.spv", here))).buffer); + const src = new Map(); + for (let i = 5; i < w.length; i += w[i] >>> 16) if ((w[i] & 0xffff) === 124) src.set(w[i + 2], w[i + 3]); // OpBitcast + for (let i = 5; i < w.length; i += w[i] >>> 16) { + if ((w[i] & 0xffff) !== 12) continue; // OpExtInst + if (w[i + 4] === 39) w[i + 4] = 38; // SMin -> UMin + else if ([38, 41, 44].includes(w[i + 4])) for (let k = i + 5; k < i + (w[i] >>> 16); k++) w[k] = src.get(w[k]) ?? w[k]; + } + try { + out["intsign.mixed"] = t.translate(new Uint8Array(w.buffer), { stage: "compute", entryPoint: "main" }); + } catch (e) { + check("intsign.comp, mixed signedness: translates", false, (e as Error).message); + } + const r = out["intsign.mixed"]; + check("intsign.comp, mixed signedness: unsigned min/max/clamp on bitcast operands", ["min", "max", "clamp"].every((f) => has(r, new RegExp(`\\b${f}\\(bitcast\\(`))) && has(r, /min\(bitcast>\(/), r?.wgsl); + check("intsign.comp, mixed signedness: UMin on signed values clamps unsigned, result bitcast back", has(r, /bitcast\(min\(bitcast\(\w+\), bitcast\(/), r?.wgsl); +} + +// OpLogicalAnd/Or on bool vectors (naga's writer: its integer vector division guard, egui-wgpu 0.37), +// which spv-in types as scalars only: the module with its vector OpLogicalEqual as OpLogicalAnd and +// OpLogicalNotEqual as OpLogicalOr becomes selects; the scalar && stays. +run("boolvec.comp", "boolvec.comp.spv", { stage: "compute", entryPoint: "main" }); +{ + const w = new Uint32Array(Uint8Array.from(readFileSync(new URL("boolvec.comp.spv", here))).buffer); + for (let i = 5; i < w.length; i += w[i] >>> 16) { + if ((w[i] & 0xffff) === 164) w[i] = (w[i] & 0xffff0000) | 167; // OpLogicalEqual -> OpLogicalAnd + else if ((w[i] & 0xffff) === 165) w[i] = (w[i] & 0xffff0000) | 166; // OpLogicalNotEqual -> OpLogicalOr + } + try { + out["boolvec.logical"] = t.translate(new Uint8Array(w.buffer), { stage: "compute", entryPoint: "main" }); + } catch (e) { + check("boolvec.comp, vector LogicalAnd/Or: translates", false, (e as Error).message); + } + const r = out["boolvec.logical"]; + check("boolvec.comp, vector LogicalAnd/Or: as selects, scalar && kept", has(r, /select\(vec2\(false, false\), /) && has(r, /select\(\w+, vec2\(true, true\), /) && has(r, /&&/), r?.wgsl); +} + // A std430 push block WGSL's uniform address space cannot lay out // (Firefox and Safari refuse arrays of stride 4 there): vec4 words, // run below with known bytes. A block that fits keeps its struct. @@ -589,6 +633,10 @@ const pipelines: [string, string, string | undefined][] = [ ["fastdiv", "fastdiv.comp", undefined], ["small", "small.comp", undefined], ["zerodiv", "zerodiv.comp", undefined], + ["intsign", "intsign.comp", undefined], + ["intsign.mixed", "intsign.mixed", undefined], + ["boolvec", "boolvec.comp", undefined], + ["boolvec.logical", "boolvec.logical", undefined], ["barriercont", "barriercont.comp", undefined], ["texel", "texel.vert.spv", "texel.frag.spv"], ["texel.comp", "texel.comp.spv", undefined], diff --git a/vk/naga/test/shaders/boolvec.comp b/vk/naga/test/shaders/boolvec.comp new file mode 100644 index 0000000..3d41974 --- /dev/null +++ b/vk/naga/test/shaders/boolvec.comp @@ -0,0 +1,17 @@ +#version 450 +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +// Logical ops on bool vectors. run.ts also translates this module with +// equal(bvec2, bvec2) as OpLogicalAnd and notEqual as OpLogicalOr, which +// GLSL cannot write but naga's SPIR-V writer emits (its guard of an integer +// vector division: egui-wgpu 0.37's fragment shaders, FilmCraft). +layout(local_size_x = 1) in; +layout(std430, binding = 0) buffer B { ivec2 a; ivec2 b; ivec2 r; }; +void main() { + bvec2 x = equal(a, b); + bvec2 y = lessThan(a, b); + bvec2 e = equal(x, y); + bvec2 o = notEqual(x, y); + bool s = x.x && y.y; + r = ivec2(e) + 2 * ivec2(o) + ivec2(s); +} diff --git a/vk/naga/test/shaders/boolvec.comp.opt.spv b/vk/naga/test/shaders/boolvec.comp.opt.spv new file mode 100644 index 0000000..44f1e04 Binary files /dev/null and b/vk/naga/test/shaders/boolvec.comp.opt.spv differ diff --git a/vk/naga/test/shaders/boolvec.comp.spv b/vk/naga/test/shaders/boolvec.comp.spv new file mode 100644 index 0000000..bc73aae Binary files /dev/null and b/vk/naga/test/shaders/boolvec.comp.spv differ diff --git a/vk/naga/test/shaders/intsign.comp b/vk/naga/test/shaders/intsign.comp new file mode 100644 index 0000000..a5f6b22 --- /dev/null +++ b/vk/naga/test/shaders/intsign.comp @@ -0,0 +1,20 @@ +#version 450 +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +// GLSL.std.450 integer ops take their signedness from the opcode. run.ts +// also translates this module with the unsigned ops on the signed values +// directly and SMin as UMin, as naga's SPIR-V writer emits its bounds +// checks (FilmCraft, #57). +layout(local_size_x = 1) in; +layout(std430, binding = 0) buffer B { int s[8]; uint u[8]; ivec2 sv; uvec2 uv; }; +void main() { + int a = s[0]; + uint b = u[0]; + u[1] = min(uint(a), b); + u[2] = max(uint(a), b); + u[3] = clamp(uint(a), b, 7u); + uv = min(uvec2(sv), uv); + s[1] = min(a, s[2]); + s[3] = findMSB(uint(a)); + s[4] = abs(a); +} diff --git a/vk/naga/test/shaders/intsign.comp.opt.spv b/vk/naga/test/shaders/intsign.comp.opt.spv new file mode 100644 index 0000000..af2c126 Binary files /dev/null and b/vk/naga/test/shaders/intsign.comp.opt.spv differ diff --git a/vk/naga/test/shaders/intsign.comp.spv b/vk/naga/test/shaders/intsign.comp.spv new file mode 100644 index 0000000..286e764 Binary files /dev/null and b/vk/naga/test/shaders/intsign.comp.spv differ