M0.1: HLSL preprocessor matching dxc -P across the DXC test corpus
- Source manager (line splicing, UTF-8 BOM) and clang-style diagnostics. - Lexer producing preprocessing tokens. - Preprocessor modelled on clang's: object and function-like macros, #/##, variadics with GNU comma elision, painted recursion blocking, nested argument pre-expansion, #if/#elif expressions, #include with -I and #pragma once, #line, #error/#warning, pass-through #pragma, and dxc's predefined macros (__HLSL_VERSION, __SHADER_TARGET_*, __spirv__, ...). - dxc's compiled-in HLSL headers (<dx/linalg.h>, <vk/spirv.h>, ...) are vendored as data and used as the fallback for angled includes. - -P/-Fi/-D/-I/-HV 2021/-enable-16bit-types options; profiles now cover lib_, ms_, as_ and SM 6.0-6.11. - `zig build oracle-pp`: token-for-token comparison with dxc -P. 2060 of 2060 corpus files dxc accepts match.
This commit is contained in:
parent
de2e3da34a
commit
fb322f24a7
13
build.zig
13
build.zig
|
|
@ -4,10 +4,16 @@ pub fn build(b: *std.Build) void {
|
||||||
const target = b.standardTargetOptions(.{});
|
const target = b.standardTargetOptions(.{});
|
||||||
const optimize = b.standardOptimizeOption(.{});
|
const optimize = b.standardOptimizeOption(.{});
|
||||||
|
|
||||||
|
const hlsl_headers = b.createModule(.{
|
||||||
|
.root_source_file = b.path("vendor/hlsl_headers.zig"),
|
||||||
|
.target = target,
|
||||||
|
.optimize = optimize,
|
||||||
|
});
|
||||||
const mod = b.addModule("zdxc", .{
|
const mod = b.addModule("zdxc", .{
|
||||||
.root_source_file = b.path("src/root.zig"),
|
.root_source_file = b.path("src/root.zig"),
|
||||||
.target = target,
|
.target = target,
|
||||||
.optimize = optimize,
|
.optimize = optimize,
|
||||||
|
.imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }},
|
||||||
});
|
});
|
||||||
|
|
||||||
const exe = b.addExecutable(.{
|
const exe = b.addExecutable(.{
|
||||||
|
|
@ -40,4 +46,11 @@ pub fn build(b: *std.Build) void {
|
||||||
oracle.setCwd(b.path("."));
|
oracle.setCwd(b.path("."));
|
||||||
oracle.has_side_effects = true;
|
oracle.has_side_effects = true;
|
||||||
oracle_step.dependOn(&oracle.step);
|
oracle_step.dependOn(&oracle.step);
|
||||||
|
|
||||||
|
const oracle_pp_step = b.step("oracle-pp", "Compare zdxc -P with dxc -P over the DXC test corpus");
|
||||||
|
const oracle_pp = b.addSystemCommand(&.{ "sh", "test/oracle/pp.sh" });
|
||||||
|
oracle_pp.addArtifactArg(exe);
|
||||||
|
oracle_pp.setCwd(b.path("."));
|
||||||
|
oracle_pp.has_side_effects = true;
|
||||||
|
oracle_pp_step.dependOn(&oracle_pp.step);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
//! Diagnostics: collected during compilation and rendered clang-style.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const source = @import("front/source.zig");
|
||||||
|
|
||||||
|
pub const Severity = enum {
|
||||||
|
note,
|
||||||
|
warning,
|
||||||
|
@"error",
|
||||||
|
fatal,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Diagnostic = struct {
|
||||||
|
severity: Severity,
|
||||||
|
loc: source.Loc,
|
||||||
|
message: []const u8,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Diagnostics = struct {
|
||||||
|
arena: std.heap.ArenaAllocator,
|
||||||
|
list: std.ArrayList(Diagnostic) = .empty,
|
||||||
|
error_count: u32 = 0,
|
||||||
|
warning_count: u32 = 0,
|
||||||
|
/// -WX
|
||||||
|
warnings_as_errors: bool = false,
|
||||||
|
/// -no-warnings
|
||||||
|
suppress_warnings: bool = false,
|
||||||
|
|
||||||
|
pub fn init(gpa: Allocator) Diagnostics {
|
||||||
|
return .{ .arena = .init(gpa) };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(d: *Diagnostics) void {
|
||||||
|
d.arena.deinit();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(d: *Diagnostics, severity: Severity, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
|
var sev = severity;
|
||||||
|
if (sev == .warning) {
|
||||||
|
if (d.suppress_warnings) return;
|
||||||
|
if (d.warnings_as_errors) sev = .@"error";
|
||||||
|
}
|
||||||
|
const a = d.arena.allocator();
|
||||||
|
const msg = std.fmt.allocPrint(a, fmt, args) catch "out of memory formatting diagnostic";
|
||||||
|
d.list.append(a, .{ .severity = sev, .loc = loc, .message = msg }) catch return;
|
||||||
|
switch (sev) {
|
||||||
|
.@"error", .fatal => d.error_count += 1,
|
||||||
|
.warning => d.warning_count += 1,
|
||||||
|
.note => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn err(d: *Diagnostics, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
|
d.add(.@"error", loc, fmt, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn warn(d: *Diagnostics, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
|
d.add(.warning, loc, fmt, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hasErrors(d: *const Diagnostics) bool {
|
||||||
|
return d.error_count != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render all diagnostics as `file:line:col: error: message` followed by
|
||||||
|
/// the source line and a caret.
|
||||||
|
pub fn render(d: *const Diagnostics, sm: *const source.SourceManager, w: *std.Io.Writer) !void {
|
||||||
|
for (d.list.items) |diag| {
|
||||||
|
if (diag.loc.isNone()) {
|
||||||
|
try w.print("{s}: {s}\n", .{ @tagName(diag.severity), diag.message });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const f = sm.file(diag.loc.file);
|
||||||
|
const lc = sm.lineCol(diag.loc);
|
||||||
|
try w.print("{s}:{d}:{d}: {s}: {s}\n", .{ f.path, lc.line, lc.col, @tagName(diag.severity), diag.message });
|
||||||
|
const line = sm.lineText(diag.loc);
|
||||||
|
try w.print("{s}\n", .{line});
|
||||||
|
for (0..lc.col - 1) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
|
||||||
|
try w.writeAll("^\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -13,6 +13,9 @@ pub const ShaderKind = enum(u8) {
|
||||||
hull = 3,
|
hull = 3,
|
||||||
domain = 4,
|
domain = 4,
|
||||||
compute = 5,
|
compute = 5,
|
||||||
|
library = 6,
|
||||||
|
mesh = 13,
|
||||||
|
amplification = 14,
|
||||||
|
|
||||||
pub fn profilePrefix(k: ShaderKind) []const u8 {
|
pub fn profilePrefix(k: ShaderKind) []const u8 {
|
||||||
return switch (k) {
|
return switch (k) {
|
||||||
|
|
@ -22,22 +25,41 @@ pub const ShaderKind = enum(u8) {
|
||||||
.hull => "hs",
|
.hull => "hs",
|
||||||
.domain => "ds",
|
.domain => "ds",
|
||||||
.compute => "cs",
|
.compute => "cs",
|
||||||
|
.library => "lib",
|
||||||
|
.mesh => "ms",
|
||||||
|
.amplification => "as",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Highest shader model minor version accepted (matches the oracle dxc).
|
||||||
|
pub const max_minor = 11;
|
||||||
|
|
||||||
pub const Profile = struct {
|
pub const Profile = struct {
|
||||||
kind: ShaderKind,
|
kind: ShaderKind,
|
||||||
major: u8,
|
major: u8,
|
||||||
minor: u8,
|
minor: u8,
|
||||||
|
|
||||||
|
/// Parses `<stage>_6_<minor>`, e.g. `cs_6_6` or `lib_6_10`.
|
||||||
pub fn parse(s: []const u8) ?Profile {
|
pub fn parse(s: []const u8) ?Profile {
|
||||||
if (s.len != 6 or s[2] != '_' or s[4] != '_') return null;
|
var it = std.mem.splitScalar(u8, s, '_');
|
||||||
|
const prefix = it.next() orelse return null;
|
||||||
|
const major_str = it.next() orelse return null;
|
||||||
|
const minor_str = it.next() orelse return null;
|
||||||
|
if (it.next() != null) return null;
|
||||||
const kind: ShaderKind = for (std.enums.values(ShaderKind)) |k| {
|
const kind: ShaderKind = for (std.enums.values(ShaderKind)) |k| {
|
||||||
if (std.mem.eql(u8, s[0..2], k.profilePrefix())) break k;
|
if (std.mem.eql(u8, prefix, k.profilePrefix())) break k;
|
||||||
} else return null;
|
} else return null;
|
||||||
if (s[3] != '6' or s[5] < '0' or s[5] > '9') return null;
|
if (!std.mem.eql(u8, major_str, "6")) return null;
|
||||||
return .{ .kind = kind, .major = 6, .minor = s[5] - '0' };
|
const minor = std.fmt.parseInt(u8, minor_str, 10) catch return null;
|
||||||
|
if (minor > max_minor) return null;
|
||||||
|
const min_minor: u8 = switch (kind) {
|
||||||
|
.library => 1,
|
||||||
|
.mesh, .amplification => 5,
|
||||||
|
else => 0,
|
||||||
|
};
|
||||||
|
if (minor < min_minor) return null;
|
||||||
|
return .{ .kind = kind, .major = 6, .minor = minor };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -157,5 +179,7 @@ test "profile parsing" {
|
||||||
try std.testing.expectEqual(ShaderKind.compute, p.kind);
|
try std.testing.expectEqual(ShaderKind.compute, p.kind);
|
||||||
try std.testing.expectEqual(@as(u8, 6), p.minor);
|
try std.testing.expectEqual(@as(u8, 6), p.minor);
|
||||||
try std.testing.expect(Profile.parse("cs_5_0") == null);
|
try std.testing.expect(Profile.parse("cs_5_0") == null);
|
||||||
try std.testing.expect(Profile.parse("lib_6_3") == null);
|
try std.testing.expectEqual(ShaderKind.library, Profile.parse("lib_6_3").?.kind);
|
||||||
|
try std.testing.expectEqual(@as(u8, 10), Profile.parse("cs_6_10").?.minor);
|
||||||
|
try std.testing.expect(Profile.parse("ms_6_4") == null);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,365 @@
|
||||||
|
//! HLSL lexer producing preprocessing tokens. Keywords are not distinguished
|
||||||
|
//! here; the parser classifies identifiers.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const source = @import("source.zig");
|
||||||
|
|
||||||
|
pub const Kind = enum(u8) {
|
||||||
|
eof,
|
||||||
|
/// Unlexable input (stray character, unterminated literal).
|
||||||
|
invalid,
|
||||||
|
identifier,
|
||||||
|
/// pp-number: integer and floating literals with suffixes.
|
||||||
|
number,
|
||||||
|
string,
|
||||||
|
char,
|
||||||
|
/// Produced by the preprocessor for `#pragma` lines; text holds the
|
||||||
|
/// pragma body.
|
||||||
|
pragma,
|
||||||
|
|
||||||
|
l_paren,
|
||||||
|
r_paren,
|
||||||
|
l_brace,
|
||||||
|
r_brace,
|
||||||
|
l_square,
|
||||||
|
r_square,
|
||||||
|
semi,
|
||||||
|
comma,
|
||||||
|
colon,
|
||||||
|
colon_colon,
|
||||||
|
question,
|
||||||
|
period,
|
||||||
|
ellipsis,
|
||||||
|
arrow,
|
||||||
|
plus,
|
||||||
|
plus_plus,
|
||||||
|
plus_equal,
|
||||||
|
minus,
|
||||||
|
minus_minus,
|
||||||
|
minus_equal,
|
||||||
|
star,
|
||||||
|
star_equal,
|
||||||
|
slash,
|
||||||
|
slash_equal,
|
||||||
|
percent,
|
||||||
|
percent_equal,
|
||||||
|
amp,
|
||||||
|
amp_amp,
|
||||||
|
amp_equal,
|
||||||
|
pipe,
|
||||||
|
pipe_pipe,
|
||||||
|
pipe_equal,
|
||||||
|
caret,
|
||||||
|
caret_equal,
|
||||||
|
tilde,
|
||||||
|
exclaim,
|
||||||
|
exclaim_equal,
|
||||||
|
equal,
|
||||||
|
equal_equal,
|
||||||
|
less,
|
||||||
|
less_equal,
|
||||||
|
less_less,
|
||||||
|
less_less_equal,
|
||||||
|
greater,
|
||||||
|
greater_equal,
|
||||||
|
greater_greater,
|
||||||
|
greater_greater_equal,
|
||||||
|
hash,
|
||||||
|
hash_hash,
|
||||||
|
|
||||||
|
pub fn isPunct(k: Kind) bool {
|
||||||
|
return @backingInt(k) >= @backingInt(Kind.l_paren);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Flags = packed struct(u8) {
|
||||||
|
/// First token on its (physical) line.
|
||||||
|
bol: bool = false,
|
||||||
|
/// Preceded by whitespace or a comment.
|
||||||
|
space: bool = false,
|
||||||
|
/// Painted by the preprocessor: never macro-expand this identifier.
|
||||||
|
no_expand: bool = false,
|
||||||
|
_: u5 = 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Token = struct {
|
||||||
|
kind: Kind,
|
||||||
|
flags: Flags = .{},
|
||||||
|
/// Spelling. Points into the source text, or into preprocessor-owned
|
||||||
|
/// memory for tokens created by `#` and `##`.
|
||||||
|
text: []const u8,
|
||||||
|
loc: source.Loc,
|
||||||
|
|
||||||
|
pub fn is(t: Token, kind: Kind) bool {
|
||||||
|
return t.kind == kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn isIdent(t: Token, name: []const u8) bool {
|
||||||
|
return t.kind == .identifier and std.mem.eql(u8, t.text, name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Lexer = struct {
|
||||||
|
text: []const u8,
|
||||||
|
file: source.FileId,
|
||||||
|
pos: u32 = 0,
|
||||||
|
at_bol: bool = true,
|
||||||
|
|
||||||
|
pub fn init(text: []const u8, file: source.FileId) Lexer {
|
||||||
|
return .{ .text = text, .file = file };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peekAt(l: *const Lexer, i: usize) u8 {
|
||||||
|
return if (i < l.text.len) l.text[i] else 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Skip whitespace and comments; report whether any was seen and whether
|
||||||
|
/// a newline was crossed.
|
||||||
|
fn skipTrivia(l: *Lexer) struct { space: bool, newline: bool } {
|
||||||
|
var space = false;
|
||||||
|
var newline = false;
|
||||||
|
while (l.pos < l.text.len) {
|
||||||
|
const c = l.text[l.pos];
|
||||||
|
switch (c) {
|
||||||
|
' ', '\t', '\r', 0x0b, 0x0c => {
|
||||||
|
space = true;
|
||||||
|
l.pos += 1;
|
||||||
|
},
|
||||||
|
'\n' => {
|
||||||
|
newline = true;
|
||||||
|
space = false;
|
||||||
|
l.pos += 1;
|
||||||
|
},
|
||||||
|
'/' => {
|
||||||
|
const n = l.peekAt(l.pos + 1);
|
||||||
|
if (n == '/') {
|
||||||
|
while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1;
|
||||||
|
space = true;
|
||||||
|
} else if (n == '*') {
|
||||||
|
l.pos += 2;
|
||||||
|
// A newline inside a block comment does not start a
|
||||||
|
// new line for directive purposes (the comment is one
|
||||||
|
// space after translation phase 3).
|
||||||
|
while (l.pos < l.text.len) : (l.pos += 1) {
|
||||||
|
if (l.text[l.pos] == '*' and l.peekAt(l.pos + 1) == '/') {
|
||||||
|
l.pos += 2;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Unterminated block comment: consume to EOF.
|
||||||
|
}
|
||||||
|
space = true;
|
||||||
|
} else break;
|
||||||
|
},
|
||||||
|
else => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return .{ .space = space, .newline = newline };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next(l: *Lexer) Token {
|
||||||
|
const trivia = l.skipTrivia();
|
||||||
|
if (trivia.newline) l.at_bol = true;
|
||||||
|
var flags: Flags = .{ .bol = l.at_bol, .space = trivia.space };
|
||||||
|
if (l.at_bol) flags.space = false;
|
||||||
|
l.at_bol = false;
|
||||||
|
const start = l.pos;
|
||||||
|
const kind = l.lexToken();
|
||||||
|
return .{
|
||||||
|
.kind = kind,
|
||||||
|
.flags = flags,
|
||||||
|
.text = l.text[start..l.pos],
|
||||||
|
.loc = .{ .file = l.file, .offset = start },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rest of the current line, used for `#error`, `#pragma` and similar.
|
||||||
|
/// Leaves the lexer at the newline.
|
||||||
|
pub fn restOfLine(l: *Lexer) []const u8 {
|
||||||
|
const start = l.pos;
|
||||||
|
while (l.pos < l.text.len and l.text[l.pos] != '\n') {
|
||||||
|
// Block comments may contain newlines; skip them as a unit.
|
||||||
|
if (l.text[l.pos] == '/' and l.peekAt(l.pos + 1) == '*') {
|
||||||
|
if (std.mem.indexOfPos(u8, l.text, l.pos + 2, "*/")) |end| {
|
||||||
|
l.pos = @intCast(end + 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (l.text[l.pos] == '/' and l.peekAt(l.pos + 1) == '/') {
|
||||||
|
const s = l.text[start..l.pos];
|
||||||
|
while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1;
|
||||||
|
return std.mem.trim(u8, s, " \t\r");
|
||||||
|
}
|
||||||
|
l.pos += 1;
|
||||||
|
}
|
||||||
|
return std.mem.trim(u8, l.text[start..l.pos], " \t\r");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After `#include`, lex `<...>` as a header name. Returns null if the
|
||||||
|
/// next token does not start with `<`.
|
||||||
|
pub fn headerName(l: *Lexer) ?Token {
|
||||||
|
const trivia = l.skipTrivia();
|
||||||
|
if (trivia.newline) {
|
||||||
|
l.at_bol = true;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (l.peekAt(l.pos) != '<') return null;
|
||||||
|
const start = l.pos;
|
||||||
|
var i = l.pos + 1;
|
||||||
|
while (i < l.text.len and l.text[i] != '>' and l.text[i] != '\n') i += 1;
|
||||||
|
if (i >= l.text.len or l.text[i] != '>') return null;
|
||||||
|
l.pos = @intCast(i + 1);
|
||||||
|
return .{ .kind = .string, .flags = .{ .space = trivia.space }, .text = l.text[start..l.pos], .loc = .{ .file = l.file, .offset = start } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Skip to the start of the next line (used for skipped conditional
|
||||||
|
/// blocks and after directives).
|
||||||
|
pub fn skipLine(l: *Lexer) void {
|
||||||
|
while (l.pos < l.text.len) {
|
||||||
|
const c = l.text[l.pos];
|
||||||
|
if (c == '\n') return;
|
||||||
|
if (c == '/' and l.peekAt(l.pos + 1) == '*') {
|
||||||
|
if (std.mem.indexOfPos(u8, l.text, l.pos + 2, "*/")) |end| {
|
||||||
|
l.pos = @intCast(end + 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
l.pos = @intCast(l.text.len);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c == '/' and l.peekAt(l.pos + 1) == '/') {
|
||||||
|
while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
l.pos += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lexToken(l: *Lexer) Kind {
|
||||||
|
if (l.pos >= l.text.len) return .eof;
|
||||||
|
const c = l.text[l.pos];
|
||||||
|
l.pos += 1;
|
||||||
|
switch (c) {
|
||||||
|
'a'...'z', 'A'...'Z', '_' => {
|
||||||
|
while (l.pos < l.text.len and isIdentChar(l.text[l.pos])) l.pos += 1;
|
||||||
|
return .identifier;
|
||||||
|
},
|
||||||
|
'0'...'9' => {
|
||||||
|
l.lexPpNumber();
|
||||||
|
return .number;
|
||||||
|
},
|
||||||
|
'.' => {
|
||||||
|
if (std.ascii.isDigit(l.peekAt(l.pos))) {
|
||||||
|
l.lexPpNumber();
|
||||||
|
return .number;
|
||||||
|
}
|
||||||
|
if (l.peekAt(l.pos) == '.' and l.peekAt(l.pos + 1) == '.') {
|
||||||
|
l.pos += 2;
|
||||||
|
return .ellipsis;
|
||||||
|
}
|
||||||
|
return .period;
|
||||||
|
},
|
||||||
|
'"' => return l.lexQuoted('"', .string),
|
||||||
|
'\'' => return l.lexQuoted('\'', .char),
|
||||||
|
'(' => return .l_paren,
|
||||||
|
')' => return .r_paren,
|
||||||
|
'{' => return .l_brace,
|
||||||
|
'}' => return .r_brace,
|
||||||
|
'[' => return .l_square,
|
||||||
|
']' => return .r_square,
|
||||||
|
';' => return .semi,
|
||||||
|
',' => return .comma,
|
||||||
|
'?' => return .question,
|
||||||
|
'~' => return .tilde,
|
||||||
|
':' => return if (l.eat(':')) .colon_colon else .colon,
|
||||||
|
'+' => return if (l.eat('+')) .plus_plus else if (l.eat('=')) .plus_equal else .plus,
|
||||||
|
'-' => return if (l.eat('-')) .minus_minus else if (l.eat('=')) .minus_equal else if (l.eat('>')) .arrow else .minus,
|
||||||
|
'*' => return if (l.eat('=')) .star_equal else .star,
|
||||||
|
'/' => return if (l.eat('=')) .slash_equal else .slash,
|
||||||
|
'%' => return if (l.eat('=')) .percent_equal else .percent,
|
||||||
|
'&' => return if (l.eat('&')) .amp_amp else if (l.eat('=')) .amp_equal else .amp,
|
||||||
|
'|' => return if (l.eat('|')) .pipe_pipe else if (l.eat('=')) .pipe_equal else .pipe,
|
||||||
|
'^' => return if (l.eat('=')) .caret_equal else .caret,
|
||||||
|
'!' => return if (l.eat('=')) .exclaim_equal else .exclaim,
|
||||||
|
'=' => return if (l.eat('=')) .equal_equal else .equal,
|
||||||
|
'#' => return if (l.eat('#')) .hash_hash else .hash,
|
||||||
|
'<' => {
|
||||||
|
if (l.eat('<')) return if (l.eat('=')) .less_less_equal else .less_less;
|
||||||
|
return if (l.eat('=')) .less_equal else .less;
|
||||||
|
},
|
||||||
|
'>' => {
|
||||||
|
if (l.eat('>')) return if (l.eat('=')) .greater_greater_equal else .greater_greater;
|
||||||
|
return if (l.eat('=')) .greater_equal else .greater;
|
||||||
|
},
|
||||||
|
else => return .invalid,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eat(l: *Lexer, c: u8) bool {
|
||||||
|
if (l.peekAt(l.pos) == c) {
|
||||||
|
l.pos += 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lexPpNumber(l: *Lexer) void {
|
||||||
|
while (l.pos < l.text.len) {
|
||||||
|
const c = l.text[l.pos];
|
||||||
|
if ((c == '+' or c == '-') and l.pos > 0) {
|
||||||
|
const p = l.text[l.pos - 1];
|
||||||
|
if (p == 'e' or p == 'E' or p == 'p' or p == 'P') {
|
||||||
|
l.pos += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (isIdentChar(c) or c == '.') {
|
||||||
|
l.pos += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lexQuoted(l: *Lexer, quote: u8, kind: Kind) Kind {
|
||||||
|
while (l.pos < l.text.len) {
|
||||||
|
const c = l.text[l.pos];
|
||||||
|
if (c == '\n') return .invalid;
|
||||||
|
l.pos += 1;
|
||||||
|
if (c == '\\' and l.pos < l.text.len) {
|
||||||
|
l.pos += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote) return kind;
|
||||||
|
}
|
||||||
|
return .invalid;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn isIdentChar(c: u8) bool {
|
||||||
|
return std.ascii.isAlphanumeric(c) or c == '_';
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expectKinds(text: []const u8, kinds: []const Kind) !void {
|
||||||
|
var l = Lexer.init(text, 0);
|
||||||
|
for (kinds) |k| try std.testing.expectEqual(k, l.next().kind);
|
||||||
|
try std.testing.expectEqual(Kind.eof, l.next().kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "punctuators and literals" {
|
||||||
|
try expectKinds("a+=b<<=c>>1.5e-3f", &.{ .identifier, .plus_equal, .identifier, .less_less_equal, .identifier, .greater_greater, .number });
|
||||||
|
try expectKinds("x::y->z...", &.{ .identifier, .colon_colon, .identifier, .arrow, .identifier, .ellipsis });
|
||||||
|
try expectKinds("\"a\\\"b\" 'c' .5h 0x1Fu", &.{ .string, .char, .number, .number });
|
||||||
|
try expectKinds("# ## #x", &.{ .hash, .hash_hash, .hash, .identifier });
|
||||||
|
}
|
||||||
|
|
||||||
|
test "comments, flags and lines" {
|
||||||
|
var l = Lexer.init("a /* x\n y */ b // c\n c", 0);
|
||||||
|
const a = l.next();
|
||||||
|
try std.testing.expect(a.flags.bol);
|
||||||
|
const b = l.next();
|
||||||
|
try std.testing.expect(!b.flags.bol and b.flags.space);
|
||||||
|
const c = l.next();
|
||||||
|
try std.testing.expect(c.flags.bol);
|
||||||
|
try std.testing.expectEqualStrings("c", c.text);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
//! `-P` output: preprocessed text with `#line` markers, laid out like
|
||||||
|
//! clang's PrintPreprocessedOutput.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const lexer = @import("lexer.zig");
|
||||||
|
const Preprocessor = @import("preproc.zig").Preprocessor;
|
||||||
|
const Token = lexer.Token;
|
||||||
|
|
||||||
|
pub fn print(pp: *Preprocessor, w: *std.Io.Writer) !void {
|
||||||
|
var cur_file: ?[]const u8 = null;
|
||||||
|
var cur_line: u32 = 0;
|
||||||
|
var prev: ?Token = null;
|
||||||
|
var line_has_tokens = false;
|
||||||
|
while (true) {
|
||||||
|
const t = try pp.next();
|
||||||
|
if (t.kind == .eof) break;
|
||||||
|
const p = pp.presumedLoc(t.loc);
|
||||||
|
const same_file = cur_file != null and std.mem.eql(u8, cur_file.?, p.file);
|
||||||
|
if (!same_file) {
|
||||||
|
if (line_has_tokens) try w.writeByte('\n');
|
||||||
|
try w.print("#line {d} \"", .{p.line});
|
||||||
|
try writeEscaped(w, p.file);
|
||||||
|
try w.writeAll("\"\n");
|
||||||
|
cur_file = p.file;
|
||||||
|
cur_line = p.line;
|
||||||
|
line_has_tokens = false;
|
||||||
|
prev = null;
|
||||||
|
} else if (p.line > cur_line) {
|
||||||
|
// Short gaps are reproduced with newlines; long ones get a marker.
|
||||||
|
const gap = p.line - cur_line;
|
||||||
|
if (gap < 8) {
|
||||||
|
try w.splatByteAll('\n', gap);
|
||||||
|
} else {
|
||||||
|
if (line_has_tokens) try w.writeByte('\n');
|
||||||
|
try w.print("#line {d} \"", .{p.line});
|
||||||
|
try writeEscaped(w, p.file);
|
||||||
|
try w.writeAll("\"\n");
|
||||||
|
}
|
||||||
|
cur_line = p.line;
|
||||||
|
line_has_tokens = false;
|
||||||
|
prev = null;
|
||||||
|
} else if (t.kind == .pragma and line_has_tokens) {
|
||||||
|
try w.writeByte('\n');
|
||||||
|
cur_line += 1;
|
||||||
|
line_has_tokens = false;
|
||||||
|
prev = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (t.kind == .pragma) {
|
||||||
|
try w.print("#pragma {s}\n", .{t.text});
|
||||||
|
cur_line += 1;
|
||||||
|
line_has_tokens = false;
|
||||||
|
prev = null;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (prev) |pv| {
|
||||||
|
if (t.flags.space or avoidConcat(pv, t)) try w.writeByte(' ');
|
||||||
|
} else if (t.flags.space and line_has_tokens) try w.writeByte(' ');
|
||||||
|
try w.writeAll(t.text);
|
||||||
|
prev = t;
|
||||||
|
line_has_tokens = true;
|
||||||
|
}
|
||||||
|
if (line_has_tokens) try w.writeByte('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
fn writeEscaped(w: *std.Io.Writer, s: []const u8) !void {
|
||||||
|
for (s) |c| {
|
||||||
|
if (c == '"' or c == '\\') try w.writeByte('\\');
|
||||||
|
try w.writeByte(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when printing `b` directly after `a` would lex differently.
|
||||||
|
fn avoidConcat(a: Token, b: Token) bool {
|
||||||
|
if (a.text.len == 0 or b.text.len == 0) return false;
|
||||||
|
const last = a.text[a.text.len - 1];
|
||||||
|
const first = b.text[0];
|
||||||
|
if (lexer.isIdentChar(last) and (lexer.isIdentChar(first) or first == '.')) return true;
|
||||||
|
if (a.kind == .number and (first == '+' or first == '-' or first == '.')) return true;
|
||||||
|
var buf: [8]u8 = undefined;
|
||||||
|
if (a.text.len > 3 or b.text.len > 3 or !a.kind.isPunct() or !b.kind.isPunct()) return false;
|
||||||
|
const joined = std.fmt.bufPrint(&buf, "{s}{s}", .{ a.text, b.text }) catch return true;
|
||||||
|
var l = lexer.Lexer.init(joined, 0);
|
||||||
|
return l.next().text.len != a.text.len;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,188 @@
|
||||||
|
//! Source files and locations.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
||||||
|
pub const FileId = u32;
|
||||||
|
|
||||||
|
pub const Loc = struct {
|
||||||
|
file: FileId,
|
||||||
|
/// Byte offset into the file's (line-spliced) text.
|
||||||
|
offset: u32,
|
||||||
|
|
||||||
|
pub const none: Loc = .{ .file = std.math.maxInt(FileId), .offset = 0 };
|
||||||
|
|
||||||
|
pub fn isNone(l: Loc) bool {
|
||||||
|
return l.file == none.file;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Reads files on behalf of the compiler (real filesystem, or in-memory for
|
||||||
|
/// tests and for in-process callers).
|
||||||
|
pub const FileSystem = struct {
|
||||||
|
ctx: *anyopaque,
|
||||||
|
readFn: *const fn (ctx: *anyopaque, gpa: Allocator, path: []const u8) ?[]const u8,
|
||||||
|
|
||||||
|
pub fn read(fs: FileSystem, gpa: Allocator, path: []const u8) ?[]const u8 {
|
||||||
|
return fs.readFn(fs.ctx, gpa, path);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// In-memory file system: path -> contents.
|
||||||
|
pub const MemoryFs = struct {
|
||||||
|
files: std.StringHashMapUnmanaged([]const u8) = .empty,
|
||||||
|
|
||||||
|
pub fn put(m: *MemoryFs, gpa: Allocator, path: []const u8, text: []const u8) !void {
|
||||||
|
try m.files.put(gpa, path, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(m: *MemoryFs, gpa: Allocator) void {
|
||||||
|
m.files.deinit(gpa);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fileSystem(m: *MemoryFs) FileSystem {
|
||||||
|
return .{ .ctx = m, .readFn = readImpl };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn readImpl(ctx: *anyopaque, gpa: Allocator, path: []const u8) ?[]const u8 {
|
||||||
|
const m: *MemoryFs = @ptrCast(@alignCast(ctx));
|
||||||
|
const text = m.files.get(path) orelse return null;
|
||||||
|
return gpa.dupe(u8, text) catch null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Real file system through std.Io.
|
||||||
|
pub const DiskFs = struct {
|
||||||
|
io: std.Io,
|
||||||
|
|
||||||
|
pub fn fileSystem(d: *DiskFs) FileSystem {
|
||||||
|
return .{ .ctx = d, .readFn = readImpl };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn readImpl(ctx: *anyopaque, gpa: Allocator, path: []const u8) ?[]const u8 {
|
||||||
|
const d: *DiskFs = @ptrCast(@alignCast(ctx));
|
||||||
|
return std.Io.Dir.cwd().readFileAlloc(d.io, path, gpa, .limited(256 << 20)) catch null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const File = struct {
|
||||||
|
path: []const u8,
|
||||||
|
text: []const u8,
|
||||||
|
/// Offsets of the first byte of each line.
|
||||||
|
line_starts: []const u32,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const LineCol = struct { line: u32, col: u32 };
|
||||||
|
|
||||||
|
pub const SourceManager = struct {
|
||||||
|
arena: std.heap.ArenaAllocator,
|
||||||
|
files: std.ArrayList(File) = .empty,
|
||||||
|
fs: FileSystem,
|
||||||
|
|
||||||
|
pub fn init(gpa: Allocator, fs: FileSystem) SourceManager {
|
||||||
|
return .{ .arena = .init(gpa), .fs = fs };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(sm: *SourceManager) void {
|
||||||
|
sm.arena.deinit();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn allocator(sm: *SourceManager) Allocator {
|
||||||
|
return sm.arena.allocator();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load a file from the file system; null if it cannot be read.
|
||||||
|
pub fn load(sm: *SourceManager, path: []const u8) !?FileId {
|
||||||
|
const text = sm.fs.read(sm.allocator(), path) orelse return null;
|
||||||
|
return try sm.addFile(path, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Register text under `path`. Backslash-newline sequences are removed
|
||||||
|
/// (translation phase 2), so offsets refer to the spliced text.
|
||||||
|
pub fn addFile(sm: *SourceManager, path: []const u8, raw: []const u8) !FileId {
|
||||||
|
const a = sm.allocator();
|
||||||
|
const no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw;
|
||||||
|
const text = try spliceLines(a, no_bom);
|
||||||
|
var starts: std.ArrayList(u32) = .empty;
|
||||||
|
try starts.append(a, 0);
|
||||||
|
for (text, 0..) |c, i| {
|
||||||
|
if (c == '\n') try starts.append(a, @intCast(i + 1));
|
||||||
|
}
|
||||||
|
try sm.files.append(a, .{
|
||||||
|
.path = try a.dupe(u8, path),
|
||||||
|
.text = text,
|
||||||
|
.line_starts = try starts.toOwnedSlice(a),
|
||||||
|
});
|
||||||
|
return @intCast(sm.files.items.len - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn file(sm: *const SourceManager, id: FileId) *const File {
|
||||||
|
return &sm.files.items[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1-based line and column.
|
||||||
|
pub fn lineCol(sm: *const SourceManager, loc: Loc) LineCol {
|
||||||
|
const f = sm.file(loc.file);
|
||||||
|
const idx = std.sort.upperBound(u32, f.line_starts, loc.offset, struct {
|
||||||
|
fn cmp(target: u32, x: u32) std.math.Order {
|
||||||
|
return std.math.order(target, x);
|
||||||
|
}
|
||||||
|
}.cmp);
|
||||||
|
const line: u32 = @intCast(idx);
|
||||||
|
return .{ .line = line, .col = loc.offset - f.line_starts[line - 1] + 1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text of the line containing `loc`, without the newline.
|
||||||
|
pub fn lineText(sm: *const SourceManager, loc: Loc) []const u8 {
|
||||||
|
const f = sm.file(loc.file);
|
||||||
|
const lc = sm.lineCol(loc);
|
||||||
|
const start = f.line_starts[lc.line - 1];
|
||||||
|
var end = start;
|
||||||
|
while (end < f.text.len and f.text[end] != '\n' and f.text[end] != '\r') end += 1;
|
||||||
|
return f.text[start..end];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
|
||||||
|
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
|
||||||
|
var out: std.ArrayList(u8) = .empty;
|
||||||
|
try out.ensureTotalCapacity(a, raw.len);
|
||||||
|
var i: usize = 0;
|
||||||
|
while (i < raw.len) {
|
||||||
|
if (raw[i] == '\\') {
|
||||||
|
var j = i + 1;
|
||||||
|
// Clang tolerates whitespace between the backslash and newline.
|
||||||
|
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
|
||||||
|
if (j < raw.len and raw[j] == '\n') {
|
||||||
|
i = j + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
|
||||||
|
i = j + 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.appendAssumeCapacity(raw[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
return out.items;
|
||||||
|
}
|
||||||
|
|
||||||
|
test "line and column lookup" {
|
||||||
|
var mfs: MemoryFs = .{};
|
||||||
|
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
||||||
|
defer sm.deinit();
|
||||||
|
const id = try sm.addFile("a.hlsl", "ab\ncd\n\nx");
|
||||||
|
try std.testing.expectEqual(LineCol{ .line = 1, .col = 1 }, sm.lineCol(.{ .file = id, .offset = 0 }));
|
||||||
|
try std.testing.expectEqual(LineCol{ .line = 2, .col = 2 }, sm.lineCol(.{ .file = id, .offset = 4 }));
|
||||||
|
try std.testing.expectEqual(LineCol{ .line = 4, .col = 1 }, sm.lineCol(.{ .file = id, .offset = 7 }));
|
||||||
|
try std.testing.expectEqualStrings("cd", sm.lineText(.{ .file = id, .offset = 3 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
test "line splicing" {
|
||||||
|
var mfs: MemoryFs = .{};
|
||||||
|
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
||||||
|
defer sm.deinit();
|
||||||
|
const id = try sm.addFile("a.hlsl", "#define A 1 \\\n + 2\nx");
|
||||||
|
try std.testing.expectEqualStrings("#define A 1 + 2\nx", sm.file(id).text);
|
||||||
|
}
|
||||||
130
src/main.zig
130
src/main.zig
|
|
@ -3,6 +3,7 @@ const Io = std.Io;
|
||||||
const zdxc = @import("zdxc");
|
const zdxc = @import("zdxc");
|
||||||
const shader = zdxc.dxil.shader;
|
const shader = zdxc.dxil.shader;
|
||||||
const container = zdxc.dxil.container;
|
const container = zdxc.dxil.container;
|
||||||
|
const front = zdxc.front;
|
||||||
|
|
||||||
const usage =
|
const usage =
|
||||||
\\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler
|
\\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler
|
||||||
|
|
@ -14,11 +15,19 @@ const usage =
|
||||||
\\ -E <name> Entry point name (default: main)
|
\\ -E <name> Entry point name (default: main)
|
||||||
\\ -Fo <file> Output object file
|
\\ -Fo <file> Output object file
|
||||||
\\ -spirv Generate SPIR-V
|
\\ -spirv Generate SPIR-V
|
||||||
|
\\ -D <name>[=<value>] Define a macro
|
||||||
|
\\ -I <dir> Add an include directory
|
||||||
|
\\ -P Preprocess only (to -Fi <file>, or stdout)
|
||||||
|
\\ -Fi <file> Output file for -P
|
||||||
|
\\ -HV 2021 HLSL version (only 2021 is supported)
|
||||||
|
\\ -enable-16bit-types Enable 16-bit types
|
||||||
\\ --version Print version
|
\\ --version Print version
|
||||||
\\
|
\\
|
||||||
\\DEVELOPMENT (temporary, until the frontend lands):
|
\\DEVELOPMENT (temporary, until the frontend lands):
|
||||||
\\ -zdxc-empty Emit an empty shader for -T instead of compiling <input>
|
\\ -zdxc-empty Emit an empty shader for -T instead of compiling <input>
|
||||||
\\ -zdxc-check-hash Verify the container hash of <input>
|
\\ -zdxc-check-hash Verify the container hash of <input>
|
||||||
|
\\ -zdxc-lex Print the tokens of <input>, one per line (no preprocessing;
|
||||||
|
\\ `#line` lines are skipped)
|
||||||
\\
|
\\
|
||||||
;
|
;
|
||||||
|
|
||||||
|
|
@ -28,8 +37,14 @@ const Options = struct {
|
||||||
output: ?[]const u8 = null,
|
output: ?[]const u8 = null,
|
||||||
input: ?[]const u8 = null,
|
input: ?[]const u8 = null,
|
||||||
spirv: bool = false,
|
spirv: bool = false,
|
||||||
|
preprocess: bool = false,
|
||||||
|
pp_output: ?[]const u8 = null,
|
||||||
|
enable_16bit: bool = false,
|
||||||
|
defines: std.ArrayList(front.preproc.Define) = .empty,
|
||||||
|
include_dirs: std.ArrayList([]const u8) = .empty,
|
||||||
empty: bool = false,
|
empty: bool = false,
|
||||||
check_hash: bool = false,
|
check_hash: bool = false,
|
||||||
|
lex: bool = false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const Cli = struct {
|
const Cli = struct {
|
||||||
|
|
@ -48,7 +63,7 @@ pub fn main(init: std.process.Init) !u8 {
|
||||||
const io = init.io;
|
const io = init.io;
|
||||||
var stderr_buf: [1024]u8 = undefined;
|
var stderr_buf: [1024]u8 = undefined;
|
||||||
var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buf);
|
var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buf);
|
||||||
var stdout_buf: [1024]u8 = undefined;
|
var stdout_buf: [4096]u8 = undefined;
|
||||||
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
||||||
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
|
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
|
||||||
|
|
||||||
|
|
@ -60,36 +75,56 @@ pub fn main(init: std.process.Init) !u8 {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !void {
|
/// Splits `-Dfoo` / `-D foo` style options.
|
||||||
|
fn optionValue(cli: Cli, args: []const [:0]const u8, i: *usize, flag: []const u8) ![]const u8 {
|
||||||
|
const a = args[i.*];
|
||||||
|
if (a.len > flag.len) return a[flag.len..];
|
||||||
|
i.* += 1;
|
||||||
|
if (i.* >= args.len) return cli.fail("missing argument to '{s}'", .{flag});
|
||||||
|
return args[i.*];
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parseArgs(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !?Options {
|
||||||
var opts: Options = .{};
|
var opts: Options = .{};
|
||||||
var i: usize = 1;
|
var i: usize = 1;
|
||||||
while (i < args.len) : (i += 1) {
|
while (i < args.len) : (i += 1) {
|
||||||
const a = args[i];
|
const a = args[i];
|
||||||
const next = struct {
|
|
||||||
fn get(c: Cli, as: []const [:0]const u8, idx: *usize, name: []const u8) ![]const u8 {
|
|
||||||
idx.* += 1;
|
|
||||||
if (idx.* >= as.len) return c.fail("missing argument to '{s}'", .{name});
|
|
||||||
return as[idx.*];
|
|
||||||
}
|
|
||||||
}.get;
|
|
||||||
if (std.mem.eql(u8, a, "-T")) {
|
if (std.mem.eql(u8, a, "-T")) {
|
||||||
opts.profile = try next(cli, args, &i, a);
|
opts.profile = try optionValue(cli, args, &i, "-T");
|
||||||
} else if (std.mem.eql(u8, a, "-E")) {
|
} else if (std.mem.eql(u8, a, "-E")) {
|
||||||
opts.entry = try next(cli, args, &i, a);
|
opts.entry = try optionValue(cli, args, &i, "-E");
|
||||||
} else if (std.mem.eql(u8, a, "-Fo")) {
|
} else if (std.mem.eql(u8, a, "-Fo")) {
|
||||||
opts.output = try next(cli, args, &i, a);
|
opts.output = try optionValue(cli, args, &i, "-Fo");
|
||||||
|
} else if (std.mem.eql(u8, a, "-Fi")) {
|
||||||
|
opts.pp_output = try optionValue(cli, args, &i, "-Fi");
|
||||||
|
} else if (std.mem.startsWith(u8, a, "-D")) {
|
||||||
|
const v = try optionValue(cli, args, &i, "-D");
|
||||||
|
if (std.mem.indexOfScalar(u8, v, '=')) |eq| {
|
||||||
|
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
|
||||||
|
} else try opts.defines.append(arena, .{ .name = v });
|
||||||
|
} else if (std.mem.startsWith(u8, a, "-I")) {
|
||||||
|
try opts.include_dirs.append(arena, try optionValue(cli, args, &i, "-I"));
|
||||||
|
} else if (std.mem.eql(u8, a, "-HV")) {
|
||||||
|
const v = try optionValue(cli, args, &i, "-HV");
|
||||||
|
if (!std.mem.eql(u8, v, "2021")) return cli.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
|
||||||
|
} else if (std.mem.eql(u8, a, "-P")) {
|
||||||
|
opts.preprocess = true;
|
||||||
} else if (std.mem.eql(u8, a, "-spirv")) {
|
} else if (std.mem.eql(u8, a, "-spirv")) {
|
||||||
opts.spirv = true;
|
opts.spirv = true;
|
||||||
|
} else if (std.mem.eql(u8, a, "-enable-16bit-types")) {
|
||||||
|
opts.enable_16bit = true;
|
||||||
} else if (std.mem.eql(u8, a, "-zdxc-empty")) {
|
} else if (std.mem.eql(u8, a, "-zdxc-empty")) {
|
||||||
opts.empty = true;
|
opts.empty = true;
|
||||||
} else if (std.mem.eql(u8, a, "-zdxc-check-hash")) {
|
} else if (std.mem.eql(u8, a, "-zdxc-check-hash")) {
|
||||||
opts.check_hash = true;
|
opts.check_hash = true;
|
||||||
|
} else if (std.mem.eql(u8, a, "-zdxc-lex")) {
|
||||||
|
opts.lex = true;
|
||||||
} else if (std.mem.eql(u8, a, "--version")) {
|
} else if (std.mem.eql(u8, a, "--version")) {
|
||||||
try stdout.print("zdxc {s}\n", .{zdxc.version});
|
try stdout.print("zdxc {s}\n", .{zdxc.version});
|
||||||
return;
|
return null;
|
||||||
} else if (std.mem.eql(u8, a, "-help") or std.mem.eql(u8, a, "--help")) {
|
} else if (std.mem.eql(u8, a, "-help") or std.mem.eql(u8, a, "--help")) {
|
||||||
try stdout.writeAll(usage);
|
try stdout.writeAll(usage);
|
||||||
return;
|
return null;
|
||||||
} else if (a.len > 0 and a[0] == '-') {
|
} else if (a.len > 0 and a[0] == '-') {
|
||||||
return cli.fail("unknown argument: '{s}'", .{a});
|
return cli.fail("unknown argument: '{s}'", .{a});
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -97,27 +132,80 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
||||||
opts.input = a;
|
opts.input = a;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return opts;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !void {
|
||||||
|
const opts = try parseArgs(cli, arena, args, stdout) orelse return;
|
||||||
|
|
||||||
if (opts.check_hash) {
|
if (opts.check_hash) {
|
||||||
const path = opts.input orelse return cli.fail("no input file", .{});
|
const path = opts.input orelse return cli.fail("no input file", .{});
|
||||||
const bytes = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(1 << 30));
|
const bytes = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(1 << 30));
|
||||||
var view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{path});
|
const view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{path});
|
||||||
_ = &view;
|
|
||||||
if (!container.hashMatches(view.bytes)) return cli.fail("{s}: hash mismatch", .{path});
|
if (!container.hashMatches(view.bytes)) return cli.fail("{s}: hash mismatch", .{path});
|
||||||
try stdout.print("{s}: hash ok ({d} parts)\n", .{ path, view.parts.items.len });
|
try stdout.print("{s}: hash ok ({d} parts)\n", .{ path, view.parts.items.len });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const profile_str = opts.profile orelse return cli.fail("missing -T <profile>", .{});
|
if (opts.lex) {
|
||||||
const profile = shader.Profile.parse(profile_str) orelse return cli.fail("unknown profile '{s}'", .{profile_str});
|
const path = opts.input orelse return cli.fail("no input file", .{});
|
||||||
|
const text = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(256 << 20));
|
||||||
|
var lx = front.lexer.Lexer.init(text, 0);
|
||||||
|
while (true) {
|
||||||
|
const t = lx.next();
|
||||||
|
if (t.kind == .eof) break;
|
||||||
|
if (t.kind == .hash and t.flags.bol) {
|
||||||
|
const save = lx;
|
||||||
|
const d = lx.next();
|
||||||
|
if (d.isIdent("line")) {
|
||||||
|
lx.skipLine();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lx = save;
|
||||||
|
}
|
||||||
|
try stdout.print("{s}\n", .{t.text});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!opts.empty) return cli.fail("compiling HLSL is not implemented yet (use -zdxc-empty)", .{});
|
const profile: ?shader.Profile = if (opts.profile) |p|
|
||||||
if (profile.kind != .compute) return cli.fail("-zdxc-empty supports compute profiles only", .{});
|
shader.Profile.parse(p) orelse return cli.fail("unknown profile '{s}'", .{p})
|
||||||
|
else
|
||||||
|
null;
|
||||||
|
|
||||||
|
if (opts.preprocess) {
|
||||||
|
const input = opts.input orelse return cli.fail("no input file", .{});
|
||||||
|
var disk: front.source.DiskFs = .{ .io = cli.io };
|
||||||
|
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
|
||||||
|
var diags = zdxc.Diagnostics.init(arena);
|
||||||
|
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
|
||||||
|
.defines = opts.defines.items,
|
||||||
|
.include_dirs = opts.include_dirs.items,
|
||||||
|
.stage = if (profile) |p| @backingInt(p.kind) else 5,
|
||||||
|
.major = if (profile) |p| p.major else 6,
|
||||||
|
.minor = if (profile) |p| p.minor else 0,
|
||||||
|
.spirv = opts.spirv,
|
||||||
|
.enable_16bit = opts.enable_16bit,
|
||||||
|
});
|
||||||
|
var out: Io.Writer.Allocating = .init(arena);
|
||||||
|
if (try pp.enterMainFile(input)) try front.pp_print.print(&pp, &out.writer);
|
||||||
|
try diags.render(&sm, cli.stderr);
|
||||||
|
try cli.stderr.flush();
|
||||||
|
if (diags.hasErrors()) return error.Fatal;
|
||||||
|
if (opts.pp_output) |path| {
|
||||||
|
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
|
||||||
|
} else try stdout.writeAll(out.written());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prof = profile orelse return cli.fail("missing -T <profile>", .{});
|
||||||
|
if (!opts.empty) return cli.fail("compiling HLSL is not implemented yet (use -P or -zdxc-empty)", .{});
|
||||||
|
if (prof.kind != .compute) return cli.fail("-zdxc-empty supports compute profiles only", .{});
|
||||||
|
|
||||||
const bytes = if (opts.spirv)
|
const bytes = if (opts.spirv)
|
||||||
try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } })
|
try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } })
|
||||||
else
|
else
|
||||||
try shader.buildEmptyCompute(arena, .{ .entry = opts.entry, .profile = profile, .num_threads = .{ 1, 1, 1 } });
|
try shader.buildEmptyCompute(arena, .{ .entry = opts.entry, .profile = prof, .num_threads = .{ 1, 1, 1 } });
|
||||||
|
|
||||||
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
|
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
|
||||||
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes });
|
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes });
|
||||||
|
|
|
||||||
11
src/root.zig
11
src/root.zig
|
|
@ -1,5 +1,14 @@
|
||||||
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
||||||
|
|
||||||
|
pub const Diagnostics = @import("diag.zig").Diagnostics;
|
||||||
|
|
||||||
|
pub const front = struct {
|
||||||
|
pub const source = @import("front/source.zig");
|
||||||
|
pub const lexer = @import("front/lexer.zig");
|
||||||
|
pub const preproc = @import("front/preproc.zig");
|
||||||
|
pub const pp_print = @import("front/pp_print.zig");
|
||||||
|
};
|
||||||
|
|
||||||
pub const dxil = struct {
|
pub const dxil = struct {
|
||||||
pub const bitstream = @import("dxil/bitstream.zig");
|
pub const bitstream = @import("dxil/bitstream.zig");
|
||||||
pub const container = @import("dxil/container.zig");
|
pub const container = @import("dxil/container.zig");
|
||||||
|
|
@ -16,6 +25,8 @@ pub const version = "0.0.0";
|
||||||
|
|
||||||
test {
|
test {
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
std.testing.refAllDecls(front);
|
||||||
std.testing.refAllDecls(dxil);
|
std.testing.refAllDecls(dxil);
|
||||||
std.testing.refAllDecls(spirv);
|
std.testing.refAllDecls(spirv);
|
||||||
|
_ = @import("diag.zig");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ Each entry records the source path and the DXC commit it was copied from.
|
||||||
|
|
||||||
| File | Source in DXC | DXC commit | License |
|
| File | Source in DXC | DXC commit | License |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| _(none yet; the HLSL intrinsic table and SPIR-V grammar arrive with M0.1)_ | | | |
|
| `hlsl-headers/` (all files) | `tools/clang/lib/Headers/hlsl/` | ecb18fb18 | Apache-2.0 WITH LLVM-exception (`hlsl-headers/LICENSE.txt`) |
|
||||||
|
|
||||||
DXC is distributed under the University of Illinois/NCSA license (LICENSE.TXT
|
DXC is distributed under the University of Illinois/NCSA license (LICENSE.TXT
|
||||||
in the DXC tree); SPIRV-Headers files are under the Khronos MIT-style license.
|
in the DXC tree); SPIRV-Headers files are under the Khronos MIT-style license.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,222 @@
|
||||||
|
==============================================================================
|
||||||
|
The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
|
|
||||||
|
---- LLVM Exceptions to the Apache 2.0 License ----
|
||||||
|
|
||||||
|
As an exception, if, as a result of your compiling your source code, portions
|
||||||
|
of this Software are embedded into an Object form of such source code, you
|
||||||
|
may redistribute such embedded portions in such Object form without complying
|
||||||
|
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
||||||
|
|
||||||
|
In addition, if you combine or link compiled forms of this Software with
|
||||||
|
software that is licensed under the GPLv2 ("Combined Software") and if a
|
||||||
|
court of competent jurisdiction determines that the patent provision (Section
|
||||||
|
3), the indemnity provision (Section 9) or other Section of the License
|
||||||
|
conflicts with the conditions of the GPLv2, you may retroactively and
|
||||||
|
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
||||||
|
the License, but only in their entirety and only with respect to the Combined
|
||||||
|
Software.
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
HLSL Standard Header Library
|
||||||
|
============================
|
||||||
|
|
||||||
|
The contents of this directory and subdirectories are the HLSL Standard Header
|
||||||
|
library. These headers are open source software. You may freely distribute all
|
||||||
|
or parts of these headers under the terms of the license agreement found in
|
||||||
|
LICENSE.txt.
|
||||||
|
|
@ -0,0 +1,727 @@
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
//
|
||||||
|
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
|
||||||
|
// Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
//
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
// DirectX Shader Model 6.10 Linear Algebra objects and APIs.
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
|
#ifndef _HLSL_DX_LINALG_H_
|
||||||
|
#define _HLSL_DX_LINALG_H_
|
||||||
|
|
||||||
|
#include <enable_if>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
#if ((__SHADER_TARGET_MAJOR > 6) || \
|
||||||
|
(__SHADER_TARGET_MAJOR == 6 && __SHADER_TARGET_MINOR >= 10)) && \
|
||||||
|
(__HLSL_VERSION >= 2021)
|
||||||
|
|
||||||
|
#pragma dxc diagnostic push
|
||||||
|
#pragma dxc diagnostic ignored "-Whlsl-groupshared-202x"
|
||||||
|
|
||||||
|
namespace dxil {
|
||||||
|
|
||||||
|
// This enum must _exactly_ match the DXIL constants.
|
||||||
|
enum class ComponentType : uint32_t {
|
||||||
|
Invalid = 0,
|
||||||
|
I1 = 1,
|
||||||
|
I16 = 2,
|
||||||
|
U16 = 3,
|
||||||
|
I32 = 4,
|
||||||
|
U32 = 5,
|
||||||
|
I64 = 6,
|
||||||
|
U64 = 7,
|
||||||
|
F16 = 8,
|
||||||
|
F32 = 9,
|
||||||
|
F64 = 10,
|
||||||
|
SNormF16 = 11,
|
||||||
|
UNormF16 = 12,
|
||||||
|
SNormF32 = 13,
|
||||||
|
UNormF32 = 14,
|
||||||
|
SNormF64 = 15,
|
||||||
|
UNormF64 = 16,
|
||||||
|
PackedS8x32 = 17,
|
||||||
|
PackedU8x32 = 18,
|
||||||
|
|
||||||
|
// BEGIN NEW FOR SM 6.9
|
||||||
|
I8 = 19,
|
||||||
|
U8 = 20,
|
||||||
|
F8_E4M3FN = 21,
|
||||||
|
F8_E5M2 = 22,
|
||||||
|
// END
|
||||||
|
|
||||||
|
// BEGIN NEW FOR SM 6.10
|
||||||
|
BFloat16 = 23,
|
||||||
|
// END
|
||||||
|
|
||||||
|
LastEntry
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace dxil
|
||||||
|
|
||||||
|
namespace dx {
|
||||||
|
|
||||||
|
namespace linalg {
|
||||||
|
|
||||||
|
#define __COMPONENT_TYPE(type) type = (uint)dxil::ComponentType::type
|
||||||
|
|
||||||
|
// This enum only defines values that are valid for Matrix component types.
|
||||||
|
// Each enumeration's value matches the cooresponding DXIL constant.
|
||||||
|
struct ComponentType {
|
||||||
|
enum ComponentEnum {
|
||||||
|
// Signed integers.
|
||||||
|
__COMPONENT_TYPE(I8),
|
||||||
|
__COMPONENT_TYPE(I16),
|
||||||
|
__COMPONENT_TYPE(I32),
|
||||||
|
__COMPONENT_TYPE(I64),
|
||||||
|
|
||||||
|
// Unsigned integers.
|
||||||
|
__COMPONENT_TYPE(U8),
|
||||||
|
__COMPONENT_TYPE(U16),
|
||||||
|
__COMPONENT_TYPE(U32),
|
||||||
|
__COMPONENT_TYPE(U64),
|
||||||
|
|
||||||
|
// Floating point types.
|
||||||
|
__COMPONENT_TYPE(F8_E4M3FN),
|
||||||
|
__COMPONENT_TYPE(F8_E5M2),
|
||||||
|
__COMPONENT_TYPE(F16),
|
||||||
|
__COMPONENT_TYPE(F32),
|
||||||
|
__COMPONENT_TYPE(F64),
|
||||||
|
__COMPONENT_TYPE(BFloat16),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
#undef __COMPONENT_TYPE
|
||||||
|
|
||||||
|
using ComponentEnum = ComponentType::ComponentEnum;
|
||||||
|
|
||||||
|
struct MatrixUse {
|
||||||
|
enum MatrixUseEnum {
|
||||||
|
A = 0,
|
||||||
|
B = 1,
|
||||||
|
Accumulator = 2,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
using MatrixUseEnum = MatrixUse::MatrixUseEnum;
|
||||||
|
|
||||||
|
struct MatrixScope {
|
||||||
|
enum MatrixScopeEnum {
|
||||||
|
Thread = 0,
|
||||||
|
Wave = 1,
|
||||||
|
ThreadGroup = 2,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
using MatrixScopeEnum = MatrixScope::MatrixScopeEnum;
|
||||||
|
|
||||||
|
struct MatrixLayout {
|
||||||
|
enum MatrixLayoutEnum {
|
||||||
|
RowMajor = 0,
|
||||||
|
ColMajor = 1,
|
||||||
|
MulOptimal = 2,
|
||||||
|
MulOptimalTranspose = 3,
|
||||||
|
OuterProductOptimal = 4,
|
||||||
|
OuterProductOptimalTranspose = 5,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
using MatrixLayoutEnum = MatrixLayout::MatrixLayoutEnum;
|
||||||
|
|
||||||
|
namespace __detail {
|
||||||
|
template <ComponentEnum> struct ComponentTypeTraits {
|
||||||
|
using Type = uint;
|
||||||
|
static const bool IsNativeScalar = false;
|
||||||
|
static const uint ElementsPerScalar = 4;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename> struct TypeTraits {
|
||||||
|
static const ComponentEnum CompType =
|
||||||
|
(ComponentEnum)dxil::ComponentType::Invalid;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <ComponentEnum> struct IsComponentTypeAvailable {
|
||||||
|
static const bool value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
#if !__HLSL_ENABLE_16_BIT
|
||||||
|
template <> struct IsComponentTypeAvailable<ComponentType::I16> {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
template <> struct IsComponentTypeAvailable<ComponentType::U16> {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
template <> struct IsComponentTypeAvailable<ComponentType::F16> {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template <ComponentEnum CT, typename Ty> struct IsCompatibleVectorElement {
|
||||||
|
static const bool IsPackedCarrier =
|
||||||
|
hlsl::is_same<Ty, uint8_t4_packed>::value ||
|
||||||
|
hlsl::is_same<Ty, int8_t4_packed>::value;
|
||||||
|
static const bool value =
|
||||||
|
IsComponentTypeAvailable<CT>::value &&
|
||||||
|
(hlsl::is_same<Ty, typename ComponentTypeTraits<CT>::Type>::value ||
|
||||||
|
(!ComponentTypeTraits<CT>::IsNativeScalar && IsPackedCarrier));
|
||||||
|
};
|
||||||
|
|
||||||
|
template <> struct ComponentTypeTraits<ComponentType::BFloat16> {
|
||||||
|
using Type = uint;
|
||||||
|
static const bool IsNativeScalar = false;
|
||||||
|
static const uint ElementsPerScalar = 2;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define __MATRIX_SCALAR_COMPONENT_MAPPING(enum_val, type) \
|
||||||
|
template <> struct ComponentTypeTraits<enum_val> { \
|
||||||
|
using Type = type; \
|
||||||
|
static const bool IsNativeScalar = true; \
|
||||||
|
static const uint ElementsPerScalar = 1; \
|
||||||
|
}; \
|
||||||
|
template <> struct TypeTraits<type> { \
|
||||||
|
static const ComponentEnum CompType = enum_val; \
|
||||||
|
};
|
||||||
|
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I16, int16_t)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U16, uint16_t)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F16, float16_t)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I32, int32_t)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U32, uint32_t)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F32, float)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I64, int64_t)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U64, uint64_t)
|
||||||
|
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F64, double)
|
||||||
|
|
||||||
|
template <ComponentEnum DstCT, ComponentEnum SrcCT, int SrcN> struct DstN {
|
||||||
|
// Make sure to round up in case SrcN isn't an even multiple of the number of
|
||||||
|
// elements per scalar
|
||||||
|
static const int Value =
|
||||||
|
(SrcN * ComponentTypeTraits<SrcCT>::ElementsPerScalar +
|
||||||
|
ComponentTypeTraits<DstCT>::ElementsPerScalar - 1) /
|
||||||
|
ComponentTypeTraits<DstCT>::ElementsPerScalar;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <SIZE_TYPE MVal, SIZE_TYPE NVal, bool Transposed> struct DimMN {
|
||||||
|
static const SIZE_TYPE M = MVal;
|
||||||
|
static const SIZE_TYPE N = NVal;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <SIZE_TYPE MVal, SIZE_TYPE NVal> struct DimMN<MVal, NVal, true> {
|
||||||
|
static const SIZE_TYPE M = NVal;
|
||||||
|
static const SIZE_TYPE N = MVal;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <ComponentEnum CT, SIZE_TYPE PackedComponentCount>
|
||||||
|
struct ScalarCountFromPackedComponents {
|
||||||
|
static const SIZE_TYPE ElementsPerScalar =
|
||||||
|
ComponentTypeTraits<CT>::ElementsPerScalar;
|
||||||
|
static const SIZE_TYPE Value =
|
||||||
|
(PackedComponentCount + ElementsPerScalar - 1) / ElementsPerScalar;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N> struct DefaultAlign {
|
||||||
|
enum {
|
||||||
|
MinDim = M < N ? M : N,
|
||||||
|
ScalarCount = ScalarCountFromPackedComponents<CT, MinDim>::Value,
|
||||||
|
ByteAlign = ScalarCount * 4,
|
||||||
|
MinByteAlign = ByteAlign < 4 ? 4 : ByteAlign,
|
||||||
|
Value = MinByteAlign < 16 ? MinByteAlign : 16
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace __detail
|
||||||
|
|
||||||
|
template <ComponentEnum CT, uint DimA> struct VectorRef {
|
||||||
|
ByteAddressBuffer Buf;
|
||||||
|
uint Offset;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Ty, int N, ComponentEnum CT> struct InterpretedVector {
|
||||||
|
vector<Ty, N> Data;
|
||||||
|
static const ComponentEnum Interpretation = CT;
|
||||||
|
static const SIZE_TYPE Size =
|
||||||
|
__detail::ComponentTypeTraits<CT>::ElementsPerScalar * N;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <ComponentEnum CT, typename Ty, int N>
|
||||||
|
typename hlsl::enable_if< __detail::IsCompatibleVectorElement<CT, Ty>::value,
|
||||||
|
InterpretedVector<Ty, N, CT> >::type
|
||||||
|
MakeInterpretedVector(vector<Ty, N> Vec) {
|
||||||
|
InterpretedVector<Ty, N, CT> IV = {Vec};
|
||||||
|
return IV;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum DestCT, ComponentEnum OriginCT, typename Ty, int N>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
DestCT != OriginCT && __detail::IsComponentTypeAvailable<DestCT>::value &&
|
||||||
|
__detail::IsCompatibleVectorElement<OriginCT, Ty>::value,
|
||||||
|
InterpretedVector<typename __detail::ComponentTypeTraits<DestCT>::Type,
|
||||||
|
__detail::DstN<DestCT, OriginCT, N>::Value,
|
||||||
|
DestCT> >::type
|
||||||
|
Convert(vector<Ty, N> Vec) {
|
||||||
|
vector<typename __detail::ComponentTypeTraits<DestCT>::Type,
|
||||||
|
__detail::DstN<DestCT, OriginCT, N>::Value>
|
||||||
|
Result;
|
||||||
|
dx::__builtin_LinAlg_Convert(Result, Vec, OriginCT, DestCT);
|
||||||
|
return MakeInterpretedVector<DestCT>(Result);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum DestCT, ComponentEnum OriginCT, typename Ty, int N>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
DestCT == OriginCT &&
|
||||||
|
__detail::IsCompatibleVectorElement<OriginCT, Ty>::value,
|
||||||
|
InterpretedVector<Ty, N, DestCT> >::type
|
||||||
|
Convert(vector<Ty, N> Vec) {
|
||||||
|
return MakeInterpretedVector<DestCT>(Vec);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, MatrixUseEnum Use,
|
||||||
|
MatrixScopeEnum Scope>
|
||||||
|
class Matrix {
|
||||||
|
using ElementType = typename __detail::ComponentTypeTraits<CT>::Type;
|
||||||
|
// If this isn't a native scalar, we have a type that may pack more than 1
|
||||||
|
// element in each scalar value. (Ex. 8bit => 4elems, 16bit => 2elems)
|
||||||
|
static const uint ElementsPerScalar =
|
||||||
|
__detail::ComponentTypeTraits<CT>::ElementsPerScalar;
|
||||||
|
static const bool IsNativeScalar =
|
||||||
|
__detail::ComponentTypeTraits<CT>::IsNativeScalar;
|
||||||
|
|
||||||
|
using HandleT = __builtin_LinAlgMatrix
|
||||||
|
[[__LinAlgMatrix_Attributes(CT, M, N, Use, Scope)]];
|
||||||
|
HandleT __handle;
|
||||||
|
|
||||||
|
template <ComponentEnum NewCT, MatrixUseEnum NewUse = Use,
|
||||||
|
bool Transpose = false>
|
||||||
|
[[nodiscard]] Matrix<NewCT, __detail::DimMN<M, N, Transpose>::M,
|
||||||
|
__detail::DimMN<M, N, Transpose>::N, NewUse, Scope>
|
||||||
|
Cast() {
|
||||||
|
Matrix<NewCT, __detail::DimMN<M, N, Transpose>::M,
|
||||||
|
__detail::DimMN<M, N, Transpose>::N, NewUse, Scope>
|
||||||
|
Result;
|
||||||
|
dx::__builtin_LinAlg_CopyConvertMatrix(Result.__handle, __handle,
|
||||||
|
Transpose);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Ty>
|
||||||
|
[[nodiscard]] static
|
||||||
|
typename hlsl::enable_if<hlsl::is_arithmetic<Ty>::value, Matrix>::type
|
||||||
|
Splat(Ty Val) {
|
||||||
|
Matrix Result;
|
||||||
|
dx::__builtin_LinAlg_FillMatrix(Result.__handle, hlsl::is_signed<Ty>::value,
|
||||||
|
Val);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value>
|
||||||
|
[[nodiscard]] static Matrix Load(ByteAddressBuffer Res, uint StartOffset,
|
||||||
|
uint Stride, MatrixLayoutEnum Layout) {
|
||||||
|
Matrix Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixLoadFromDescriptor(
|
||||||
|
Result.__handle, Res, StartOffset, Stride, Layout, Align);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value>
|
||||||
|
[[nodiscard]] static Matrix Load(RWByteAddressBuffer Res, uint StartOffset,
|
||||||
|
uint Stride, MatrixLayoutEnum Layout) {
|
||||||
|
Matrix Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixLoadFromDescriptor(
|
||||||
|
Result.__handle, Res, StartOffset, Stride, Layout, Align);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Ty, SIZE_TYPE Size>
|
||||||
|
[[nodiscard]] static typename hlsl::enable_if<
|
||||||
|
(hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
|
||||||
|
ElementType>::value ||
|
||||||
|
hlsl::is_integral_or_packed_integral<
|
||||||
|
typename hlsl::strip_vector_type<Ty>::type>::value),
|
||||||
|
Matrix>::type
|
||||||
|
Load(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
|
||||||
|
MatrixLayoutEnum Layout) {
|
||||||
|
Matrix Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixLoadFromMemory(Result.__handle, Arr, StartIdx,
|
||||||
|
Stride, Layout);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum LocalCT = CT>
|
||||||
|
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, uint>::type
|
||||||
|
Length() {
|
||||||
|
return dx::__builtin_LinAlg_MatrixLength(__handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum LocalCT = CT>
|
||||||
|
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, uint2>::type
|
||||||
|
GetCoordinate(uint Index) {
|
||||||
|
return dx::__builtin_LinAlg_MatrixGetCoordinate(__handle, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum LocalCT = CT>
|
||||||
|
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, ElementType>::type
|
||||||
|
Get(uint Index) {
|
||||||
|
ElementType Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixGetElement(Result, __handle, Index);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum LocalCT = CT>
|
||||||
|
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, void>::type
|
||||||
|
Set(uint Index, ElementType Value) {
|
||||||
|
dx::__builtin_LinAlg_MatrixSetElement(__handle, __handle, Index, Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value>
|
||||||
|
void Store(RWByteAddressBuffer Res, uint StartOffset, uint Stride,
|
||||||
|
MatrixLayoutEnum Layout) {
|
||||||
|
dx::__builtin_LinAlg_MatrixStoreToDescriptor(__handle, Res, StartOffset,
|
||||||
|
Stride, Layout, Align);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Ty, SIZE_TYPE Size>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
(hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
|
||||||
|
ElementType>::value ||
|
||||||
|
hlsl::is_integral_or_packed_integral<
|
||||||
|
typename hlsl::strip_vector_type<Ty>::type>::value),
|
||||||
|
void>::type
|
||||||
|
Store(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
|
||||||
|
MatrixLayoutEnum Layout) {
|
||||||
|
dx::__builtin_LinAlg_MatrixStoreToMemory(__handle, Arr, StartIdx, Stride,
|
||||||
|
Layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accumulate methods
|
||||||
|
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value,
|
||||||
|
MatrixUseEnum UseLocal = Use>
|
||||||
|
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset, uint Stride,
|
||||||
|
MatrixLayoutEnum Layout) {
|
||||||
|
dx::__builtin_LinAlg_MatrixAccumulateToDescriptor(
|
||||||
|
__handle, Res, StartOffset, Stride, Layout, Align);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Ty, MatrixUseEnum UseLocal = Use, SIZE_TYPE Size>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
|
||||||
|
ElementType>::value &&
|
||||||
|
hlsl::is_arithmetic_vector<Ty>::value &&
|
||||||
|
Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
InterlockedAccumulate(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
|
||||||
|
MatrixLayoutEnum Layout) {
|
||||||
|
dx::__builtin_LinAlg_MatrixAccumulateToMemory(__handle, Arr, StartIdx,
|
||||||
|
Stride, Layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Ty, MatrixUseEnum UseLocal = Use, SIZE_TYPE Size>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
|
||||||
|
uint8_t4_packed>::value &&
|
||||||
|
Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
InterlockedAccumulate(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
|
||||||
|
MatrixLayoutEnum Layout) {
|
||||||
|
dx::__builtin_LinAlg_MatrixAccumulateToMemory(__handle, Arr, StartIdx,
|
||||||
|
Stride, Layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum MatrixCT, MatrixUseEnum UseLocal = Use>
|
||||||
|
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
Accumulate(const Matrix<MatrixCT, M, N, MatrixUse::A, Scope> MatrixA) {
|
||||||
|
dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixA.__handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum MatrixCT, MatrixUseEnum UseLocal = Use>
|
||||||
|
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
Accumulate(const Matrix<MatrixCT, M, N, MatrixUse::B, Scope> MatrixB) {
|
||||||
|
dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixB.__handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum LHSCT, ComponentEnum RHSCT, SIZE_TYPE K,
|
||||||
|
MatrixUseEnum UseLocal = Use>
|
||||||
|
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
MultiplyAccumulate(const Matrix<LHSCT, M, K, MatrixUse::A, Scope> MatrixA,
|
||||||
|
const Matrix<RHSCT, K, N, MatrixUse::B, Scope> MatrixB) {
|
||||||
|
dx::__builtin_LinAlg_MatrixMatrixMultiplyAccumulate(
|
||||||
|
__handle, MatrixA.__handle, MatrixB.__handle, __handle);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Thread-scope Matrices are read-only. Using a template partial
|
||||||
|
// specialization for this simplifies the SFINAE-foo above.
|
||||||
|
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, MatrixUseEnum Use>
|
||||||
|
class Matrix<CT, M, N, Use, MatrixScope::Thread> {
|
||||||
|
using ElementType = typename __detail::ComponentTypeTraits<CT>::Type;
|
||||||
|
|
||||||
|
using HandleT = __builtin_LinAlgMatrix
|
||||||
|
[[__LinAlgMatrix_Attributes(CT, M, N, Use, MatrixScope::Thread)]];
|
||||||
|
HandleT __handle;
|
||||||
|
|
||||||
|
template <MatrixLayoutEnum Layout, uint Align = 128,
|
||||||
|
MatrixUseEnum UseLocal = Use>
|
||||||
|
[[nodiscard]] static
|
||||||
|
typename hlsl::enable_if<Use == MatrixUse::A && UseLocal == Use,
|
||||||
|
Matrix>::type
|
||||||
|
Load(ByteAddressBuffer Res, uint StartOffset, uint Stride) {
|
||||||
|
Matrix Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixLoadFromDescriptor(
|
||||||
|
Result.__handle, Res, StartOffset, Stride, Layout, Align);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint Align = 128, MatrixUseEnum UseLocal = Use>
|
||||||
|
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
|
||||||
|
void>::type
|
||||||
|
InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset) {
|
||||||
|
dx::__builtin_LinAlg_MatrixAccumulateToDescriptor(
|
||||||
|
__handle, Res, StartOffset, 0, MatrixLayout::OuterProductOptimal,
|
||||||
|
Align);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
MatrixUseEnum AccumulatorLayout() {
|
||||||
|
return (MatrixUseEnum)(dx::__builtin_LinAlg_MatrixQueryAccumulatorLayout());
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum OutCT, ComponentEnum ACT, ComponentEnum BCT,
|
||||||
|
SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
|
||||||
|
[[nodiscard]] Matrix<OutCT, M, N, MatrixUse::Accumulator, MatrixScope::Wave>
|
||||||
|
Multiply(const Matrix<ACT, M, K, MatrixUse::A, MatrixScope::Wave> MatrixA,
|
||||||
|
const Matrix<BCT, K, N, MatrixUse::B, MatrixScope::Wave> MatrixB) {
|
||||||
|
Matrix<OutCT, M, N, MatrixUse::Accumulator, MatrixScope::Wave> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
|
||||||
|
MatrixB.__handle);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
|
||||||
|
[[nodiscard]] Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Wave>
|
||||||
|
Multiply(const Matrix<CT, M, K, MatrixUse::A, MatrixScope::Wave> MatrixA,
|
||||||
|
const Matrix<CT, K, N, MatrixUse::B, MatrixScope::Wave> MatrixB) {
|
||||||
|
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Wave> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
|
||||||
|
MatrixB.__handle);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum OutCT, ComponentEnum ACT, ComponentEnum BCT,
|
||||||
|
SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
|
||||||
|
[[nodiscard]] Matrix<OutCT, M, N, MatrixUse::Accumulator,
|
||||||
|
MatrixScope::ThreadGroup>
|
||||||
|
Multiply(
|
||||||
|
const Matrix<ACT, M, K, MatrixUse::A, MatrixScope::ThreadGroup> MatrixA,
|
||||||
|
const Matrix<BCT, K, N, MatrixUse::B, MatrixScope::ThreadGroup> MatrixB) {
|
||||||
|
Matrix<OutCT, M, N, MatrixUse::Accumulator, MatrixScope::ThreadGroup> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
|
||||||
|
MatrixB.__handle);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
|
||||||
|
[[nodiscard]] Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::ThreadGroup>
|
||||||
|
Multiply(
|
||||||
|
const Matrix<CT, M, K, MatrixUse::A, MatrixScope::ThreadGroup> MatrixA,
|
||||||
|
const Matrix<CT, K, N, MatrixUse::B, MatrixScope::ThreadGroup> MatrixB) {
|
||||||
|
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::ThreadGroup> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
|
||||||
|
MatrixB.__handle);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cooperative Vector Replacement API
|
||||||
|
// Cooperative Vector operates on per-thread vectors multiplying against B
|
||||||
|
// matrices with thread scope.
|
||||||
|
|
||||||
|
template <typename OutputTy, typename InputTy, SIZE_TYPE M, SIZE_TYPE K,
|
||||||
|
ComponentEnum CT>
|
||||||
|
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value,
|
||||||
|
vector<OutputTy, M> >::type
|
||||||
|
Multiply(Matrix<CT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
|
||||||
|
vector<InputTy, K> Vec) {
|
||||||
|
vector<OutputTy, M> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixVectorMultiply(
|
||||||
|
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value, Vec,
|
||||||
|
__detail::TypeTraits<InputTy>::CompType);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename OutputTy, typename InputTy, ComponentEnum InputCT,
|
||||||
|
SIZE_TYPE M, SIZE_TYPE K, SIZE_TYPE VecK, ComponentEnum MatrixCT>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
InterpretedVector<InputTy, VecK, InputCT>::Size == K &&
|
||||||
|
__detail::IsCompatibleVectorElement<InputCT, InputTy>::value,
|
||||||
|
vector<OutputTy, M> >::type
|
||||||
|
Multiply(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
|
||||||
|
InterpretedVector<InputTy, VecK, InputCT> InterpVec) {
|
||||||
|
vector<OutputTy, M> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixVectorMultiply(
|
||||||
|
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value,
|
||||||
|
InterpVec.Data, InterpVec.Interpretation);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename OutputTy, typename InputTy, typename BiasTy, SIZE_TYPE M,
|
||||||
|
SIZE_TYPE K, ComponentEnum CT>
|
||||||
|
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value &&
|
||||||
|
hlsl::is_arithmetic<BiasTy>::value,
|
||||||
|
vector<OutputTy, M> >::type
|
||||||
|
MultiplyAdd(Matrix<CT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
|
||||||
|
vector<InputTy, K> Vec, vector<BiasTy, M> Bias) {
|
||||||
|
|
||||||
|
InterpretedVector<OutputTy, M, __detail::TypeTraits<OutputTy>::CompType>
|
||||||
|
BiasConvInterp = Convert<__detail::TypeTraits<OutputTy>::CompType,
|
||||||
|
__detail::TypeTraits<BiasTy>::CompType>(Bias);
|
||||||
|
|
||||||
|
vector<OutputTy, M> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
|
||||||
|
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value, Vec,
|
||||||
|
__detail::TypeTraits<InputTy>::CompType, BiasConvInterp.Data);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename OutputTy, typename InputTy, ComponentEnum InputCT,
|
||||||
|
typename BiasTy, SIZE_TYPE M, SIZE_TYPE K, SIZE_TYPE VecK,
|
||||||
|
ComponentEnum MatrixCT>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
VecK == __detail::ScalarCountFromPackedComponents<InputCT, K>::Value &&
|
||||||
|
__detail::IsCompatibleVectorElement<InputCT, InputTy>::value &&
|
||||||
|
hlsl::is_arithmetic<BiasTy>::value,
|
||||||
|
vector<OutputTy, M> >::type
|
||||||
|
MultiplyAdd(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
|
||||||
|
InterpretedVector<InputTy, VecK, InputCT> InterpVec,
|
||||||
|
vector<BiasTy, M> Bias) {
|
||||||
|
|
||||||
|
InterpretedVector<OutputTy, M, __detail::TypeTraits<OutputTy>::CompType>
|
||||||
|
BiasConvInterp = Convert<__detail::TypeTraits<OutputTy>::CompType,
|
||||||
|
__detail::TypeTraits<BiasTy>::CompType>(Bias);
|
||||||
|
|
||||||
|
vector<OutputTy, M> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
|
||||||
|
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value,
|
||||||
|
InterpVec.Data, InterpVec.Interpretation, BiasConvInterp.Data);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename OutputTy, typename InputTy, ComponentEnum BiasCT,
|
||||||
|
SIZE_TYPE M, SIZE_TYPE K, ComponentEnum MatrixCT>
|
||||||
|
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value,
|
||||||
|
vector<OutputTy, M> >::type
|
||||||
|
MultiplyAdd(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
|
||||||
|
vector<InputTy, K> Vec, VectorRef<BiasCT, M> BiasRef) {
|
||||||
|
|
||||||
|
using BiasVecTy =
|
||||||
|
vector<typename __detail::ComponentTypeTraits<BiasCT>::Type,
|
||||||
|
__detail::ScalarCountFromPackedComponents<BiasCT, M>::Value>;
|
||||||
|
BiasVecTy Bias = BiasRef.Buf.template Load<BiasVecTy>(BiasRef.Offset);
|
||||||
|
|
||||||
|
// Convert currently does not support packed type vector sizes that
|
||||||
|
// are not a multiple of the number of elements per scalar, so we
|
||||||
|
// need to do an extra conversion here to get it into the right shape.
|
||||||
|
// For example, if BiasRef is F8_E4M3FN and M is 7, it gets loaded into
|
||||||
|
// vector<uint, 2>, and if OutputTy is half, Convert will return
|
||||||
|
// vector<half, 8> instead of vector<half, 7>.
|
||||||
|
// https://github.com/microsoft/DirectXShaderCompiler/issues/8418
|
||||||
|
//
|
||||||
|
// Convert to OutputTy vector with padding
|
||||||
|
using BiasConvInterpPaddedTy = InterpretedVector<
|
||||||
|
OutputTy,
|
||||||
|
__detail::DstN<
|
||||||
|
__detail::TypeTraits<OutputTy>::CompType, BiasCT,
|
||||||
|
__detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value,
|
||||||
|
__detail::TypeTraits<OutputTy>::CompType>;
|
||||||
|
|
||||||
|
BiasConvInterpPaddedTy BiasConvInterpPadded =
|
||||||
|
Convert<__detail::TypeTraits<OutputTy>::CompType, BiasCT>(Bias);
|
||||||
|
|
||||||
|
// Truncate the vector to the correct size M
|
||||||
|
vector<OutputTy, M> BiasConv = (vector<OutputTy, M>)BiasConvInterpPadded.Data;
|
||||||
|
|
||||||
|
vector<OutputTy, M> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
|
||||||
|
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value, Vec,
|
||||||
|
__detail::TypeTraits<InputTy>::CompType, BiasConv);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename OutputTy, typename InputTy, ComponentEnum InputCT,
|
||||||
|
ComponentEnum BiasCT, SIZE_TYPE M, SIZE_TYPE K, SIZE_TYPE VecK,
|
||||||
|
ComponentEnum MatrixCT>
|
||||||
|
typename hlsl::enable_if<
|
||||||
|
VecK == __detail::ScalarCountFromPackedComponents<InputCT, K>::Value &&
|
||||||
|
__detail::IsCompatibleVectorElement<InputCT, InputTy>::value,
|
||||||
|
vector<OutputTy, M> >::type
|
||||||
|
MultiplyAdd(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
|
||||||
|
InterpretedVector<InputTy, VecK, InputCT> InterpVec,
|
||||||
|
VectorRef<BiasCT, M> BiasRef) {
|
||||||
|
using BiasVecTy =
|
||||||
|
vector<typename __detail::ComponentTypeTraits<BiasCT>::Type,
|
||||||
|
__detail::ScalarCountFromPackedComponents<BiasCT, M>::Value>;
|
||||||
|
BiasVecTy Bias = BiasRef.Buf.template Load<BiasVecTy>(BiasRef.Offset);
|
||||||
|
|
||||||
|
// Convert currently does not support packed type vector sizes that
|
||||||
|
// are not a multiple of the number of elements per scalar, so we
|
||||||
|
// need to do an extra conversion here to get it into the right shape.
|
||||||
|
// For example, if BiasRef is F8_E4M3FN and M is 7, it gets loaded into
|
||||||
|
// vector<uint, 2>, and if OutputTy is half, Convert will return
|
||||||
|
// vector<half, 8> instead of vector<half, 7>.
|
||||||
|
// https://github.com/microsoft/DirectXShaderCompiler/issues/8418
|
||||||
|
//
|
||||||
|
// Convert to OutputTy vector with padding
|
||||||
|
using BiasConvInterpPaddedTy = InterpretedVector<
|
||||||
|
OutputTy,
|
||||||
|
__detail::DstN<
|
||||||
|
__detail::TypeTraits<OutputTy>::CompType, BiasCT,
|
||||||
|
__detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value,
|
||||||
|
__detail::TypeTraits<OutputTy>::CompType>;
|
||||||
|
|
||||||
|
BiasConvInterpPaddedTy BiasConvInterpPadded =
|
||||||
|
Convert<__detail::TypeTraits<OutputTy>::CompType, BiasCT>(Bias);
|
||||||
|
|
||||||
|
// Truncate the vector to the correct size M
|
||||||
|
vector<OutputTy, M> BiasConv = (vector<OutputTy, M>)BiasConvInterpPadded.Data;
|
||||||
|
|
||||||
|
vector<OutputTy, M> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
|
||||||
|
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value,
|
||||||
|
InterpVec.Data, InterpVec.Interpretation, BiasConv);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outer product functions
|
||||||
|
template <ComponentEnum CT, typename InputTy, SIZE_TYPE M, SIZE_TYPE N>
|
||||||
|
[[nodiscard]] typename hlsl::enable_if<
|
||||||
|
hlsl::is_arithmetic<InputTy>::value,
|
||||||
|
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Thread> >::type
|
||||||
|
OuterProduct(vector<InputTy, M> VecA, vector<InputTy, N> VecB) {
|
||||||
|
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Thread> Result;
|
||||||
|
dx::__builtin_LinAlg_MatrixOuterProduct(
|
||||||
|
Result.__handle, hlsl::is_signed<InputTy>::value, VecA, VecB);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint Align = 64, typename InputTy, SIZE_TYPE M>
|
||||||
|
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value, void>::type
|
||||||
|
InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset,
|
||||||
|
vector<InputTy, M> Vec) {
|
||||||
|
dx::__builtin_LinAlg_VectorAccumulateToDescriptor(Res, StartOffset, Align,
|
||||||
|
Vec);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace linalg
|
||||||
|
|
||||||
|
} // namespace dx
|
||||||
|
|
||||||
|
#pragma dxc diagnostic pop
|
||||||
|
|
||||||
|
#endif // SM 6.10 check and HV version check
|
||||||
|
|
||||||
|
#endif // _HLSL_DX_LINALG_H_
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
//
|
||||||
|
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
|
||||||
|
// Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
//
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
// SFINAE construct for enable_if to enable and disable declarations.
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
|
#ifndef __HLSL_ENABLE_IF
|
||||||
|
#define __HLSL_ENABLE_IF
|
||||||
|
|
||||||
|
#if __HLSL_VERSION >= 2021
|
||||||
|
|
||||||
|
namespace hlsl {
|
||||||
|
|
||||||
|
template <bool B, typename T> struct enable_if {};
|
||||||
|
|
||||||
|
template <typename T> struct enable_if<true, T> {
|
||||||
|
using type = T;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace hlsl
|
||||||
|
|
||||||
|
#endif // __HLSL_VERSION >= 2021
|
||||||
|
|
||||||
|
#endif // __HLSL_ENABLE_IF
|
||||||
|
|
@ -0,0 +1,134 @@
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
//
|
||||||
|
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
|
||||||
|
// Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
//
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
// Template trait constructs for driving template specialization.
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
|
#ifndef __HLSL_TYPE_TRAITS
|
||||||
|
#define __HLSL_TYPE_TRAITS
|
||||||
|
|
||||||
|
#if __HLSL_VERSION >= 2021
|
||||||
|
|
||||||
|
#define SIZE_TYPE int
|
||||||
|
|
||||||
|
namespace hlsl {
|
||||||
|
|
||||||
|
template <typename T, typename U> struct is_same {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T> struct is_same<T, T> {
|
||||||
|
static const bool value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T> struct is_arithmetic {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define __ARITHMETIC_TYPE(type) \
|
||||||
|
template <> struct is_arithmetic<type> { \
|
||||||
|
static const bool value = true; \
|
||||||
|
};
|
||||||
|
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
__ARITHMETIC_TYPE(uint16_t)
|
||||||
|
__ARITHMETIC_TYPE(int16_t)
|
||||||
|
#endif
|
||||||
|
__ARITHMETIC_TYPE(uint)
|
||||||
|
__ARITHMETIC_TYPE(int)
|
||||||
|
__ARITHMETIC_TYPE(uint64_t)
|
||||||
|
__ARITHMETIC_TYPE(int64_t)
|
||||||
|
__ARITHMETIC_TYPE(half)
|
||||||
|
__ARITHMETIC_TYPE(float)
|
||||||
|
__ARITHMETIC_TYPE(double)
|
||||||
|
|
||||||
|
#undef __ARITHMETIC_TYPE
|
||||||
|
|
||||||
|
template <typename T> struct is_integral {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define __INTEGRAL_TYPE(type) \
|
||||||
|
template <> struct is_integral<type> { \
|
||||||
|
static const bool value = true; \
|
||||||
|
};
|
||||||
|
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
__INTEGRAL_TYPE(uint16_t)
|
||||||
|
__INTEGRAL_TYPE(int16_t)
|
||||||
|
#endif
|
||||||
|
__INTEGRAL_TYPE(uint)
|
||||||
|
__INTEGRAL_TYPE(int)
|
||||||
|
__INTEGRAL_TYPE(uint64_t)
|
||||||
|
__INTEGRAL_TYPE(int64_t)
|
||||||
|
|
||||||
|
#undef __INTEGRAL_TYPE
|
||||||
|
|
||||||
|
template <typename T> struct is_packed_integral {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
#if __hlsl_dx_compiler
|
||||||
|
template <> struct is_packed_integral<uint8_t4_packed> {
|
||||||
|
static const bool value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <> struct is_packed_integral<int8_t4_packed> {
|
||||||
|
static const bool value = true;
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template <typename T> struct is_integral_or_packed_integral {
|
||||||
|
static const bool value =
|
||||||
|
is_integral<T>::value || is_packed_integral<T>::value;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T> struct is_signed {
|
||||||
|
static const bool value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define __UNSIGNED_TYPE(type) \
|
||||||
|
template <> struct is_signed<type> { \
|
||||||
|
static const bool value = false; \
|
||||||
|
};
|
||||||
|
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
__UNSIGNED_TYPE(uint16_t)
|
||||||
|
#endif
|
||||||
|
__UNSIGNED_TYPE(uint)
|
||||||
|
__UNSIGNED_TYPE(uint64_t)
|
||||||
|
|
||||||
|
#undef __UNSIGNED_TYPE
|
||||||
|
|
||||||
|
template <typename T> struct is_vector {
|
||||||
|
static const bool value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T, uint N> struct is_vector<vector<T, N> > {
|
||||||
|
static const bool value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T> struct strip_vector_type {
|
||||||
|
using type = T;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T, SIZE_TYPE N> struct strip_vector_type<vector<T, N> > {
|
||||||
|
using type = T;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T> struct is_arithmetic_vector {
|
||||||
|
static const bool value =
|
||||||
|
is_arithmetic<T>::value ||
|
||||||
|
(is_vector<T>::value &&
|
||||||
|
is_arithmetic<typename strip_vector_type<T>::type>::value);
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace hlsl
|
||||||
|
|
||||||
|
#endif // __HLSL_VERSION >= 2021
|
||||||
|
#endif // __HLSL_TYPE_TRAITS
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
//
|
||||||
|
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
|
||||||
|
// Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
//
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
// Header for vector template utility functions for operating on vector
|
||||||
|
// templates.
|
||||||
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
|
#ifndef __HLSL_VECTOR_UTILS
|
||||||
|
#define __HLSL_VECTOR_UTILS
|
||||||
|
|
||||||
|
#if __HLSL_VERSION >= 2021
|
||||||
|
|
||||||
|
#include <enable_if>
|
||||||
|
|
||||||
|
namespace hlsl {
|
||||||
|
|
||||||
|
template <int Off, int OSz, typename T, int ISz>
|
||||||
|
typename hlsl::enable_if<Off + OSz <= ISz, vector<T, OSz> >::type
|
||||||
|
slice(vector<T, ISz> In) {
|
||||||
|
vector<T, OSz> Result = (vector<T, OSz>)0;
|
||||||
|
|
||||||
|
[unroll]
|
||||||
|
for (int I = 0; I < OSz; ++I)
|
||||||
|
Result[I] = In[I + Off];
|
||||||
|
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <int OSz, typename T, int ISz>
|
||||||
|
vector<T, OSz> slice(vector<T, ISz> In) {
|
||||||
|
return slice<0, OSz, T, ISz>(In);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace hlsl
|
||||||
|
|
||||||
|
#endif // __HLSL_VERSION >= 2021
|
||||||
|
#endif // __HLSL_VECTOR_UTILS
|
||||||
|
|
@ -0,0 +1,275 @@
|
||||||
|
// Copyright (c) 2024 Google LLC
|
||||||
|
//
|
||||||
|
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
|
||||||
|
#ifndef _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_
|
||||||
|
#define _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_
|
||||||
|
|
||||||
|
#if __SPIRV_MAJOR_VERSION__ == 1 && __SPIRV_MINOR_VERSION__ < 6
|
||||||
|
#error "CooperativeMatrix requires a minimum of SPIR-V 1.6"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <vk/spirv.h>
|
||||||
|
|
||||||
|
namespace vk {
|
||||||
|
namespace khr {
|
||||||
|
|
||||||
|
// The base cooperative matrix class. The template arguments correspond to the
|
||||||
|
// operands in the OpTypeCooperativeMatrixKHR instruction.
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
class CooperativeMatrix {
|
||||||
|
template <class NewComponentType>
|
||||||
|
CooperativeMatrix<NewComponentType, scope, rows, columns, use> cast();
|
||||||
|
|
||||||
|
// Apply OpSNegate or OFNegate, depending on ComponentType, in a element by
|
||||||
|
// element manner.
|
||||||
|
CooperativeMatrix negate();
|
||||||
|
|
||||||
|
// Apply OpIAdd or OFAdd, depending on ComponentType, in a element by element
|
||||||
|
// manner.
|
||||||
|
CooperativeMatrix operator+(CooperativeMatrix other);
|
||||||
|
|
||||||
|
// Apply OpISub or OFSub, depending on ComponentType, in a element by element
|
||||||
|
// manner.
|
||||||
|
CooperativeMatrix operator-(CooperativeMatrix other);
|
||||||
|
|
||||||
|
// Apply OpIMul or OFMul, depending on ComponentType, in a element by element
|
||||||
|
// manner.
|
||||||
|
CooperativeMatrix operator*(CooperativeMatrix other);
|
||||||
|
|
||||||
|
// Apply OpSDiv, OpUDiv or OFDiv, depending on ComponentType, in a element by
|
||||||
|
// element manner.
|
||||||
|
CooperativeMatrix operator/(CooperativeMatrix other);
|
||||||
|
|
||||||
|
// Apply OpMatrixTimesScalar in a element by element manner.
|
||||||
|
CooperativeMatrix operator*(ComponentType scalar);
|
||||||
|
|
||||||
|
// Store the cooperative matrix using OpCooperativeMatrixStoreKHR to
|
||||||
|
// data using the given memory layout, stride, and memory access operands.
|
||||||
|
// `NonPrivatePointer` and `MakePointerAvailable` with the workgroup scope
|
||||||
|
// will be added to the memory access operands to make the memory coherent.
|
||||||
|
//
|
||||||
|
// This function uses a SPIR-V pointer because HLSL does not allow groupshared
|
||||||
|
// memory object to be passed by reference. The pointer is a hack to get
|
||||||
|
// around that.
|
||||||
|
//
|
||||||
|
// The layout and stride will be passed to the SPIR-V instruction as is. The
|
||||||
|
// precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
void Store(WorkgroupSpirvPointer<Type> data, uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access
|
||||||
|
// operands.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
void Store(WorkgroupSpirvPointer<Type> data, uint32_t stride) {
|
||||||
|
Store<MemoryAccessMaskNone, layout>(data, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store the cooperative matrix using OpCooperativeMatrixStoreKHR to
|
||||||
|
// data[index] using the given memory layout, stride, and memory access
|
||||||
|
// operands. The layout and stride will be passed to the SPIR-V instruction as
|
||||||
|
// is. The precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
void Store(RWStructuredBuffer<Type> data, uint32_t index, uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access
|
||||||
|
// operands.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
void Store(RWStructuredBuffer<Type> data, uint32_t index, uint32_t stride) {
|
||||||
|
Store<MemoryAccessMaskNone, layout>(data, index, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store the cooperative matrix using OpCooperativeMatrixStoreKHR to
|
||||||
|
// data[index] using the given memory layout, stride, and memory access
|
||||||
|
// operands. `NonPrivatePointer` and `MakePointerAvailable` with the
|
||||||
|
// QueueFamily scope will be added to the memory access operands to make the
|
||||||
|
// memory coherent.
|
||||||
|
//
|
||||||
|
// The layout and stride will be passed to the SPIR-V instruction as is. The
|
||||||
|
// precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
void CoherentStore(globallycoherent RWStructuredBuffer<Type> data,
|
||||||
|
uint32_t index, uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access operands
|
||||||
|
// template argument.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
void CoherentStore(globallycoherent RWStructuredBuffer<Type> data,
|
||||||
|
uint32_t index, uint32_t stride) {
|
||||||
|
CoherentStore<MemoryAccessMaskNone, layout>(data, index, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
|
||||||
|
// data using the given memory layout, stride, and memory access operands.
|
||||||
|
// `NonPrivatePointer` and `MakePointerVisible` with the workgroup scope
|
||||||
|
// will be added to the memory access operands to make the memory coherent.
|
||||||
|
//
|
||||||
|
// This function uses a SPIR-V pointer because HLSL does not allow groupshared
|
||||||
|
// memory object to be passed by reference. The pointer is a hack to get
|
||||||
|
// around that.
|
||||||
|
//
|
||||||
|
// The layout and stride will be passed to the SPIR-V instruction as is. The
|
||||||
|
// precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
static CooperativeMatrix Load(WorkgroupSpirvPointer<Type> data,
|
||||||
|
uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access
|
||||||
|
// operands.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
static CooperativeMatrix Load(WorkgroupSpirvPointer<Type> data,
|
||||||
|
uint32_t stride) {
|
||||||
|
return Load<MemoryAccessMaskNone, layout>(data, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
|
||||||
|
// data[index] using the given memory layout, stride, and memory access
|
||||||
|
// operands.
|
||||||
|
//
|
||||||
|
// The layout and stride will be passed to the SPIR-V instruction as is. The
|
||||||
|
// precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
static CooperativeMatrix Load(RWStructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access
|
||||||
|
// operands.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
static CooperativeMatrix Load(RWStructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride) {
|
||||||
|
return Load<MemoryAccessMaskNone, layout>(data, index, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
|
||||||
|
// data[index] using the given memory layout, stride, and memory access
|
||||||
|
// operands. `NonPrivatePointer` and `MakePointerVisible` with the QueueFamily
|
||||||
|
// scope will be added to the memory access operands to make the memory
|
||||||
|
// coherent.
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// The layout and stride will be passed to the SPIR-V instruction as is. The
|
||||||
|
// precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
static CooperativeMatrix
|
||||||
|
CoherentLoad(globallycoherent RWStructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access operands
|
||||||
|
// template argument.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
static CooperativeMatrix
|
||||||
|
CoherentLoad(globallycoherent RWStructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride) {
|
||||||
|
return CoherentLoad<MemoryAccessMaskNone, layout>(data, index, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
|
||||||
|
// data[index] using the given memory layout, stride, and memory access
|
||||||
|
// operands. No memory access bits are added to the operands. Since the memory
|
||||||
|
// is readonly, there should be no need.
|
||||||
|
//
|
||||||
|
// The layout and stride will be passed to the SPIR-V instruction as is. The
|
||||||
|
// precise meaning can be found in the specification for
|
||||||
|
// SPV_KHR_cooperative_matrix.
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
static CooperativeMatrix Load(StructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride);
|
||||||
|
|
||||||
|
// Same as above, but uses MemoryAccessMaskNone for the memory access
|
||||||
|
// operands.
|
||||||
|
template <CooperativeMatrixLayout layout, class Type>
|
||||||
|
static CooperativeMatrix Load(StructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride) {
|
||||||
|
return Load<MemoryAccessMaskNone, layout>(data, index, stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Constructs a cooperative matrix with all values initialized to v. Note that
|
||||||
|
// all threads in scope must have the same value for v.
|
||||||
|
static CooperativeMatrix Splat(ComponentType v);
|
||||||
|
|
||||||
|
// Returns the result of OpCooperativeMatrixLengthKHR on the current type.
|
||||||
|
static uint32_t GetLength();
|
||||||
|
|
||||||
|
// Functions to access the elements of the cooperative matrix. The index must
|
||||||
|
// be less than GetLength().
|
||||||
|
void Set(ComponentType value, uint32_t index);
|
||||||
|
ComponentType Get(uint32_t index);
|
||||||
|
|
||||||
|
static const bool hasSignedIntegerComponentType =
|
||||||
|
(ComponentType(0) - ComponentType(1) < ComponentType(0));
|
||||||
|
|
||||||
|
// clang-format off
|
||||||
|
using SpirvMatrixType = vk::SpirvOpaqueType<
|
||||||
|
/* OpTypeCooperativeMatrixKHR */ 4456, ComponentType,
|
||||||
|
vk::integral_constant<uint, scope>, vk::integral_constant<uint, rows>,
|
||||||
|
vk::integral_constant<uint, columns>, vk::integral_constant<uint, use> >;
|
||||||
|
|
||||||
|
[[vk::ext_extension("SPV_KHR_cooperative_matrix")]]
|
||||||
|
[[vk::ext_capability(/* CooperativeMatrixKHRCapability */ 6022)]]
|
||||||
|
[[vk::ext_capability(/* VulkanMemoryModel */ 5345)]]
|
||||||
|
SpirvMatrixType _matrix;
|
||||||
|
// clang-format on
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cooperative matrix that can be used in the "a" position of a multiply add
|
||||||
|
// instruction (r = (a * b) + c).
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns>
|
||||||
|
using CooperativeMatrixA =
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns,
|
||||||
|
CooperativeMatrixUseMatrixAKHR>;
|
||||||
|
|
||||||
|
// Cooperative matrix that can be used in the "b" position of a multiply add
|
||||||
|
// instruction (r = (a * b) + c).
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns>
|
||||||
|
using CooperativeMatrixB =
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns,
|
||||||
|
CooperativeMatrixUseMatrixBKHR>;
|
||||||
|
|
||||||
|
// Cooperative matrix that can be used in the "r" and "c" position of a multiply
|
||||||
|
// add instruction (r = (a * b) + c).
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns>
|
||||||
|
using CooperativeMatrixAccumulator =
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns,
|
||||||
|
CooperativeMatrixUseMatrixAccumulatorKHR>;
|
||||||
|
|
||||||
|
// Returns the result of OpCooperativeMatrixMulAddKHR when applied to a, b, and
|
||||||
|
// c. The cooperative matrix operands are inferred, with the
|
||||||
|
// SaturatingAccumulationKHR bit not set.
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
|
||||||
|
cooperativeMatrixMultiplyAdd(
|
||||||
|
CooperativeMatrixA<ComponentType, scope, rows, K> a,
|
||||||
|
CooperativeMatrixB<ComponentType, scope, K, columns> b,
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c);
|
||||||
|
|
||||||
|
// Returns the result of OpCooperativeMatrixMulAddKHR when applied to a, b, and
|
||||||
|
// c. The cooperative matrix operands are inferred, with the
|
||||||
|
// SaturatingAccumulationKHR bit set.
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
|
||||||
|
cooperativeMatrixSaturatingMultiplyAdd(
|
||||||
|
CooperativeMatrixA<ComponentType, scope, rows, K> a,
|
||||||
|
CooperativeMatrixB<ComponentType, scope, K, columns> b,
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c);
|
||||||
|
|
||||||
|
} // namespace khr
|
||||||
|
} // namespace vk
|
||||||
|
|
||||||
|
#include <vk/khr/cooperative_matrix.impl>
|
||||||
|
#endif // _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_
|
||||||
|
|
@ -0,0 +1,377 @@
|
||||||
|
// Copyright (c) 2024 Google LLC
|
||||||
|
//
|
||||||
|
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
|
||||||
|
#include <vk/opcode_selector.h>
|
||||||
|
|
||||||
|
template <typename ResultType, typename ComponentType>
|
||||||
|
[[vk::ext_instruction(/* OpMatrixTimesScalar */ 143)]] ResultType
|
||||||
|
__builtin_spv_MatrixTimesScalar(ResultType a, ComponentType b);
|
||||||
|
|
||||||
|
template <typename ComponentType, vk::Scope scope, uint rows, uint columns,
|
||||||
|
vk::CooperativeMatrixUse use>
|
||||||
|
[[vk::ext_instruction(/* OpCompositeExtract */ 81)]] ComponentType
|
||||||
|
__builtin_spv_ExtractFromCooperativeMatrix(
|
||||||
|
typename vk::khr::CooperativeMatrix<ComponentType, scope, rows, columns,
|
||||||
|
use>::SpirvMatrixType matrix,
|
||||||
|
uint32_t index);
|
||||||
|
|
||||||
|
template <typename CoopMatrixType, typename ComponentType>
|
||||||
|
[[vk::ext_instruction(/* OpCompositeConstruct */ 80)]] CoopMatrixType
|
||||||
|
__builtin_spv_ConstructCooperativeMatrix(ComponentType value);
|
||||||
|
|
||||||
|
template <class ResultPointerType, class BaseType>
|
||||||
|
[[vk::ext_instruction(/* OpAccessChain */ 65)]] ResultPointerType
|
||||||
|
__builtin_spv_AccessChain([[vk::ext_reference]] BaseType base, uint32_t index);
|
||||||
|
|
||||||
|
template <class ObjectType, class PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpLoad */ 61)]] ObjectType
|
||||||
|
__builtin_spv_LoadPointer(PointerType base);
|
||||||
|
|
||||||
|
template <class PointerType, class ObjectType>
|
||||||
|
[[vk::ext_instruction(/* OpLoad */ 62)]] void
|
||||||
|
__builtin_spv_StorePointer(PointerType base, ObjectType object);
|
||||||
|
|
||||||
|
template <typename ComponentType, vk::Scope scope, uint rows, uint columns,
|
||||||
|
vk::CooperativeMatrixUse use>
|
||||||
|
[[vk::ext_instruction(/* OpCompositeInsert */ 82)]]
|
||||||
|
typename vk::khr::CooperativeMatrix<ComponentType, scope, rows, columns,
|
||||||
|
use>::SpirvMatrixType
|
||||||
|
__builtin_spv_InsertIntoCooperativeMatrix(
|
||||||
|
ComponentType value,
|
||||||
|
typename vk::khr::CooperativeMatrix<ComponentType, scope, rows, columns,
|
||||||
|
use>::SpirvMatrixType matrix,
|
||||||
|
uint32_t index);
|
||||||
|
|
||||||
|
// Define the load and store instructions
|
||||||
|
template <typename ResultType, typename PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType
|
||||||
|
__builtin_spv_CooperativeMatrixLoadKHR(
|
||||||
|
[[vk::ext_reference]] PointerType pointer,
|
||||||
|
vk::CooperativeMatrixLayout memory_layout, uint stride,
|
||||||
|
[[vk::ext_literal]] uint32_t memory_operand);
|
||||||
|
|
||||||
|
template <typename ResultType, typename PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType
|
||||||
|
__builtin_spv_CooperativeMatrixLoadKHR(
|
||||||
|
[[vk::ext_reference]] PointerType pointer,
|
||||||
|
vk::CooperativeMatrixLayout memory_layout, uint stride,
|
||||||
|
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
|
||||||
|
|
||||||
|
template <typename ResultType, typename PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType
|
||||||
|
__builtin_spv_CooperativeMatrixWorkgroupLoadKHR(
|
||||||
|
vk::WorkgroupSpirvPointer<PointerType> pointer,
|
||||||
|
vk::CooperativeMatrixLayout memory_layout, uint stride,
|
||||||
|
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
|
||||||
|
|
||||||
|
template <typename ObjectType, typename PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void
|
||||||
|
__builtin_spv_CooperativeMatrixStoreKHR(
|
||||||
|
[[vk::ext_reference]] PointerType pointer, ObjectType object,
|
||||||
|
vk::CooperativeMatrixLayout memory_layout, uint stride,
|
||||||
|
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
|
||||||
|
|
||||||
|
template <typename ObjectType, typename PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void
|
||||||
|
__builtin_spv_CooperativeMatrixStoreKHR(
|
||||||
|
[[vk::ext_reference]] PointerType pointer, ObjectType object,
|
||||||
|
vk::CooperativeMatrixLayout memory_layout, uint stride,
|
||||||
|
[[vk::ext_literal]] uint32_t memory_operand);
|
||||||
|
|
||||||
|
template <typename ObjectType, typename PointerType>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void
|
||||||
|
__builtin_spv_CooperativeMatrixWorkgroupStoreKHR(
|
||||||
|
vk::WorkgroupSpirvPointer<PointerType> pointer, ObjectType object,
|
||||||
|
vk::CooperativeMatrixLayout memory_layout, uint stride,
|
||||||
|
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
|
||||||
|
|
||||||
|
// We cannot define `OpCooperativeMatrixLengthKHR` using ext_instruction because
|
||||||
|
// one of the operands is a type id. This builtin will have specific code in the
|
||||||
|
// compiler to expand it.
|
||||||
|
template <class MatrixType> uint __builtin_spv_CooperativeMatrixLengthKHR();
|
||||||
|
|
||||||
|
// Arithmetic Instructions
|
||||||
|
template <typename ResultType, typename MatrixTypeA, typename MatrixTypeB,
|
||||||
|
typename MatrixTypeC>
|
||||||
|
[[vk::ext_instruction(/* OpCooperativeMatrixMulAddKHR */ 4459)]] ResultType
|
||||||
|
__builtin_spv_CooperativeMatrixMulAddKHR(MatrixTypeA a, MatrixTypeB b,
|
||||||
|
MatrixTypeC c,
|
||||||
|
[[vk::ext_literal]] int operands);
|
||||||
|
namespace vk {
|
||||||
|
namespace khr {
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <class NewComponentType>
|
||||||
|
CooperativeMatrix<NewComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::cast() {
|
||||||
|
using ResultType =
|
||||||
|
CooperativeMatrix<NewComponentType, scope, rows, columns, use>;
|
||||||
|
ResultType result;
|
||||||
|
result._matrix = util::ConversionSelector<ComponentType, NewComponentType>::
|
||||||
|
template Convert<typename ResultType::SpirvMatrixType>(_matrix);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::negate() {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix = util::ArithmeticSelector<ComponentType>::Negate(_matrix);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator+(
|
||||||
|
CooperativeMatrix other) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix =
|
||||||
|
util::ArithmeticSelector<ComponentType>::Add(_matrix, other._matrix);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator-(
|
||||||
|
CooperativeMatrix other) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix =
|
||||||
|
util::ArithmeticSelector<ComponentType>::Sub(_matrix, other._matrix);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator*(
|
||||||
|
CooperativeMatrix other) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix =
|
||||||
|
util::ArithmeticSelector<ComponentType>::Mul(_matrix, other._matrix);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator/(
|
||||||
|
CooperativeMatrix other) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix =
|
||||||
|
util::ArithmeticSelector<ComponentType>::Div(_matrix, other._matrix);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator*(
|
||||||
|
ComponentType scalar) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix = __builtin_spv_MatrixTimesScalar(_matrix, scalar);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::Store(
|
||||||
|
WorkgroupSpirvPointer<Type> data, uint32_t stride) {
|
||||||
|
__builtin_spv_CooperativeMatrixWorkgroupStoreKHR(
|
||||||
|
data, _matrix, layout, stride,
|
||||||
|
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
|
||||||
|
MemoryAccessMakePointerAvailableMask,
|
||||||
|
ScopeWorkgroup);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::Store(
|
||||||
|
RWStructuredBuffer<Type> data, uint32_t index, uint32_t stride) {
|
||||||
|
__builtin_spv_CooperativeMatrixStoreKHR(data[index], _matrix, layout, stride,
|
||||||
|
memoryAccessOperands);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::CoherentStore(
|
||||||
|
globallycoherent RWStructuredBuffer<Type> data, uint32_t index,
|
||||||
|
uint32_t stride) {
|
||||||
|
__builtin_spv_CooperativeMatrixStoreKHR(
|
||||||
|
data[index], _matrix, layout, stride,
|
||||||
|
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
|
||||||
|
MemoryAccessMakePointerAvailableMask,
|
||||||
|
ScopeQueueFamily);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Load(
|
||||||
|
vk::WorkgroupSpirvPointer<Type> buffer, uint32_t stride) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix =
|
||||||
|
__builtin_spv_CooperativeMatrixWorkgroupLoadKHR<SpirvMatrixType>(
|
||||||
|
buffer, layout, stride,
|
||||||
|
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
|
||||||
|
MemoryAccessMakePointerVisibleMask,
|
||||||
|
ScopeWorkgroup);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Load(
|
||||||
|
RWStructuredBuffer<Type> buffer, uint32_t index, uint32_t stride) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix = __builtin_spv_CooperativeMatrixLoadKHR<SpirvMatrixType>(
|
||||||
|
buffer[index], layout, stride, memoryAccessOperands);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::CoherentLoad(
|
||||||
|
RWStructuredBuffer<Type> buffer, uint32_t index, uint32_t stride) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix = __builtin_spv_CooperativeMatrixLoadKHR<SpirvMatrixType>(
|
||||||
|
buffer[index], layout, stride,
|
||||||
|
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
|
||||||
|
MemoryAccessMakePointerVisibleMask,
|
||||||
|
ScopeQueueFamily);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
|
||||||
|
class Type>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Load(
|
||||||
|
StructuredBuffer<Type> buffer, uint32_t index, uint32_t stride) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix = __builtin_spv_CooperativeMatrixLoadKHR<SpirvMatrixType>(
|
||||||
|
buffer[index], layout, stride, MemoryAccessMaskNone);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>
|
||||||
|
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Splat(
|
||||||
|
ComponentType v) {
|
||||||
|
CooperativeMatrix result;
|
||||||
|
result._matrix = __builtin_spv_ConstructCooperativeMatrix<SpirvMatrixType>(v);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
uint CooperativeMatrix<ComponentType, scope, rows, columns, use>::GetLength() {
|
||||||
|
return __builtin_spv_CooperativeMatrixLengthKHR<SpirvMatrixType>();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
ComponentType CooperativeMatrix<ComponentType, scope, rows, columns, use>::Get(
|
||||||
|
uint32_t index) {
|
||||||
|
// clang-format off
|
||||||
|
using ComponentPtr = vk::SpirvOpaqueType<
|
||||||
|
/* OpTypePointer */ 32,
|
||||||
|
/* function storage class */ vk::Literal<vk::integral_constant<uint, 7> >,
|
||||||
|
ComponentType>;
|
||||||
|
// clang-format on
|
||||||
|
ComponentPtr ptr = __builtin_spv_AccessChain<ComponentPtr>(_matrix, index);
|
||||||
|
return __builtin_spv_LoadPointer<ComponentType>(ptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class ComponentType, Scope scope, uint rows, uint columns,
|
||||||
|
CooperativeMatrixUse use>
|
||||||
|
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::Set(
|
||||||
|
ComponentType value, uint32_t index) {
|
||||||
|
// clang-format off
|
||||||
|
using ComponentPtr = vk::SpirvOpaqueType<
|
||||||
|
/* OpTypePointer */ 32,
|
||||||
|
/* function storage class */ vk::Literal<vk::integral_constant<uint, 7> >,
|
||||||
|
ComponentType>;
|
||||||
|
// clang-format on
|
||||||
|
ComponentPtr ptr = __builtin_spv_AccessChain<ComponentPtr>(_matrix, index);
|
||||||
|
return __builtin_spv_StorePointer(ptr, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
|
||||||
|
cooperativeMatrixMultiplyAdd(
|
||||||
|
CooperativeMatrixA<ComponentType, scope, rows, K> a,
|
||||||
|
CooperativeMatrixB<ComponentType, scope, K, columns> b,
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c) {
|
||||||
|
|
||||||
|
const vk::CooperativeMatrixOperandsMask allSignedComponents =
|
||||||
|
vk::CooperativeMatrixOperandsMatrixASignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsMatrixBSignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsMatrixCSignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsMatrixResultSignedComponentsKHRMask;
|
||||||
|
|
||||||
|
const vk::CooperativeMatrixOperandsMask operands =
|
||||||
|
(vk::CooperativeMatrixOperandsMask)(
|
||||||
|
a.hasSignedIntegerComponentType
|
||||||
|
? allSignedComponents
|
||||||
|
: vk::CooperativeMatrixOperandsMaskNone);
|
||||||
|
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> result;
|
||||||
|
result._matrix = __builtin_spv_CooperativeMatrixMulAddKHR<
|
||||||
|
typename CooperativeMatrixAccumulator<ComponentType, scope, rows,
|
||||||
|
columns>::SpirvMatrixType>(
|
||||||
|
a._matrix, b._matrix, c._matrix, operands);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
|
||||||
|
cooperativeMatrixSaturatingMultiplyAdd(
|
||||||
|
CooperativeMatrixA<ComponentType, scope, rows, K> a,
|
||||||
|
CooperativeMatrixB<ComponentType, scope, K, columns> b,
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c) {
|
||||||
|
|
||||||
|
const vk::CooperativeMatrixOperandsMask allSignedComponents =
|
||||||
|
vk::CooperativeMatrixOperandsMatrixASignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsMatrixBSignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsMatrixCSignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsMatrixResultSignedComponentsKHRMask |
|
||||||
|
vk::CooperativeMatrixOperandsSaturatingAccumulationKHRMask;
|
||||||
|
|
||||||
|
const vk::CooperativeMatrixOperandsMask operands =
|
||||||
|
(vk::CooperativeMatrixOperandsMask)(
|
||||||
|
a.hasSignedIntegerComponentType
|
||||||
|
? allSignedComponents
|
||||||
|
: vk::CooperativeMatrixOperandsSaturatingAccumulationKHRMask);
|
||||||
|
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> result;
|
||||||
|
result._matrix = __builtin_spv_CooperativeMatrixMulAddKHR<
|
||||||
|
typename CooperativeMatrixAccumulator<ComponentType, scope, rows,
|
||||||
|
columns>::SpirvMatrixType>(
|
||||||
|
a._matrix, b._matrix, c._matrix, operands);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace khr
|
||||||
|
} // namespace vk
|
||||||
|
|
@ -0,0 +1,227 @@
|
||||||
|
// Copyright (c) 2024 Google LLC
|
||||||
|
//
|
||||||
|
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
|
||||||
|
#ifndef _HLSL_VK_KHR_OPCODE_SELECTOR_H_
|
||||||
|
#define _HLSL_VK_KHR_OPCODE_SELECTOR_H_
|
||||||
|
|
||||||
|
#define DECLARE_UNARY_OP(name, opcode) \
|
||||||
|
template <typename ResultType> \
|
||||||
|
[[vk::ext_instruction(opcode)]] ResultType __builtin_spv_##name( \
|
||||||
|
ResultType a)
|
||||||
|
|
||||||
|
DECLARE_UNARY_OP(CopyObject, 83);
|
||||||
|
DECLARE_UNARY_OP(SNegate, 126);
|
||||||
|
DECLARE_UNARY_OP(FNegate, 127);
|
||||||
|
|
||||||
|
#define DECLARE_CONVERSION_OP(name, opcode) \
|
||||||
|
template <typename ResultType, typename OperandType> \
|
||||||
|
[[vk::ext_instruction(opcode)]] ResultType __builtin_spv_##name( \
|
||||||
|
OperandType a)
|
||||||
|
|
||||||
|
DECLARE_CONVERSION_OP(ConvertFtoU, 109);
|
||||||
|
DECLARE_CONVERSION_OP(ConvertFtoS, 110);
|
||||||
|
DECLARE_CONVERSION_OP(ConvertSToF, 111);
|
||||||
|
DECLARE_CONVERSION_OP(ConvertUToF, 112);
|
||||||
|
DECLARE_CONVERSION_OP(UConvert, 113);
|
||||||
|
DECLARE_CONVERSION_OP(SConvert, 114);
|
||||||
|
DECLARE_CONVERSION_OP(FConvert, 115);
|
||||||
|
DECLARE_CONVERSION_OP(Bitcast, 124);
|
||||||
|
|
||||||
|
#undef DECLARY_UNARY_OP
|
||||||
|
|
||||||
|
#define DECLARE_BINOP(name, opcode) \
|
||||||
|
template <typename ResultType> \
|
||||||
|
[[vk::ext_instruction(opcode)]] ResultType __builtin_spv_##name( \
|
||||||
|
ResultType a, ResultType b)
|
||||||
|
|
||||||
|
DECLARE_BINOP(IAdd, 128);
|
||||||
|
DECLARE_BINOP(FAdd, 129);
|
||||||
|
DECLARE_BINOP(ISub, 130);
|
||||||
|
DECLARE_BINOP(FSub, 131);
|
||||||
|
DECLARE_BINOP(IMul, 132);
|
||||||
|
DECLARE_BINOP(FMul, 133);
|
||||||
|
DECLARE_BINOP(UDiv, 134);
|
||||||
|
DECLARE_BINOP(SDiv, 135);
|
||||||
|
DECLARE_BINOP(FDiv, 136);
|
||||||
|
|
||||||
|
#undef DECLARE_BINOP
|
||||||
|
namespace vk {
|
||||||
|
namespace util {
|
||||||
|
|
||||||
|
template <class ComponentType> class ArithmeticSelector;
|
||||||
|
|
||||||
|
#define ARITHMETIC_SELECTOR(BaseType, OpNegate, OpAdd, OpSub, OpMul, OpDiv, \
|
||||||
|
SIGNED_INTEGER_TYPE) \
|
||||||
|
template <> class ArithmeticSelector<BaseType> { \
|
||||||
|
template <class T> static T Negate(T a) { return OpNegate(a); } \
|
||||||
|
template <class T> static T Add(T a, T b) { return OpAdd(a, b); } \
|
||||||
|
template <class T> static T Sub(T a, T b) { return OpSub(a, b); } \
|
||||||
|
template <class T> static T Mul(T a, T b) { return OpMul(a, b); } \
|
||||||
|
template <class T> static T Div(T a, T b) { return OpDiv(a, b); } \
|
||||||
|
};
|
||||||
|
|
||||||
|
ARITHMETIC_SELECTOR(half, __builtin_spv_FNegate, __builtin_spv_FAdd,
|
||||||
|
__builtin_spv_FSub, __builtin_spv_FMul, __builtin_spv_FDiv,
|
||||||
|
false);
|
||||||
|
ARITHMETIC_SELECTOR(float, __builtin_spv_FNegate, __builtin_spv_FAdd,
|
||||||
|
__builtin_spv_FSub, __builtin_spv_FMul, __builtin_spv_FDiv,
|
||||||
|
false);
|
||||||
|
ARITHMETIC_SELECTOR(double, __builtin_spv_FNegate, __builtin_spv_FAdd,
|
||||||
|
__builtin_spv_FSub, __builtin_spv_FMul, __builtin_spv_FDiv,
|
||||||
|
false);
|
||||||
|
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
ARITHMETIC_SELECTOR(int16_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
|
||||||
|
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_SDiv,
|
||||||
|
true);
|
||||||
|
ARITHMETIC_SELECTOR(uint16_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
|
||||||
|
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_UDiv,
|
||||||
|
false);
|
||||||
|
#endif // __HLSL_ENABLE_16_BIT
|
||||||
|
|
||||||
|
ARITHMETIC_SELECTOR(int32_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
|
||||||
|
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_SDiv,
|
||||||
|
true);
|
||||||
|
ARITHMETIC_SELECTOR(int64_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
|
||||||
|
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_SDiv,
|
||||||
|
true);
|
||||||
|
ARITHMETIC_SELECTOR(uint32_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
|
||||||
|
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_UDiv,
|
||||||
|
false);
|
||||||
|
ARITHMETIC_SELECTOR(uint64_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
|
||||||
|
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_UDiv,
|
||||||
|
false);
|
||||||
|
|
||||||
|
// The conversion selector is will be used to convert one type to another
|
||||||
|
// using the SPIR-V conversion instructions. See
|
||||||
|
// https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#_conversion_instructions.
|
||||||
|
// SourceType and TargetType must be integer or floating point scalar type.
|
||||||
|
|
||||||
|
// ConversionSelector::Convert converts an object of type S to an object of type
|
||||||
|
// T. S must be SourceType, a vector of SourceType, or a cooperative matrix of
|
||||||
|
// SourceType. T must be TargetType, a vector of TargetType, or a cooperative
|
||||||
|
// matrix of TargetType. T must have the same number of components as S. T is a
|
||||||
|
// cooperative matrix if and only if S is a cooperative matrix.
|
||||||
|
template <class SourceType, class TargetType> class ConversionSelector;
|
||||||
|
|
||||||
|
#define CONVERSION_SELECTOR(SourceType, TargetType, OpConvert) \
|
||||||
|
template <> class ConversionSelector<SourceType, TargetType> { \
|
||||||
|
template <class T, class S> static T Convert(S a) { \
|
||||||
|
return OpConvert<T>(a); \
|
||||||
|
} \
|
||||||
|
};
|
||||||
|
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
CONVERSION_SELECTOR(uint16_t, uint16_t, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, int16_t, __builtin_spv_Bitcast);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, uint32_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, int32_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, uint64_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, int64_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, half, __builtin_spv_ConvertUToF);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, float, __builtin_spv_ConvertUToF);
|
||||||
|
CONVERSION_SELECTOR(uint16_t, double, __builtin_spv_ConvertUToF);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(int16_t, uint16_t, __builtin_spv_Bitcast);
|
||||||
|
CONVERSION_SELECTOR(int16_t, int16_t, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(int16_t, uint32_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(int16_t, int32_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(int16_t, uint64_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(int16_t, int64_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(int16_t, half, __builtin_spv_ConvertSToF);
|
||||||
|
CONVERSION_SELECTOR(int16_t, float, __builtin_spv_ConvertSToF);
|
||||||
|
CONVERSION_SELECTOR(int16_t, double, __builtin_spv_ConvertSToF);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(uint32_t, uint16_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, int16_t, __builtin_spv_SConvert);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(int32_t, uint16_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(int32_t, int16_t, __builtin_spv_SConvert);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(uint64_t, uint16_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, int16_t, __builtin_spv_SConvert);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(int64_t, uint16_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(int64_t, int16_t, __builtin_spv_SConvert);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(half, uint16_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(half, int16_t, __builtin_spv_ConvertFtoS);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(float, uint16_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(float, int16_t, __builtin_spv_ConvertFtoS);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(double, uint16_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(double, int16_t, __builtin_spv_ConvertFtoS);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(uint32_t, uint32_t, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, int32_t, __builtin_spv_Bitcast);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, uint64_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, int64_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, half, __builtin_spv_ConvertUToF);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, float, __builtin_spv_ConvertUToF);
|
||||||
|
CONVERSION_SELECTOR(uint32_t, double, __builtin_spv_ConvertUToF);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(int32_t, uint32_t, __builtin_spv_Bitcast);
|
||||||
|
CONVERSION_SELECTOR(int32_t, int32_t, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(int32_t, uint64_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(int32_t, int64_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(int32_t, half, __builtin_spv_ConvertSToF);
|
||||||
|
CONVERSION_SELECTOR(int32_t, float, __builtin_spv_ConvertSToF);
|
||||||
|
CONVERSION_SELECTOR(int32_t, double, __builtin_spv_ConvertSToF);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(uint64_t, uint32_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, int32_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, uint64_t, __builtin_spv_Bitcast);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, int64_t, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, half, __builtin_spv_ConvertUToF);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, float, __builtin_spv_ConvertUToF);
|
||||||
|
CONVERSION_SELECTOR(uint64_t, double, __builtin_spv_ConvertUToF);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(int64_t, uint32_t, __builtin_spv_UConvert);
|
||||||
|
CONVERSION_SELECTOR(int64_t, int32_t, __builtin_spv_SConvert);
|
||||||
|
CONVERSION_SELECTOR(int64_t, uint64_t, __builtin_spv_Bitcast);
|
||||||
|
CONVERSION_SELECTOR(int64_t, int64_t, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(int64_t, half, __builtin_spv_ConvertSToF);
|
||||||
|
CONVERSION_SELECTOR(int64_t, float, __builtin_spv_ConvertSToF);
|
||||||
|
CONVERSION_SELECTOR(int64_t, double, __builtin_spv_ConvertSToF);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(half, uint32_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(half, int32_t, __builtin_spv_ConvertFtoS);
|
||||||
|
CONVERSION_SELECTOR(half, uint64_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(half, int64_t, __builtin_spv_ConvertFtoS);
|
||||||
|
CONVERSION_SELECTOR(half, half, __builtin_spv_CopyObject);
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
CONVERSION_SELECTOR(half, float, __builtin_spv_FConvert);
|
||||||
|
#else
|
||||||
|
CONVERSION_SELECTOR(half, float, __builtin_spv_CopyObject);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(half, double, __builtin_spv_FConvert);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(float, uint32_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(float, int32_t, __builtin_spv_ConvertFtoS);
|
||||||
|
CONVERSION_SELECTOR(float, uint64_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(float, int64_t, __builtin_spv_ConvertFtoS);
|
||||||
|
#if __HLSL_ENABLE_16_BIT
|
||||||
|
CONVERSION_SELECTOR(float, half, __builtin_spv_FConvert);
|
||||||
|
#else
|
||||||
|
CONVERSION_SELECTOR(float, half, __builtin_spv_CopyObject);
|
||||||
|
#endif
|
||||||
|
CONVERSION_SELECTOR(float, float, __builtin_spv_CopyObject);
|
||||||
|
CONVERSION_SELECTOR(float, double, __builtin_spv_FConvert);
|
||||||
|
|
||||||
|
CONVERSION_SELECTOR(double, uint32_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(double, int32_t, __builtin_spv_ConvertFtoS);
|
||||||
|
CONVERSION_SELECTOR(double, uint64_t, __builtin_spv_ConvertFtoU);
|
||||||
|
CONVERSION_SELECTOR(double, int64_t, __builtin_spv_ConvertFtoS);
|
||||||
|
CONVERSION_SELECTOR(double, half, __builtin_spv_FConvert);
|
||||||
|
CONVERSION_SELECTOR(double, float, __builtin_spv_FConvert);
|
||||||
|
CONVERSION_SELECTOR(double, double, __builtin_spv_CopyObject);
|
||||||
|
}; // namespace util
|
||||||
|
} // namespace vk
|
||||||
|
|
||||||
|
#endif // _HLSL_VK_KHR_OPCODE_SELECTOR_H_
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
// Copyright (c) 2024 Google LLC
|
||||||
|
//
|
||||||
|
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
|
||||||
|
// See https://llvm.org/LICENSE.txt for license information.
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||||
|
|
||||||
|
#ifndef _HLSL_VK_SPIRV_H_
|
||||||
|
#define _HLSL_VK_SPIRV_H_
|
||||||
|
|
||||||
|
namespace vk {
|
||||||
|
|
||||||
|
enum CooperativeMatrixUse {
|
||||||
|
CooperativeMatrixUseMatrixAKHR = 0,
|
||||||
|
CooperativeMatrixUseMatrixBKHR = 1,
|
||||||
|
CooperativeMatrixUseMatrixAccumulatorKHR = 2,
|
||||||
|
CooperativeMatrixUseMax = 0x7fffffff,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum CooperativeMatrixLayout {
|
||||||
|
CooperativeMatrixLayoutRowMajorKHR = 0,
|
||||||
|
CooperativeMatrixLayoutColumnMajorKHR = 1,
|
||||||
|
CooperativeMatrixLayoutRowBlockedInterleavedARM = 4202,
|
||||||
|
CooperativeMatrixLayoutColumnBlockedInterleavedARM = 4203,
|
||||||
|
CooperativeMatrixLayoutMax = 0x7fffffff,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum CooperativeMatrixOperandsMask {
|
||||||
|
CooperativeMatrixOperandsMaskNone = 0,
|
||||||
|
CooperativeMatrixOperandsMatrixASignedComponentsKHRMask = 0x00000001,
|
||||||
|
CooperativeMatrixOperandsMatrixBSignedComponentsKHRMask = 0x00000002,
|
||||||
|
CooperativeMatrixOperandsMatrixCSignedComponentsKHRMask = 0x00000004,
|
||||||
|
CooperativeMatrixOperandsMatrixResultSignedComponentsKHRMask = 0x00000008,
|
||||||
|
CooperativeMatrixOperandsSaturatingAccumulationKHRMask = 0x00000010,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum MemoryAccessMask {
|
||||||
|
MemoryAccessMaskNone = 0,
|
||||||
|
MemoryAccessVolatileMask = 0x00000001,
|
||||||
|
MemoryAccessAlignedMask = 0x00000002,
|
||||||
|
MemoryAccessNontemporalMask = 0x00000004,
|
||||||
|
MemoryAccessMakePointerAvailableMask = 0x00000008,
|
||||||
|
MemoryAccessMakePointerAvailableKHRMask = 0x00000008,
|
||||||
|
MemoryAccessMakePointerVisibleMask = 0x00000010,
|
||||||
|
MemoryAccessMakePointerVisibleKHRMask = 0x00000010,
|
||||||
|
MemoryAccessNonPrivatePointerMask = 0x00000020,
|
||||||
|
MemoryAccessNonPrivatePointerKHRMask = 0x00000020,
|
||||||
|
MemoryAccessAliasScopeINTELMaskMask = 0x00010000,
|
||||||
|
MemoryAccessNoAliasINTELMaskMask = 0x00020000,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum Scope {
|
||||||
|
ScopeCrossDevice = 0,
|
||||||
|
ScopeDevice = 1,
|
||||||
|
ScopeWorkgroup = 2,
|
||||||
|
ScopeSubgroup = 3,
|
||||||
|
ScopeInvocation = 4,
|
||||||
|
ScopeQueueFamily = 5,
|
||||||
|
ScopeQueueFamilyKHR = 5,
|
||||||
|
ScopeShaderCallKHR = 6,
|
||||||
|
ScopeMax = 0x7fffffff,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum StorageClass {
|
||||||
|
StorageClassWorkgroup = 4,
|
||||||
|
};
|
||||||
|
|
||||||
|
// An opaque type to represent a Spir-V pointer to the workgroup storage class.
|
||||||
|
// clang-format off
|
||||||
|
template <typename PointeeType>
|
||||||
|
using WorkgroupSpirvPointer = const vk::SpirvOpaqueType<
|
||||||
|
/* OpTypePointer */ 32,
|
||||||
|
vk::Literal<vk::integral_constant<uint, StorageClassWorkgroup> >,
|
||||||
|
PointeeType>;
|
||||||
|
// clang-format on
|
||||||
|
|
||||||
|
// Returns an opaque Spir-V pointer to v. The memory object v's storage class
|
||||||
|
// modifier must be groupshared. If the incorrect storage class is used, then
|
||||||
|
// there will be a validation error, and it will not show the correct
|
||||||
|
template <typename T>
|
||||||
|
[[vk::ext_instruction(/* OpCopyObject */ 83)]] WorkgroupSpirvPointer<T>
|
||||||
|
GetGroupSharedAddress([[vk::ext_reference]] T v);
|
||||||
|
|
||||||
|
} // namespace vk
|
||||||
|
|
||||||
|
#endif // _HLSL_VK_SPIRV_H_
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
//! HLSL standard headers that dxc compiles in and resolves for angled
|
||||||
|
//! includes when no file is found on disk (e.g. `#include <dx/linalg.h>`).
|
||||||
|
//! Copied from tools/clang/lib/Headers/hlsl; see hlsl-headers/LICENSE.txt.
|
||||||
|
|
||||||
|
pub const Header = struct { name: []const u8, text: []const u8 };
|
||||||
|
|
||||||
|
pub const headers = [_]Header{
|
||||||
|
.{ .name = "enable_if", .text = @embedFile("hlsl-headers/enable_if") },
|
||||||
|
.{ .name = "type_traits", .text = @embedFile("hlsl-headers/type_traits") },
|
||||||
|
.{ .name = "vector_utils", .text = @embedFile("hlsl-headers/vector_utils") },
|
||||||
|
.{ .name = "dx/linalg.h", .text = @embedFile("hlsl-headers/dx/linalg.h") },
|
||||||
|
.{ .name = "vk/opcode_selector.h", .text = @embedFile("hlsl-headers/vk/opcode_selector.h") },
|
||||||
|
.{ .name = "vk/spirv.h", .text = @embedFile("hlsl-headers/vk/spirv.h") },
|
||||||
|
.{ .name = "vk/khr/cooperative_matrix.h", .text = @embedFile("hlsl-headers/vk/khr/cooperative_matrix.h") },
|
||||||
|
.{ .name = "vk/khr/cooperative_matrix.impl", .text = @embedFile("hlsl-headers/vk/khr/cooperative_matrix.impl") },
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn find(name: []const u8) ?[]const u8 {
|
||||||
|
for (headers) |h| {
|
||||||
|
if (std.mem.eql(u8, h.name, name)) return h.text;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
Loading…
Reference in New Issue