zdxc: SM 6.10 LinAlg in libraries

Write each library function's RDAT ExtendedProperties the way dxc's
AddLinAlgFunctionProperties does: matrix constructions with their
operation shapes, thread mat-vec multiplies, wave and thread-group
matrix multiplies, outer products and accumulating stores, merged from
callees, in the extended property record tables (part types 13-20)
with record deduplication. Removes the library LinAlg gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-11-01 00:07:09 -07:00
parent edddf5e5f8
commit 506d9c0b9d
4 changed files with 308 additions and 109 deletions

View File

@ -4495,12 +4495,17 @@ const Emitter = struct {
/// What the module does with matrices (PSV0), when it has any.
fn linAlgTables(e: *Emitter) Error!?linalg_info.Tables {
if (!e.uses_linalg) return null;
return try linalg_info.collect(e.arena, &e.dm, try e.linAlgMatrices());
}
/// Each matrix type's attributes.
fn linAlgMatrices(e: *Emitter) Error!linalg_info.Matrices {
const mats = try e.arena.alloc(struct { module.TypeId, linalg_info.Matrix }, e.linalg_types.items.len);
for (mats, e.linalg_types.items) |*m, x| {
const la = e.t.get(x.ty).linalg;
m.* = .{ x.dty, .{ .comp = la.comp, .m = la.m, .n = la.n, .use = la.use, .scope = la.scope } };
}
return try linalg_info.collect(e.arena, &e.dm, mats);
return mats;
}
/// `!dx.targetTypes`: each matrix type with its attributes.
@ -4925,8 +4930,6 @@ const Emitter = struct {
}
fn writeLibraryModule(e: *Emitter, funcs: []const LibFunc) Error![]u8 {
// (RDAT's per-function linear algebra properties are not written.)
if (e.uses_linalg) return e.unsupported("linear algebra in libraries is not supported yet", .{});
const dm = &e.dm;
const mdI32 = struct {
fn f(m: *module.Module, v: i64) !module.MdId {
@ -5028,6 +5031,7 @@ const Emitter = struct {
if (r.lib_global) |lg| try res_index.put(e.arena, lg, count);
count += 1;
};
const mats = try e.linAlgMatrices();
for (funcs, analysis.infos) |lf, info| {
const f = &e.dm.functions.items[lf.func];
const name = try b.string(lf.name);
@ -5040,11 +5044,13 @@ const Emitter = struct {
}
};
std.mem.sort(u32, used.items, {}, std.sort.asc(u32));
const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref;
const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref;
const kind = shaderKind(lf.stage);
try b.addFunction(.{
.name = name,
.unmangled_name = unmangled,
.resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref,
.resources = resources,
.shader_kind = kind,
.payload_size = lf.payload_size,
.attribute_size = lf.attr_size,
@ -5052,6 +5058,7 @@ const Emitter = struct {
.feature_info2 = @truncate(libinfo.featureInfo(info.flags) >> 32),
.shader_stage_flag = if (lf.stage == .library) info.mask & 0xffff else info.mask & (@as(u32, 1) << @intCast(kind)),
.min_shader_target = (kind << 16) | (6 << 4) | libinfo.minMinor(info, if (lf.stage == .library) null else kind),
.extended_properties = props,
});
}
for (e.m.subobjects.items) |so| {

View File

@ -6,6 +6,7 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const rdat = @import("rdat.zig");
/// A matrix type's attributes (`!dx.targetTypes`).
pub const Matrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
@ -35,7 +36,7 @@ const Key2 = [2]u8;
const Key3 = [3]u8;
const Key4 = [4]u8;
const Info = struct {
pub const Info = struct {
constructions: std.AutoArrayHashMapUnmanaged(Key2, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
matvec: std.AutoArrayHashMapUnmanaged(Key3, u8) = .empty,
multiplies: std.AutoArrayHashMapUnmanaged(Key4, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
@ -46,13 +47,39 @@ const Info = struct {
const transposed: u8 = 1;
const non_mul_optimal: u8 = 2;
pub const Matrices = []const struct { module.TypeId, Matrix };
/// Collects the usage in every function of `m`; `matrices` maps matrix
/// types to their attributes.
pub fn collect(a: Allocator, m: *const module.Module, matrices: []const struct { module.TypeId, Matrix }) Allocator.Error!Tables {
pub fn collect(a: Allocator, m: *const module.Module, matrices: Matrices) Allocator.Error!Tables {
var info: Info = .{};
const c: C = .{ .m = m, .mats = matrices };
for (m.functions.items) |*f| try collectFunction(a, c, &info, f);
return serialize(a, &info);
}
/// The usage of function `func` and of the functions it calls (dxc merges
/// callee usage into callers).
pub fn functionInfo(a: Allocator, m: *const module.Module, matrices: Matrices, func: u32) Allocator.Error!Info {
var info: Info = .{};
const c: C = .{ .m = m, .mats = matrices };
var seen: std.AutoArrayHashMapUnmanaged(u32, void) = .empty;
try seen.put(a, func, {});
var k: usize = 0;
while (k < seen.count()) : (k += 1) {
const f = &m.functions.items[seen.keys()[k]];
try collectFunction(a, c, &info, f);
for (f.insts.items) |inst| if (inst.op == .call) {
const callee = inst.op.call.callee;
if (m.functions.items[callee].num_blocks > 0) try seen.put(a, callee, {});
};
}
return info;
}
const C = struct {
m: *const module.Module,
mats: []const struct { module.TypeId, Matrix },
mats: Matrices,
fn matrix(c: @This(), ty: ?module.TypeId) ?Matrix {
const t = ty orelse return null;
@ -89,8 +116,9 @@ pub fn collect(a: Allocator, m: *const module.Module, matrices: []const struct {
};
}
};
const c: C = .{ .m = m, .mats = matrices };
for (m.functions.items) |*f| {
fn collectFunction(a: Allocator, c: C, info: *Info, f: *const module.Function) Allocator.Error!void {
const m = c.m;
const fty = m.types.items[f.ty].function;
const typeOf = struct {
fn t(mm: *const module.Module, ff: *const module.Function, ft: @FieldType(module.Type, "function"), v: module.Value) ?module.TypeId {
@ -150,14 +178,12 @@ pub fn collect(a: Allocator, m: *const module.Module, matrices: []const struct {
gop.value_ptr.* |= 1;
},
else => {
try construction(a, &info, c.matrix(inst.ty));
for (call.args, 0..) |_, k| try construction(a, &info, c.matrix(arg(c, f, fty, call.args, k)));
try construction(a, info, c.matrix(inst.ty));
for (call.args, 0..) |_, k| try construction(a, info, c.matrix(arg(c, f, fty, call.args, k)));
},
}
}
}
return serialize(a, &info);
}
fn construction(a: Allocator, info: *Info, mat: ?Matrix) Allocator.Error!void {
const x = mat orelse return;
@ -309,3 +335,66 @@ pub fn psvBlock(a: Allocator, t: Tables, out: *std.ArrayList(u8)) Allocator.Erro
try out.appendSlice(a, r);
};
}
/// AddLinAlgShapes: the shape records' index array.
fn rdatShapes(a: Allocator, b: *rdat.Builder, set: std.AutoArrayHashMapUnmanaged(Shape, void)) Allocator.Error!u32 {
var idx: std.ArrayList(u32) = .empty;
for (try sortedShapes(a, set)) |s| {
var rec: [12]u8 = undefined;
for ([_]u32{ s.m, s.n, s.k }, 0..) |v, k| std.mem.writeInt(u32, rec[4 * k ..][0..4], v, .little);
try idx.append(a, try b.record(.shapes, &rec));
}
return b.array(idx.items);
}
/// A record with an index array reference, then four bytes.
fn refRecord(ref: u32, tail: [4]u8) [8]u8 {
var rec: [8]u8 = undefined;
std.mem.writeInt(u32, rec[0..4], ref, .little);
rec[4..8].* = tail;
return rec;
}
/// The function's RDAT ExtendedProperties (dxc's
/// AddLinAlgFunctionProperties): one property per non-empty kind, in
/// FunctionPropertyType order.
pub fn rdatProperties(a: Allocator, b: *rdat.Builder, info: *const Info) Allocator.Error!u32 {
var props: std.ArrayList(u32) = .empty;
var recs: std.ArrayList(u32) = .empty;
const flush = struct {
fn f(aa: Allocator, bb: *rdat.Builder, ps: *std.ArrayList(u32), rs: *std.ArrayList(u32), ty: u32) Allocator.Error!void {
if (rs.items.len == 0) return;
var arr: [4]u8 = undefined;
std.mem.writeInt(u32, &arr, try bb.array(rs.items), .little);
try ps.append(aa, try bb.record(.properties, &refRecord(ty, arr)));
rs.clearRetainingCapacity();
}
}.f;
for (try sortedKeys(Key2, a, info.constructions.keys())) |k| {
const shapes = try rdatShapes(a, b, info.constructions.get(k).?);
try recs.append(a, try b.record(.constructions, &refRecord(shapes, .{ k[0], 0, 0, 0 })));
}
try flush(a, b, &props, &recs, 1);
for (try sortedKeys(Key3, a, info.matvec.keys())) |k| {
try recs.append(a, try b.record(.thread_matvec, &.{ k[0], k[1], k[2], info.matvec.get(k).? }));
}
try flush(a, b, &props, &recs, 2);
const mul_keys = try sortedKeys(Key4, a, info.multiplies.keys());
for ([_]u8{ 1, 2 }, [_]rdat.Ext{ .wave_multiplies, .group_multiplies }, [_]u32{ 3, 4 }) |scope, t, ty| {
for (mul_keys) |k| if (k[0] == scope) {
const shapes = try rdatShapes(a, b, info.multiplies.get(k).?);
try recs.append(a, try b.record(t, &refRecord(shapes, .{ k[1], k[2], k[3], 0 })));
};
try flush(a, b, &props, &recs, ty);
}
for (try sortedKeys(Key2, a, info.outer.keys())) |k| {
try recs.append(a, try b.record(.outer_products, &.{ k[0], k[1], 0, 0 }));
}
try flush(a, b, &props, &recs, 5);
for (try sortedKeys(u8, a, info.accumulate.keys())) |k| {
try recs.append(a, try b.record(.accumulate_stores, &.{ k, info.accumulate.get(k).?, 0, 0 }));
}
try flush(a, b, &props, &recs, 6);
if (props.items.len == 0) return rdat.null_ref;
return b.array(props.items);
}

View File

@ -5,7 +5,8 @@
//! Layout: a header (version, part count), part offsets, then each
//! non-empty part as (type, size) and its 4-byte aligned contents. Parts
//! come in the order dxc adds them: strings, resources, functions, index
//! arrays, raw bytes, subobjects (only the first four are produced here).
//! arrays, raw bytes, subobjects, then the record tables of the extended
//! function properties (SM 6.10 linear algebra).
const std = @import("std");
const Allocator = std.mem.Allocator;
@ -43,6 +44,28 @@ pub const Function = struct {
extended_properties: u32 = null_ref,
};
/// The extended function property tables, in part order (part types
/// 13..20).
pub const Ext = enum(u32) {
properties = 13,
shapes,
constructions,
thread_matvec,
wave_multiplies,
group_multiplies,
outer_products,
accumulate_stores,
/// Record size in bytes.
pub fn stride(t: Ext) usize {
return switch (t) {
.shapes => 12,
.properties, .constructions, .wave_multiplies, .group_multiplies => 8,
.thread_matvec, .outer_products, .accumulate_stores => 4,
};
}
};
pub const Builder = struct {
gpa: Allocator,
strings: std.ArrayList(u8) = .empty,
@ -52,6 +75,7 @@ pub const Builder = struct {
functions: std.ArrayList([14]u32) = .empty,
raw: std.ArrayList(u8) = .empty,
subobjects: std.ArrayList([6]u32) = .empty,
ext: [8]std.ArrayList(u8) = @splat(.empty),
pub fn init(gpa: Allocator) Allocator.Error!Builder {
var b: Builder = .{ .gpa = gpa };
@ -104,6 +128,19 @@ pub const Builder = struct {
try b.subobjects.append(b.gpa, rec);
}
/// Index of a record in table `t`; an identical record is shared
/// (record deduplication, validator 1.7+).
pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 {
std.debug.assert(rec.len == t.stride());
const tab = &b.ext[@intFromEnum(t) - 13];
var at: usize = 0;
while (at < tab.items.len) : (at += rec.len) {
if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len);
}
try tab.appendSlice(b.gpa, rec);
return @intCast(at / rec.len);
}
/// Offset of `bytes` in the raw bytes part.
pub fn bytes(b: *Builder, data: []const u8) Allocator.Error!u32 {
const off: u32 = @intCast(b.raw.items.len);
@ -139,6 +176,12 @@ pub const Builder = struct {
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 6, .data = t });
}
for (b.ext, 13..) |rows, ty| if (rows.items.len > 0) {
const stride = @as(Ext, @enumFromInt(ty)).stride();
const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride);
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t });
};
var size: usize = 8 + 4 * parts.items.len;
for (parts.items) |p| size += 8 + std.mem.alignForward(usize, p.data.len, 4);
@ -174,6 +217,7 @@ pub const Builder = struct {
b.functions.deinit(b.gpa);
b.raw.deinit(b.gpa);
b.subobjects.deinit(b.gpa);
for (&b.ext) |*t| t.deinit(b.gpa);
}
};

View File

@ -0,0 +1,59 @@
// PROFILE: lib_6_10
// SM 6.10 linear algebra in a library: each function's RDAT
// ExtendedProperties (constructions with their shapes, matrix multiplies,
// outer products and accumulating stores), shared between functions with
// the same usage, must match dxc's byte for byte.
// ZCHECK: @dx.op.linAlgMatrixMultiply.mC4M5N6U2S2.mC4M5N7U0S2.mC5M7N6U1S2(i32 334,
// ZCHECK: @dx.op.linAlgMatrixOuterProduct.mC9M4N4U2S0.v4f32.v4f32(i32 340,
// ZCHECK: @dx.op.linAlgVectorAccumulateToDescriptor.v4f32(i32 342,
// ZCHECK: !dx.targetTypes = !{
#include <dx/linalg.h>
using namespace dx::linalg;
using WaveA = Matrix<ComponentType::F32, 2, 4, MatrixUse::A, MatrixScope::Wave>;
using WaveB = Matrix<ComponentType::I32, 4, 3, MatrixUse::B, MatrixScope::Wave>;
using WaveAcc = Matrix<ComponentType::F32, 2, 3, MatrixUse::Accumulator, MatrixScope::Wave>;
using GroupA = Matrix<ComponentType::I32, 5, 7, MatrixUse::A, MatrixScope::ThreadGroup>;
using GroupB = Matrix<ComponentType::U32, 7, 6, MatrixUse::B, MatrixScope::ThreadGroup>;
using GroupAcc = Matrix<ComponentType::I32, 5, 6, MatrixUse::Accumulator, MatrixScope::ThreadGroup>;
RWByteAddressBuffer Output : register(u0);
void WaveWork(float f, int i) {
WaveA A = WaveA::Splat(f);
WaveB B = WaveB::Splat(i);
WaveAcc C = Multiply<ComponentType::F32>(A, B);
C.InterlockedAccumulate(Output, 0, 12, MatrixLayout::RowMajor);
}
[shader("compute")]
[numthreads(32, 1, 1)]
void Wave1() { WaveWork(1.0f, 2); }
[shader("compute")]
[numthreads(32, 1, 1)]
void Wave2() { WaveWork(3.0f, 4); }
[shader("compute")]
[numthreads(64, 1, 1)]
void Group() {
GroupA A = GroupA::Splat(5);
GroupB B = GroupB::Splat(6u);
GroupAcc C = Multiply<ComponentType::I32>(A, B);
C.InterlockedAccumulate(Output, 64, 24, MatrixLayout::RowMajor);
WaveWork(5.0f, 6);
}
[shader("compute")]
[numthreads(1, 1, 1)]
void Outer(uint i : SV_GroupIndex) {
float4 v = float4(i, 1, 2, 3);
Matrix<ComponentType::F32, 4, 4, MatrixUse::Accumulator, MatrixScope::Thread> M =
OuterProduct<ComponentType::F32>(v, v);
M.InterlockedAccumulate(Output, 128);
InterlockedAccumulate(Output, 256, v);
}
[shader("compute")]
[numthreads(1, 1, 1)]
void NoLinAlg() { Output.Store(0, 1u); }