From feab1bf63b25d47f8d59e7baad1a5cbebf60eba1 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 31 Oct 2026 00:16:50 -0700 Subject: [PATCH] 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 (, , ...) 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. Co-Authored-By: Claude Opus 5.5 --- build.zig | 13 + src/diag.zig | 83 ++ src/dxil/shader.zig | 34 +- src/front/lexer.zig | 365 +++++ src/front/pp_print.zig | 85 ++ src/front/preproc.zig | 1309 +++++++++++++++++ src/front/source.zig | 188 +++ src/main.zig | 144 +- src/root.zig | 11 + test/oracle/pp.sh | 57 + vendor/PROVENANCE.md | 2 +- vendor/hlsl-headers/LICENSE.txt | 222 +++ vendor/hlsl-headers/README.txt | 7 + vendor/hlsl-headers/dx/linalg.h | 727 +++++++++ vendor/hlsl-headers/enable_if | 29 + vendor/hlsl-headers/type_traits | 134 ++ vendor/hlsl-headers/vector_utils | 42 + .../hlsl-headers/vk/khr/cooperative_matrix.h | 275 ++++ .../vk/khr/cooperative_matrix.impl | 377 +++++ vendor/hlsl-headers/vk/opcode_selector.h | 227 +++ vendor/hlsl-headers/vk/spirv.h | 85 ++ vendor/hlsl_headers.zig | 25 + 22 files changed, 4407 insertions(+), 34 deletions(-) create mode 100644 src/diag.zig create mode 100644 src/front/lexer.zig create mode 100644 src/front/pp_print.zig create mode 100644 src/front/preproc.zig create mode 100644 src/front/source.zig create mode 100644 test/oracle/pp.sh create mode 100644 vendor/hlsl-headers/LICENSE.txt create mode 100644 vendor/hlsl-headers/README.txt create mode 100644 vendor/hlsl-headers/dx/linalg.h create mode 100644 vendor/hlsl-headers/enable_if create mode 100644 vendor/hlsl-headers/type_traits create mode 100644 vendor/hlsl-headers/vector_utils create mode 100644 vendor/hlsl-headers/vk/khr/cooperative_matrix.h create mode 100644 vendor/hlsl-headers/vk/khr/cooperative_matrix.impl create mode 100644 vendor/hlsl-headers/vk/opcode_selector.h create mode 100644 vendor/hlsl-headers/vk/spirv.h create mode 100644 vendor/hlsl_headers.zig diff --git a/build.zig b/build.zig index fd638d2..fbd2a95 100644 --- a/build.zig +++ b/build.zig @@ -4,10 +4,16 @@ pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); 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", .{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, + .imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }}, }); const exe = b.addExecutable(.{ @@ -40,4 +46,11 @@ pub fn build(b: *std.Build) void { oracle.setCwd(b.path(".")); oracle.has_side_effects = true; 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); } diff --git a/src/diag.zig b/src/diag.zig new file mode 100644 index 0000000..44e5cfb --- /dev/null +++ b/src/diag.zig @@ -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"); + } + } +}; diff --git a/src/dxil/shader.zig b/src/dxil/shader.zig index 93b9408..6c34c7f 100644 --- a/src/dxil/shader.zig +++ b/src/dxil/shader.zig @@ -13,6 +13,9 @@ pub const ShaderKind = enum(u8) { hull = 3, domain = 4, compute = 5, + library = 6, + mesh = 13, + amplification = 14, pub fn profilePrefix(k: ShaderKind) []const u8 { return switch (k) { @@ -22,22 +25,41 @@ pub const ShaderKind = enum(u8) { .hull => "hs", .domain => "ds", .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 { kind: ShaderKind, major: u8, minor: u8, + /// Parses `_6_`, e.g. `cs_6_6` or `lib_6_10`. 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| { - 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; - if (s[3] != '6' or s[5] < '0' or s[5] > '9') return null; - return .{ .kind = kind, .major = 6, .minor = s[5] - '0' }; + if (!std.mem.eql(u8, major_str, "6")) return null; + 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(@as(u8, 6), p.minor); 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); } diff --git a/src/front/lexer.zig b/src/front/lexer.zig new file mode 100644 index 0000000..1dc03b3 --- /dev/null +++ b/src/front/lexer.zig @@ -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); +} diff --git a/src/front/pp_print.zig b/src/front/pp_print.zig new file mode 100644 index 0000000..8f02827 --- /dev/null +++ b/src/front/pp_print.zig @@ -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; +} diff --git a/src/front/preproc.zig b/src/front/preproc.zig new file mode 100644 index 0000000..90989bc --- /dev/null +++ b/src/front/preproc.zig @@ -0,0 +1,1309 @@ +//! C preprocessor for HLSL, modelled on clang's: a stack of token sources +//! (files and macro expansions), with macros disabled while their expansion +//! is being rescanned and identifiers painted `no_expand` when they name a +//! disabled macro. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const source = @import("source.zig"); +const lexer = @import("lexer.zig"); +const Diagnostics = @import("../diag.zig").Diagnostics; +const Token = lexer.Token; +const Kind = lexer.Kind; +const Loc = source.Loc; + +pub const Define = struct { + name: []const u8, + /// null means `1`, as with `-D NAME`. + value: ?[]const u8 = null, +}; + +pub const Options = struct { + defines: []const Define = &.{}, + include_dirs: []const []const u8 = &.{}, + /// DXIL::ShaderKind of the target profile. + stage: u32 = 5, + major: u32 = 6, + minor: u32 = 0, + spirv: bool = false, + enable_16bit: bool = false, +}; + +const Builtin = enum { + none, + line, + file, + counter, + include_level, + base_file, + /// `__has_feature(x)`: function-like, valid anywhere (as in clang). + has_feature, + /// `__has_builtin(x)` and friends: always 0. + has_nothing, +}; + +const Macro = struct { + name: []const u8, + function_like: bool = false, + variadic: bool = false, + params: []const []const u8 = &.{}, + body: []const Token = &.{}, + builtin: Builtin = .none, + disabled: bool = false, + loc: Loc = .none, + + fn paramIndex(m: *const Macro, t: Token) ?usize { + if (!m.function_like or t.kind != .identifier) return null; + for (m.params, 0..) |p, i| { + if (std.mem.eql(u8, p, t.text)) return i; + } + return null; + } + + fn sameDefinition(a: *const Macro, b: *const Macro) bool { + if (a.function_like != b.function_like or a.variadic != b.variadic) return false; + if (a.params.len != b.params.len or a.body.len != b.body.len) return false; + for (a.params, b.params) |x, y| if (!std.mem.eql(u8, x, y)) return false; + for (a.body, b.body, 0..) |x, y, i| { + if (x.kind != y.kind or !std.mem.eql(u8, x.text, y.text)) return false; + if (i > 0 and x.flags.space != y.flags.space) return false; + } + return true; + } +}; + +const Context = struct { + tokens: []const Token, + pos: usize = 0, + /// Macro re-enabled when this context is exhausted. + macro: ?*Macro = null, + /// Barrier for isolated expansion (macro arguments, #if): returns eof + /// instead of reading past it. + barrier: bool = false, +}; + +const Cond = struct { + /// Some group in this #if chain has been taken. + taken: bool, + seen_else: bool, + loc: Loc, +}; + +const IncludeFrame = struct { + lex: lexer.Lexer, + /// Directory of this file, for quoted includes. + dir: []const u8, + cond_base: usize, +}; + +const LineOverride = struct { + /// Physical line of the #line directive. + phys_line: u32, + line: u32, + name: ?[]const u8, +}; + +pub const Error = Allocator.Error; + +pub const PresumedLoc = struct { file: []const u8, line: u32 }; + +const max_include_depth = 200; +const embedded_prefix = "/"; +const hlsl_headers = @import("hlsl_headers"); + +pub const Preprocessor = struct { + arena: Allocator, + sm: *source.SourceManager, + diags: *Diagnostics, + opts: Options, + macros: std.StringHashMapUnmanaged(*Macro) = .empty, + contexts: std.ArrayList(Context) = .empty, + includes: std.ArrayList(IncludeFrame) = .empty, + conds: std.ArrayList(Cond) = .empty, + pushback: std.ArrayList(Raw) = .empty, + pragma_once: std.StringHashMapUnmanaged(void) = .empty, + line_overrides: std.AutoHashMapUnmanaged(source.FileId, std.ArrayList(LineOverride)) = .empty, + counter: u32 = 0, + main_file: ?source.FileId = null, + + const Raw = struct { tok: Token, from_file: bool }; + + /// `arena` owns everything the preprocessor allocates, including the + /// text of returned tokens. + pub fn init(arena: Allocator, sm: *source.SourceManager, diags: *Diagnostics, opts: Options) Preprocessor { + return .{ .arena = arena, .sm = sm, .diags = diags, .opts = opts }; + } + + /// Enter the main file. Returns false (with a diagnostic) if it cannot + /// be read. + pub fn enterMainFile(pp: *Preprocessor, path: []const u8) !bool { + const id = try pp.sm.load(path) orelse { + pp.diags.err(.none, "cannot open file '{s}'", .{path}); + return false; + }; + try pp.enterFileId(id); + pp.main_file = id; + try pp.enterPredefines(); + return true; + } + + /// Enter in-memory main file text (used by tests and the library API). + pub fn enterMainText(pp: *Preprocessor, path: []const u8, text: []const u8) !void { + const id = try pp.sm.addFile(path, text); + try pp.enterFileId(id); + pp.main_file = id; + try pp.enterPredefines(); + } + + fn enterFileId(pp: *Preprocessor, id: source.FileId) !void { + const f = pp.sm.file(id); + try pp.includes.append(pp.arena, .{ + .lex = .init(f.text, id), + .dir = std.fs.path.dirname(f.path) orelse ".", + .cond_base = pp.conds.items.len, + }); + } + + /// Predefined macros are processed as a pseudo-file of #defines entered + /// on top of the main file, so they are seen first. + fn enterPredefines(pp: *Preprocessor) !void { + const builtins = [_]struct { []const u8, Builtin }{ + .{ "__LINE__", .line }, .{ "__FILE__", .file }, + .{ "__COUNTER__", .counter }, .{ "__INCLUDE_LEVEL__", .include_level }, + .{ "__BASE_FILE__", .base_file }, .{ "__has_feature", .has_feature }, + .{ "__has_extension", .has_feature }, .{ "__has_builtin", .has_nothing }, + .{ "__has_attribute", .has_nothing }, .{ "__has_cpp_attribute", .has_nothing }, + .{ "__has_declspec_attribute", .has_nothing }, + }; + for (builtins) |b| { + const m = try pp.arena.create(Macro); + m.* = .{ .name = b[0], .builtin = b[1] }; + try pp.macros.put(pp.arena, b[0], m); + } + + var text: std.Io.Writer.Allocating = .init(pp.arena); + const w = &text.writer; + const o = pp.opts; + try w.writeAll( + \\#define __hlsl_dx_compiler 1 + \\#define __clang__ 1 + \\#define __clang_major__ 3 + \\#define __clang_minor__ 7 + \\#define __clang_patchlevel__ 0 + \\#define __llvm__ 1 + \\#define __DXC_VERSION_MAJOR 1 + \\#define __DXC_VERSION_MINOR 10 + \\#define __DXC_VERSION_RELEASE 0 + \\#define __DXC_VERSION_COMMITS 0 + \\#define __HLSL_VERSION 2021 + \\#define __SHADER_STAGE_VERTEX 1 + \\#define __SHADER_STAGE_PIXEL 0 + \\#define __SHADER_STAGE_GEOMETRY 2 + \\#define __SHADER_STAGE_HULL 3 + \\#define __SHADER_STAGE_DOMAIN 4 + \\#define __SHADER_STAGE_COMPUTE 5 + \\#define __SHADER_STAGE_AMPLIFICATION 14 + \\#define __SHADER_STAGE_MESH 13 + \\#define __SHADER_STAGE_LIBRARY 6 + \\ + ); + try w.print("#define __SHADER_TARGET_STAGE {d}\n#define __SHADER_TARGET_MAJOR {d}\n#define __SHADER_TARGET_MINOR {d}\n", .{ o.stage, o.major, o.minor }); + if (o.enable_16bit) try w.writeAll("#define __HLSL_ENABLE_16_BIT 1\n"); + if (o.spirv) try w.writeAll("#define __spirv__ 1\n#define __SPIRV_MAJOR_VERSION__ 1\n#define __SPIRV_MINOR_VERSION__ 0\n"); + for (o.defines) |d| try w.print("#define {s} {s}\n", .{ d.name, d.value orelse "1" }); + + const id = try pp.sm.addFile("", text.written()); + try pp.enterFileId(id); + } + + // --------------------------------------------------------------------- + // Raw token sources + + fn currentLexer(pp: *Preprocessor) ?*lexer.Lexer { + if (pp.includes.items.len == 0) return null; + return &pp.includes.items[pp.includes.items.len - 1].lex; + } + + fn lexRaw(pp: *Preprocessor) Error!Raw { + if (pp.pushback.pop()) |r| return r; + while (pp.contexts.items.len > 0) { + const ctx = &pp.contexts.items[pp.contexts.items.len - 1]; + if (ctx.barrier) return .{ .tok = .{ .kind = .eof, .text = "", .loc = .none }, .from_file = false }; + if (ctx.pos < ctx.tokens.len) { + defer ctx.pos += 1; + return .{ .tok = ctx.tokens[ctx.pos], .from_file = false }; + } + if (ctx.macro) |m| m.disabled = false; + _ = pp.contexts.pop(); + } + while (pp.includes.items.len > 0) { + const frame = &pp.includes.items[pp.includes.items.len - 1]; + const t = frame.lex.next(); + if (t.kind != .eof) return .{ .tok = t, .from_file = true }; + // End of file: diagnose unterminated conditionals, pop. + while (pp.conds.items.len > frame.cond_base) { + const c = pp.conds.pop().?; + pp.diags.err(c.loc, "unterminated conditional directive", .{}); + } + if (pp.includes.items.len == 1) { + return .{ .tok = t, .from_file = true }; + } + _ = pp.includes.pop(); + } + return .{ .tok = .{ .kind = .eof, .text = "", .loc = .none }, .from_file = true }; + } + + /// Raw token with directives handled. `#pragma` lines come back as + /// `.pragma` tokens. + fn lexRawSkipDirectives(pp: *Preprocessor) Error!Raw { + while (true) { + const r = try pp.lexRaw(); + if (r.from_file and r.tok.kind == .hash and r.tok.flags.bol) { + if (try pp.handleDirective(r.tok)) |pragma| return .{ .tok = pragma, .from_file = true }; + continue; + } + return r; + } + } + + /// Next fully macro-expanded token. + pub fn next(pp: *Preprocessor) Error!Token { + while (true) { + const r = try pp.lexRawSkipDirectives(); + const t = r.tok; + if (t.kind != .identifier or t.flags.no_expand) return t; + const m = pp.macros.get(t.text) orelse return t; + if (m.disabled) { + var painted = t; + painted.flags.no_expand = true; + return painted; + } + if (try pp.expandMacro(m, t)) continue; + return t; + } + } + + // --------------------------------------------------------------------- + // Macro expansion + + fn expandMacro(pp: *Preprocessor, m: *Macro, name: Token) Error!bool { + if (m.builtin == .has_feature or m.builtin == .has_nothing) { + return pp.expandFeatureCheck(m, name); + } + if (m.builtin != .none) { + const tok = try pp.builtinToken(m.builtin, name); + const toks = try pp.arena.alloc(Token, 1); + toks[0] = tok; + try pp.contexts.append(pp.arena, .{ .tokens = toks }); + return true; + } + + var args: ?[]const []const Token = null; + if (m.function_like) { + const r = try pp.lexRawSkipDirectives(); + if (r.tok.kind != .l_paren) { + try pp.pushback.append(pp.arena, r); + return false; + } + args = try pp.collectArgs(m, name) orelse return true; // error: drop invocation + } + + const result = try pp.substitute(m, args); + for (result, 0..) |*t, i| { + t.loc = name.loc; + if (i == 0) { + t.flags.space = name.flags.space; + t.flags.bol = name.flags.bol; + } else t.flags.bol = false; + } + m.disabled = true; + try pp.contexts.append(pp.arena, .{ .tokens = result, .macro = m }); + return true; + } + + /// `__has_feature(name)` and similar: consume `( ident )`, push 0 or 1. + fn expandFeatureCheck(pp: *Preprocessor, m: *const Macro, name: Token) Error!bool { + const open = try pp.lexRawSkipDirectives(); + if (open.tok.kind != .l_paren) { + pp.diags.err(name.loc, "builtin feature check macro requires a parenthesized identifier", .{}); + try pp.pushback.append(pp.arena, open); + return false; + } + const ident = try pp.lexRawSkipDirectives(); + const close = try pp.lexRawSkipDirectives(); + if (ident.tok.kind != .identifier or close.tok.kind != .r_paren) { + pp.diags.err(name.loc, "builtin feature check macro requires a parenthesized identifier", .{}); + if (close.tok.kind != .r_paren) try pp.pushback.append(pp.arena, close); + return true; + } + const known = m.builtin == .has_feature and pp.opts.spirv and std.mem.eql(u8, ident.tok.text, "hlsl_vk_buffer_pointer"); + const toks = try pp.arena.alloc(Token, 1); + toks[0] = numberToken(if (known) "1" else "0", name); + try pp.contexts.append(pp.arena, .{ .tokens = toks }); + return true; + } + + /// Collect raw argument tokens up to the matching ')'. Null on error. + fn collectArgs(pp: *Preprocessor, m: *const Macro, name: Token) Error!?[]const []const Token { + var args: std.ArrayList([]const Token) = .empty; + var cur: std.ArrayList(Token) = .empty; + var depth: u32 = 0; + while (true) { + const r = try pp.lexRawSkipDirectives(); + var t = r.tok; + switch (t.kind) { + .eof => { + pp.diags.err(name.loc, "unterminated function-like macro invocation '{s}'", .{m.name}); + if (!r.from_file) try pp.pushback.append(pp.arena, r); + return null; + }, + .l_paren => depth += 1, + .r_paren => { + if (depth == 0) break; + depth -= 1; + }, + .comma => if (depth == 0 and !(m.variadic and args.items.len + 1 >= m.params.len)) { + try args.append(pp.arena, try cur.toOwnedSlice(pp.arena)); + continue; + }, + else => {}, + } + // Identifiers naming a currently disabled macro stay painted. + if (t.kind == .identifier and !t.flags.no_expand) { + if (pp.macros.get(t.text)) |am| { + if (am.disabled) t.flags.no_expand = true; + } + } + t.flags.bol = false; + try cur.append(pp.arena, t); + } + try args.append(pp.arena, try cur.toOwnedSlice(pp.arena)); + + var n = args.items.len; + if (m.params.len == 0 and n == 1 and args.items[0].len == 0) n = 0; + if (m.variadic) { + if (n + 1 < m.params.len) { + pp.diags.err(name.loc, "too few arguments provided to function-like macro invocation '{s}'", .{m.name}); + return null; + } + while (args.items.len < m.params.len) try args.append(pp.arena, &.{}); + } else if (n != m.params.len) { + if (n < m.params.len) { + pp.diags.err(name.loc, "too few arguments provided to function-like macro invocation '{s}'", .{m.name}); + } else { + pp.diags.err(name.loc, "too many arguments provided to function-like macro invocation '{s}'", .{m.name}); + } + return null; + } + return args.items[0..m.params.len]; + } + + /// Fully macro-expand `tokens` in isolation. + fn expandIsolated(pp: *Preprocessor, tokens: []const Token) Error![]Token { + const saved_pushback = pp.pushback; + pp.pushback = .empty; + defer pp.pushback = saved_pushback; + + const base = pp.contexts.items.len; + try pp.contexts.append(pp.arena, .{ .tokens = &.{}, .barrier = true }); + try pp.contexts.append(pp.arena, .{ .tokens = tokens }); + var out: std.ArrayList(Token) = .empty; + while (true) { + const t = try pp.next(); + if (t.kind == .eof and pp.contexts.items.len == base + 1 and pp.contexts.items[base].barrier) break; + try out.append(pp.arena, t); + } + _ = pp.contexts.pop(); + return out.items; + } + + fn substitute(pp: *Preprocessor, m: *const Macro, args: ?[]const []const Token) Error![]Token { + var out: std.ArrayList(Token) = .empty; + // Parallel flags: true where `out[i]` is a ## operator from the body. + var paste: std.ArrayList(bool) = .empty; + var expanded_cache: []?[]Token = &.{}; + if (args) |a| { + expanded_cache = try pp.arena.alloc(?[]Token, a.len); + @memset(expanded_cache, null); + } + + const body = m.body; + var i: usize = 0; + while (i < body.len) : (i += 1) { + const t = body[i]; + if (args) |a| { + if (t.kind == .hash and i + 1 < body.len) { + if (m.paramIndex(body[i + 1])) |p| { + var s = try pp.stringify(a[p], t.loc); + s.flags.space = t.flags.space; + try out.append(pp.arena, s); + try paste.append(pp.arena, false); + i += 1; + continue; + } + } + // GNU `, ## __VA_ARGS__`: drop the comma when empty. + if (m.variadic and t.kind == .comma and i + 2 < body.len and body[i + 1].kind == .hash_hash) { + if (m.paramIndex(body[i + 2])) |p| if (p == m.params.len - 1) { + if (a[p].len != 0) { + try out.append(pp.arena, t); + try paste.append(pp.arena, false); + for (a[p]) |at| { + try out.append(pp.arena, at); + try paste.append(pp.arena, false); + } + } + i += 2; + continue; + }; + } + if (m.paramIndex(t)) |p| { + const next_paste = i + 1 < body.len and body[i + 1].kind == .hash_hash; + const prev_paste = i > 0 and body[i - 1].kind == .hash_hash; + const toks: []const Token = if (next_paste or prev_paste) a[p] else blk: { + if (expanded_cache[p] == null) expanded_cache[p] = try pp.expandIsolated(a[p]); + break :blk expanded_cache[p].?; + }; + if (toks.len == 0) { + // Placemarker, removed after pasting. + try out.append(pp.arena, .{ .kind = .invalid, .text = "", .loc = t.loc }); + try paste.append(pp.arena, false); + } + for (toks, 0..) |at, j| { + var c = at; + if (j == 0) c.flags.space = t.flags.space; + try out.append(pp.arena, c); + try paste.append(pp.arena, false); + } + continue; + } + } + try out.append(pp.arena, t); + try paste.append(pp.arena, t.kind == .hash_hash); + } + + // Token pasting. + var res: std.ArrayList(Token) = .empty; + var k: usize = 0; + while (k < out.items.len) : (k += 1) { + if (paste.items[k] and res.items.len > 0 and k + 1 < out.items.len) { + const lhs = res.pop().?; + const rhs = out.items[k + 1]; + k += 1; + try res.append(pp.arena, try pp.pasteTokens(lhs, rhs)); + continue; + } + try res.append(pp.arena, out.items[k]); + } + // Drop placemarkers. + var w: usize = 0; + for (res.items) |t| { + if (t.kind == .invalid and t.text.len == 0) continue; + res.items[w] = t; + w += 1; + } + return res.items[0..w]; + } + + fn pasteTokens(pp: *Preprocessor, lhs: Token, rhs: Token) Error!Token { + if (lhs.kind == .invalid and lhs.text.len == 0) return rhs; + if (rhs.kind == .invalid and rhs.text.len == 0) return lhs; + const text = try std.mem.concat(pp.arena, u8, &.{ lhs.text, rhs.text }); + var l = lexer.Lexer.init(text, lhs.loc.file); + const t = l.next(); + var result: Token = .{ .kind = t.kind, .flags = lhs.flags, .text = text, .loc = lhs.loc }; + result.flags.no_expand = false; + if (t.text.len != text.len) { + pp.diags.err(lhs.loc, "pasting formed '{s}', an invalid preprocessing token", .{text}); + result.kind = .invalid; + } + return result; + } + + fn stringify(pp: *Preprocessor, toks: []const Token, loc: Loc) Error!Token { + var buf: std.ArrayList(u8) = .empty; + try buf.append(pp.arena, '"'); + for (toks, 0..) |t, i| { + if (i > 0 and t.flags.space) try buf.append(pp.arena, ' '); + if (t.kind == .string or t.kind == .char) { + for (t.text) |c| { + if (c == '"' or c == '\\') try buf.append(pp.arena, '\\'); + try buf.append(pp.arena, c); + } + } else try buf.appendSlice(pp.arena, t.text); + } + try buf.append(pp.arena, '"'); + return .{ .kind = .string, .text = buf.items, .loc = loc }; + } + + fn builtinToken(pp: *Preprocessor, b: Builtin, name: Token) Error!Token { + var tok: Token = .{ .kind = .number, .flags = name.flags, .text = "", .loc = name.loc }; + switch (b) { + .none, .has_feature, .has_nothing => unreachable, + .line => tok.text = try std.fmt.allocPrint(pp.arena, "{d}", .{pp.presumedLoc(name.loc).line}), + .counter => { + tok.text = try std.fmt.allocPrint(pp.arena, "{d}", .{pp.counter}); + pp.counter += 1; + }, + .include_level => tok.text = try std.fmt.allocPrint(pp.arena, "{d}", .{pp.includes.items.len -| 1}), + .file, .base_file => { + const path = if (b == .file) pp.presumedLoc(name.loc).file else pp.sm.file(pp.main_file.?).path; + tok.kind = .string; + tok.text = try quoteString(pp.arena, path); + }, + } + return tok; + } + + pub fn presumedLoc(pp: *const Preprocessor, loc: Loc) PresumedLoc { + if (loc.isNone()) return .{ .file = "", .line = 0 }; + const phys = pp.sm.lineCol(loc).line; + var result: PresumedLoc = .{ .file = pp.sm.file(loc.file).path, .line = phys }; + if (pp.line_overrides.get(loc.file)) |list| { + for (list.items) |ov| { + if (ov.phys_line >= phys) break; + result.line = ov.line + (phys - ov.phys_line - 1); + if (ov.name) |n| result.file = n; + } + } + return result; + } + + // --------------------------------------------------------------------- + // Directives + + /// Raw tokens up to the end of the directive line, from the current file. + fn directiveTokens(pp: *Preprocessor) Error![]Token { + const lx = pp.currentLexer().?; + var out: std.ArrayList(Token) = .empty; + while (true) { + const saved = lx.*; + const t = lx.next(); + if (t.kind == .eof or t.flags.bol) { + lx.* = saved; + break; + } + try out.append(pp.arena, t); + } + return out.items; + } + + fn skipRestOfLine(pp: *Preprocessor) void { + pp.currentLexer().?.skipLine(); + } + + /// Handle a directive whose `#` has been read. Returns a token for + /// `#pragma` lines that are passed through. + fn handleDirective(pp: *Preprocessor, hash: Token) Error!?Token { + const lx = pp.currentLexer().?; + const saved = lx.*; + const name = lx.next(); + if (name.kind == .eof or name.flags.bol) { + lx.* = saved; // null directive + return null; + } + if (name.kind != .identifier) { + pp.diags.err(name.loc, "invalid preprocessing directive", .{}); + pp.skipRestOfLine(); + return null; + } + const d = name.text; + if (std.mem.eql(u8, d, "define")) { + try pp.handleDefine(); + } else if (std.mem.eql(u8, d, "undef")) { + const toks = try pp.directiveTokens(); + if (toks.len == 0 or toks[0].kind != .identifier) { + pp.diags.err(name.loc, "macro name missing", .{}); + } else _ = pp.macros.remove(toks[0].text); + } else if (std.mem.eql(u8, d, "include")) { + try pp.handleInclude(name); + } else if (std.mem.eql(u8, d, "if")) { + const v = try pp.evalCondition(name); + try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = hash.loc }); + if (!v) try pp.skipGroup(); + } else if (std.mem.eql(u8, d, "ifdef") or std.mem.eql(u8, d, "ifndef")) { + const toks = try pp.directiveTokens(); + var v = false; + if (toks.len == 0 or toks[0].kind != .identifier) { + pp.diags.err(name.loc, "macro name missing", .{}); + } else v = pp.macros.contains(toks[0].text); + if (d.len == 6) v = !v; // ifndef + try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = hash.loc }); + if (!v) try pp.skipGroup(); + } else if (std.mem.eql(u8, d, "elif") or std.mem.eql(u8, d, "else")) { + // Reached from an active group: the chain is done, skip the rest. + if (!pp.inFileConditional()) { + pp.diags.err(hash.loc, "#{s} without #if", .{d}); + pp.skipRestOfLine(); + return null; + } + const c = &pp.conds.items[pp.conds.items.len - 1]; + if (c.seen_else) pp.diags.err(hash.loc, "#{s} after #else", .{d}); + if (std.mem.eql(u8, d, "else")) c.seen_else = true; + pp.skipRestOfLine(); + try pp.skipGroup(); + } else if (std.mem.eql(u8, d, "endif")) { + if (!pp.inFileConditional()) { + pp.diags.err(hash.loc, "#endif without #if", .{}); + } else _ = pp.conds.pop(); + pp.skipRestOfLine(); + } else if (std.mem.eql(u8, d, "pragma")) { + const body = lx.restOfLine(); + if (std.mem.eql(u8, body, "once")) { + const key = try pp.fileKey(pp.sm.file(lx.file).path); + try pp.pragma_once.put(pp.arena, key, {}); + return null; + } + return .{ .kind = .pragma, .flags = .{ .bol = true }, .text = body, .loc = hash.loc }; + } else if (std.mem.eql(u8, d, "error")) { + pp.diags.err(hash.loc, "{s}", .{lx.restOfLine()}); + } else if (std.mem.eql(u8, d, "warning")) { + pp.diags.warn(hash.loc, "{s}", .{lx.restOfLine()}); + } else if (std.mem.eql(u8, d, "line")) { + try pp.handleLine(name); + } else { + pp.diags.err(name.loc, "invalid preprocessing directive", .{}); + pp.skipRestOfLine(); + } + return null; + } + + fn inFileConditional(pp: *Preprocessor) bool { + const frame = pp.includes.items[pp.includes.items.len - 1]; + return pp.conds.items.len > frame.cond_base; + } + + /// Skip a false group. Stops after an #elif that evaluates true, an + /// #else (when nothing was taken), or the matching #endif. + fn skipGroup(pp: *Preprocessor) Error!void { + const lx = pp.currentLexer().?; + var depth: u32 = 0; + while (true) { + const t = lx.next(); + if (t.kind == .eof) { + // Put it back so lexRaw sees EOF and diagnoses. + lx.pos = @intCast(lx.text.len); + return; + } + if (!(t.kind == .hash and t.flags.bol)) { + lx.skipLine(); + continue; + } + const saved = lx.*; + const d = lx.next(); + if (d.flags.bol or d.kind != .identifier) { + lx.* = saved; + continue; + } + const name = d.text; + if (std.mem.startsWith(u8, name, "if")) { + if (std.mem.eql(u8, name, "if") or std.mem.eql(u8, name, "ifdef") or std.mem.eql(u8, name, "ifndef")) depth += 1; + lx.skipLine(); + continue; + } + if (std.mem.eql(u8, name, "endif")) { + lx.skipLine(); + if (depth == 0) { + _ = pp.conds.pop(); + return; + } + depth -= 1; + continue; + } + if (depth > 0) { + lx.skipLine(); + continue; + } + const c = &pp.conds.items[pp.conds.items.len - 1]; + if (std.mem.eql(u8, name, "else")) { + lx.skipLine(); + if (c.seen_else) pp.diags.err(t.loc, "#else after #else", .{}); + c.seen_else = true; + if (!c.taken) { + c.taken = true; + return; + } + continue; + } + if (std.mem.eql(u8, name, "elif")) { + if (c.seen_else) pp.diags.err(t.loc, "#elif after #else", .{}); + if (c.taken) { + lx.skipLine(); + continue; + } + if (try pp.evalCondition(d)) { + c.taken = true; + return; + } + continue; + } + lx.skipLine(); + } + } + + fn handleDefine(pp: *Preprocessor) Error!void { + const lx = pp.currentLexer().?; + const toks = try pp.directiveTokens(); + if (toks.len == 0 or toks[0].kind != .identifier) { + pp.diags.err(if (toks.len > 0) toks[0].loc else .none, "macro name must be an identifier", .{}); + return; + } + _ = lx; + const name = toks[0]; + if (std.mem.eql(u8, name.text, "defined")) { + pp.diags.err(name.loc, "'defined' cannot be used as a macro name", .{}); + return; + } + const m = try pp.arena.create(Macro); + m.* = .{ .name = name.text, .loc = name.loc }; + var i: usize = 1; + // Function-like only when '(' immediately follows the name. + if (toks.len > 1 and toks[1].kind == .l_paren and !toks[1].flags.space) { + m.function_like = true; + var params: std.ArrayList([]const u8) = .empty; + i = 2; + while (true) { + if (i >= toks.len) { + pp.diags.err(name.loc, "missing ')' in macro parameter list", .{}); + return; + } + const t = toks[i]; + i += 1; + if (t.kind == .r_paren and params.items.len == 0) break; + if (t.kind == .ellipsis) { + m.variadic = true; + try params.append(pp.arena, "__VA_ARGS__"); + if (i >= toks.len or toks[i].kind != .r_paren) { + pp.diags.err(t.loc, "missing ')' in macro parameter list", .{}); + return; + } + i += 1; + break; + } + if (t.kind != .identifier) { + pp.diags.err(t.loc, "invalid token in macro parameter list", .{}); + return; + } + try params.append(pp.arena, t.text); + if (i < toks.len and toks[i].kind == .ellipsis) { + // Named variadic parameter (GNU): `args...` + m.variadic = true; + i += 1; + } + if (i >= toks.len) continue; + if (toks[i].kind == .comma) { + i += 1; + continue; + } + if (toks[i].kind == .r_paren) { + i += 1; + break; + } + pp.diags.err(toks[i].loc, "expected comma in macro parameter list", .{}); + return; + } + m.params = params.items; + } + const body = toks[i..]; + if (body.len > 0) { + if (body[0].kind == .hash_hash or body[body.len - 1].kind == .hash_hash) { + pp.diags.err(body[0].loc, "'##' cannot appear at either end of a macro expansion", .{}); + return; + } + body[0].flags.space = false; + } + for (body) |*t| t.flags.bol = false; + m.body = body; + if (pp.macros.get(name.text)) |old| { + if (old.builtin != .none) { + pp.diags.warn(name.loc, "redefining builtin macro", .{}); + } else if (!old.sameDefinition(m)) { + pp.diags.warn(name.loc, "'{s}' macro redefined", .{name.text}); + } + } + try pp.macros.put(pp.arena, name.text, m); + } + + fn handleInclude(pp: *Preprocessor, directive: Token) Error!void { + const lx = pp.currentLexer().?; + var spelled: []const u8 = undefined; + var angled = false; + if (lx.headerName()) |h| { + spelled = h.text[1 .. h.text.len - 1]; + angled = true; + pp.skipRestOfLine(); + } else { + const raw = try pp.directiveTokens(); + const toks = try pp.expandIsolated(raw); + if (toks.len >= 1 and toks[0].kind == .string and toks[0].text.len >= 2) { + spelled = toks[0].text[1 .. toks[0].text.len - 1]; + } else if (toks.len >= 2 and toks[0].kind == .less) { + var buf: std.ArrayList(u8) = .empty; + for (toks[1..]) |t| { + if (t.kind == .greater) break; + if (t.flags.space and buf.items.len > 0) try buf.append(pp.arena, ' '); + try buf.appendSlice(pp.arena, t.text); + } + spelled = buf.items; + angled = true; + } else { + pp.diags.err(directive.loc, "expected \"FILENAME\" or ", .{}); + return; + } + } + + if (pp.includes.items.len >= max_include_depth) { + pp.diags.err(directive.loc, "#include nested too deeply", .{}); + return; + } + const id = try pp.resolveInclude(spelled, angled) orelse { + pp.diags.add(.fatal, directive.loc, "'{s}' file not found", .{spelled}); + return; + }; + if (pp.pragma_once.contains(try pp.fileKey(pp.sm.file(id).path))) return; + try pp.enterFileId(id); + } + + fn resolveInclude(pp: *Preprocessor, spelled: []const u8, angled: bool) Error!?source.FileId { + if (std.fs.path.isAbsolute(spelled)) return pp.sm.load(spelled); + const frame = pp.includes.items[pp.includes.items.len - 1]; + const local = try std.fs.path.join(pp.arena, &.{ frame.dir, spelled }); + if (try pp.sm.load(local)) |id| return id; + for (pp.opts.include_dirs) |dir| { + const p = try std.fs.path.join(pp.arena, &.{ dir, spelled }); + if (try pp.sm.load(p)) |id| return id; + } + // Like dxc, fall back to the compiled-in HLSL headers for <...>. + if (angled) { + var name = try pp.arena.dupe(u8, spelled); + std.mem.replaceScalar(u8, name, '\\', '/'); + if (hlsl_headers.find(name)) |text| { + name = try std.mem.concat(pp.arena, u8, &.{ embedded_prefix, name }); + for (pp.sm.files.items, 0..) |f, i| { + if (std.mem.eql(u8, f.path, name)) return @intCast(i); + } + return try pp.sm.addFile(name, text); + } + } + return null; + } + + fn fileKey(pp: *Preprocessor, path: []const u8) Error![]const u8 { + return std.fs.path.resolveAlloc(pp.arena, &.{path}); + } + + fn handleLine(pp: *Preprocessor, directive: Token) Error!void { + const raw = try pp.directiveTokens(); + const toks = try pp.expandIsolated(raw); + if (toks.len == 0 or toks[0].kind != .number) { + pp.diags.err(directive.loc, "#line directive requires a positive integer argument", .{}); + return; + } + const n = std.fmt.parseInt(u32, toks[0].text, 10) catch { + pp.diags.err(toks[0].loc, "#line directive requires a simple digit sequence", .{}); + return; + }; + var name: ?[]const u8 = null; + if (toks.len > 1) { + if (toks[1].kind != .string) { + pp.diags.err(toks[1].loc, "invalid filename for #line directive", .{}); + return; + } + name = try unquoteString(pp.arena, toks[1].text); + } + const file = pp.currentLexer().?.file; + const gop = try pp.line_overrides.getOrPut(pp.arena, file); + if (!gop.found_existing) gop.value_ptr.* = .empty; + try gop.value_ptr.append(pp.arena, .{ + .phys_line = pp.sm.lineCol(directive.loc).line, + .line = n, + .name = name, + }); + } + + // --------------------------------------------------------------------- + // #if expressions + + fn evalCondition(pp: *Preprocessor, directive: Token) Error!bool { + const raw = try pp.directiveTokens(); + // Resolve `defined` and feature checks before expansion. + var pre: std.ArrayList(Token) = .empty; + var i: usize = 0; + while (i < raw.len) : (i += 1) { + const t = raw[i]; + if (t.isIdent("defined")) { + var j = i + 1; + const paren = j < raw.len and raw[j].kind == .l_paren; + if (paren) j += 1; + if (j >= raw.len or raw[j].kind != .identifier) { + pp.diags.err(t.loc, "macro name missing after 'defined'", .{}); + return false; + } + const v = pp.macros.contains(raw[j].text); + if (paren) { + j += 1; + if (j >= raw.len or raw[j].kind != .r_paren) { + pp.diags.err(t.loc, "missing ')' after 'defined'", .{}); + return false; + } + } + try pre.append(pp.arena, numberToken(if (v) "1" else "0", t)); + i = j; + continue; + } + if (t.isIdent("__has_include") or t.isIdent("__has_include_next")) { + // __has_include("file") / __has_include() + var j = i + 1; + var found = false; + if (j < raw.len and raw[j].kind == .l_paren) { + j += 1; + var spelled: std.ArrayList(u8) = .empty; + if (j < raw.len and raw[j].kind == .string) { + try spelled.appendSlice(pp.arena, raw[j].text[1 .. raw[j].text.len - 1]); + j += 1; + } else if (j < raw.len and raw[j].kind == .less) { + j += 1; + while (j < raw.len and raw[j].kind != .greater) : (j += 1) try spelled.appendSlice(pp.arena, raw[j].text); + j += 1; + } + found = try pp.resolveInclude(spelled.items, raw[i + 2].kind == .less) != null; + } + if (j >= raw.len or raw[j].kind != .r_paren) { + pp.diags.err(t.loc, "missing ')' after '__has_include'", .{}); + return false; + } + try pre.append(pp.arena, numberToken(if (found) "1" else "0", t)); + i = j; + continue; + } + try pre.append(pp.arena, t); + } + const toks = try pp.expandIsolated(pre.items); + if (toks.len == 0) { + pp.diags.err(directive.loc, "#{s} with no expression", .{directive.text}); + return false; + } + var ev: Eval = .{ .pp = pp, .toks = toks }; + const v = ev.expr(0) catch return false; + if (ev.pos < toks.len) { + pp.diags.err(toks[ev.pos].loc, "token is not a valid binary operator in a preprocessor subexpression", .{}); + return false; + } + return v.v != 0; + } +}; + +fn numberToken(text: []const u8, at: Token) Token { + return .{ .kind = .number, .flags = at.flags, .text = text, .loc = at.loc }; +} + +fn quoteString(a: Allocator, s: []const u8) ![]const u8 { + var buf: std.ArrayList(u8) = .empty; + try buf.append(a, '"'); + for (s) |c| { + if (c == '"' or c == '\\') try buf.append(a, '\\'); + try buf.append(a, c); + } + try buf.append(a, '"'); + return buf.items; +} + +fn unquoteString(a: Allocator, s: []const u8) ![]const u8 { + var buf: std.ArrayList(u8) = .empty; + var i: usize = 1; + while (i + 1 < s.len) : (i += 1) { + if (s[i] == '\\' and i + 2 < s.len) i += 1; + try buf.append(a, s[i]); + } + return buf.items; +} + +const Value = struct { + v: i64, + unsigned: bool = false, + + fn of(b: bool) Value { + return .{ .v = @intFromBool(b) }; + } +}; + +const Eval = struct { + pp: *Preprocessor, + toks: []const Token, + pos: usize = 0, + + const EvalError = error{EvalFailed}; + + fn peek(e: *Eval) ?Token { + return if (e.pos < e.toks.len) e.toks[e.pos] else null; + } + + fn fail(e: *Eval, comptime msg: []const u8) EvalError { + const loc = if (e.peek()) |t| t.loc else if (e.toks.len > 0) e.toks[e.toks.len - 1].loc else Loc.none; + e.pp.diags.err(loc, msg, .{}); + return error.EvalFailed; + } + + fn precedence(k: Kind) ?u8 { + return switch (k) { + .question => 1, + .pipe_pipe => 2, + .amp_amp => 3, + .pipe => 4, + .caret => 5, + .amp => 6, + .equal_equal, .exclaim_equal => 7, + .less, .less_equal, .greater, .greater_equal => 8, + .less_less, .greater_greater => 9, + .plus, .minus => 10, + .star, .slash, .percent => 11, + else => null, + }; + } + + fn expr(e: *Eval, min_prec: u8) EvalError!Value { + var lhs = try e.unary(); + while (e.peek()) |op| { + const prec = precedence(op.kind) orelse break; + if (prec < min_prec) break; + e.pos += 1; + if (op.kind == .question) { + const t = try e.expr(0); + const colon = e.peek() orelse return e.fail("expected ':' in preprocessor expression"); + if (colon.kind != .colon) return e.fail("expected ':' in preprocessor expression"); + e.pos += 1; + const f = try e.expr(1); + lhs = if (lhs.v != 0) t else f; + lhs.unsigned = t.unsigned or f.unsigned; + continue; + } + const rhs = try e.expr(prec + 1); + lhs = try e.binary(op, lhs, rhs); + } + return lhs; + } + + fn binary(e: *Eval, op: Token, a: Value, b: Value) EvalError!Value { + const u = a.unsigned or b.unsigned; + const au: u64 = @bitCast(a.v); + const bu: u64 = @bitCast(b.v); + return switch (op.kind) { + .pipe_pipe => Value.of(a.v != 0 or b.v != 0), + .amp_amp => Value.of(a.v != 0 and b.v != 0), + .pipe => .{ .v = a.v | b.v, .unsigned = u }, + .caret => .{ .v = a.v ^ b.v, .unsigned = u }, + .amp => .{ .v = a.v & b.v, .unsigned = u }, + .equal_equal => Value.of(a.v == b.v), + .exclaim_equal => Value.of(a.v != b.v), + .less => Value.of(if (u) au < bu else a.v < b.v), + .less_equal => Value.of(if (u) au <= bu else a.v <= b.v), + .greater => Value.of(if (u) au > bu else a.v > b.v), + .greater_equal => Value.of(if (u) au >= bu else a.v >= b.v), + .less_less => .{ .v = if (b.v >= 64 or b.v < 0) 0 else a.v << @intCast(b.v), .unsigned = a.unsigned }, + .greater_greater => .{ + .v = if (b.v >= 64 or b.v < 0) 0 else if (a.unsigned) @bitCast(au >> @intCast(b.v)) else a.v >> @intCast(b.v), + .unsigned = a.unsigned, + }, + .plus => .{ .v = a.v +% b.v, .unsigned = u }, + .minus => .{ .v = a.v -% b.v, .unsigned = u }, + .star => .{ .v = a.v *% b.v, .unsigned = u }, + .slash, .percent => blk: { + if (b.v == 0) { + e.pp.diags.err(op.loc, "division by zero in preprocessor expression", .{}); + return error.EvalFailed; + } + if (u) break :blk .{ .v = @bitCast(if (op.kind == .slash) au / bu else au % bu), .unsigned = true }; + if (a.v == std.math.minInt(i64) and b.v == -1) break :blk .{ .v = if (op.kind == .slash) a.v else 0 }; + break :blk .{ .v = if (op.kind == .slash) @divTrunc(a.v, b.v) else @rem(a.v, b.v) }; + }, + else => unreachable, + }; + } + + fn unary(e: *Eval) EvalError!Value { + const t = e.peek() orelse return e.fail("expected value in expression"); + e.pos += 1; + switch (t.kind) { + .plus => return e.unary(), + .minus => { + const v = try e.unary(); + return .{ .v = -%v.v, .unsigned = v.unsigned }; + }, + .tilde => { + const v = try e.unary(); + return .{ .v = ~v.v, .unsigned = v.unsigned }; + }, + .exclaim => return Value.of((try e.unary()).v == 0), + .l_paren => { + const v = try e.expr(0); + const r = e.peek() orelse return e.fail("expected ')' in preprocessor expression"); + if (r.kind != .r_paren) return e.fail("expected ')' in preprocessor expression"); + e.pos += 1; + return v; + }, + .number => return parseInt(t.text) orelse { + e.pp.diags.err(t.loc, "invalid integer constant in preprocessor expression", .{}); + return error.EvalFailed; + }, + .char => return .{ .v = charValue(t.text) }, + .identifier => { + // Remaining identifiers are 0, except C++ true/false. + return .{ .v = @intFromBool(std.mem.eql(u8, t.text, "true")) }; + }, + else => { + e.pos -= 1; + return e.fail("invalid token at start of a preprocessor expression"); + }, + } + } +}; + +fn parseInt(text: []const u8) ?Value { + var end = text.len; + var unsigned = false; + while (end > 0) { + const c = text[end - 1]; + if (c == 'u' or c == 'U') { + unsigned = true; + } else if (c != 'l' and c != 'L') break; + end -= 1; + } + const digits = text[0..end]; + if (digits.len == 0) return null; + var base: u8 = 10; + var body = digits; + if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) { + base = 16; + body = digits[2..]; + } else if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'b' or digits[1] == 'B')) { + base = 2; + body = digits[2..]; + } else if (digits.len > 1 and digits[0] == '0') { + base = 8; + body = digits[1..]; + } + const v = std.fmt.parseInt(u64, body, base) catch return null; + return .{ .v = @bitCast(v), .unsigned = unsigned or v > std.math.maxInt(i64) }; +} + +fn charValue(text: []const u8) i64 { + if (text.len < 3) return 0; + const body = text[1 .. text.len - 1]; + if (body[0] != '\\') return body[0]; + if (body.len < 2) return 0; + return switch (body[1]) { + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + '0' => 0, + '\\' => '\\', + '\'' => '\'', + '"' => '"', + else => body[1], + }; +} + +// ------------------------------------------------------------------------- +// Tests + +const TestPP = struct { + mfs: source.MemoryFs = .{}, + sm: source.SourceManager = undefined, + diags: Diagnostics = undefined, + arena: std.heap.ArenaAllocator = undefined, + pp: Preprocessor = undefined, + + fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void { + const gpa = std.testing.allocator; + for (files) |f| try t.mfs.put(gpa, f[0], f[1]); + t.sm = .init(gpa, t.mfs.fileSystem()); + t.diags = .init(gpa); + t.arena = .init(gpa); + t.pp = .init(t.arena.allocator(), &t.sm, &t.diags, opts); + try t.pp.enterMainText("main.hlsl", main); + } + + fn deinit(t: *TestPP) void { + const gpa = std.testing.allocator; + t.arena.deinit(); + t.diags.deinit(); + t.sm.deinit(); + t.mfs.deinit(gpa); + } + + /// Expanded tokens joined by single spaces. + fn output(t: *TestPP) ![]const u8 { + var buf: std.ArrayList(u8) = .empty; + const a = t.arena.allocator(); + while (true) { + const tok = try t.pp.next(); + if (tok.kind == .eof) break; + if (buf.items.len > 0) try buf.append(a, ' '); + if (tok.kind == .pragma) try buf.appendSlice(a, "#pragma "); + try buf.appendSlice(a, tok.text); + } + return buf.items; + } +}; + +fn expectPP(main: []const u8, expected: []const u8) !void { + var t: TestPP = .{}; + try t.init(&.{}, main, .{}); + defer t.deinit(); + try std.testing.expectEqualStrings(expected, try t.output()); + for (t.diags.list.items) |d| std.debug.print("unexpected diagnostic: {s}\n", .{d.message}); + try std.testing.expectEqual(@as(u32, 0), t.diags.error_count); +} + +test "object and function-like macros" { + try expectPP("#define A 1 + 2\nint x = A;", "int x = 1 + 2 ;"); + try expectPP("#define F(a, b) a * b\nF(1, (2, 3))", "1 * ( 2 , 3 )"); + try expectPP("#define F(x) x\nF", "F"); + try expectPP("#define E()\nE() x", "x"); +} + +test "stringify and paste" { + try expectPP("#define S(x) #x\nS(a \"b\" c)", "\"a \\\"b\\\" c\""); + try expectPP("#define C(a,b) a##b\nC(foo, 12) C(,x) C(y,)", "foo12 x y"); + try expectPP("#define X(n) v##n\n#define v1 one\nX(1)", "one"); +} + +test "recursion is blocked and painted" { + try expectPP("#define foo foo bar\nfoo", "foo bar"); + try expectPP("#define f(x) x g\n#define g f\nf(1)(2)", "1 f ( 2 )"); + // Standard example: nested macro arguments are pre-expanded. + try expectPP("#define x 3\n#define f(a) f(x * (a))\n#undef x\n#define x 2\n#define g f\nf(y+1)", "f ( 2 * ( y + 1 ) )"); +} + +test "variadic macros" { + try expectPP("#define V(fmt, ...) p(fmt, __VA_ARGS__)\nV(a, 1, 2)", "p ( a , 1 , 2 )"); + try expectPP("#define V(fmt, ...) p(fmt , ## __VA_ARGS__)\nV(a) V(a,b)", "p ( a ) p ( a , b )"); +} + +test "conditionals" { + try expectPP("#if 1 + 1 == 2 && defined(Q) == 0\nyes\n#else\nno\n#endif", "yes"); + try expectPP("#define Q\n#ifdef Q\na\n#elif 1\nb\n#else\nc\n#endif", "a"); + try expectPP("#if 0\n#if 1\nx\n#endif\n#elif 2 > 1\ny\n#endif", "y"); + try expectPP("#if 0\n'unterminated in skipped block\n#endif\nz", "z"); + try expectPP("#if (-1 < 0u) || 0x10 != 16\nbad\n#else\ngood\n#endif", "good"); + try expectPP("#ifndef __HLSL_VERSION\nbad\n#elif __HLSL_VERSION >= 2021\ngood\n#endif", "good"); +} + +test "include, pragma once, line, builtins" { + var t: TestPP = .{}; + try t.init(&.{ + .{ "./inc.h", "#pragma once\nint inc;\n" }, + .{ "sys/s.h", "int sys;" }, + }, "#include \"inc.h\"\n#include \"inc.h\"\n#include \n#line 50 \"x.hlsl\"\nint l = __LINE__; __FILE__\n#pragma pack_matrix(row_major)\n", .{ .include_dirs = &.{"sys"} }); + defer t.deinit(); + try std.testing.expectEqualStrings("int inc ; int sys ; int l = 50 ; \"x.hlsl\" #pragma pack_matrix(row_major)", try t.output()); + try std.testing.expectEqual(@as(u32, 0), t.diags.error_count); +} + +test "errors are diagnosed" { + var t: TestPP = .{}; + try t.init(&.{}, "#error boom\n#if 1\n", .{}); + defer t.deinit(); + _ = try t.output(); + try std.testing.expectEqual(@as(u32, 2), t.diags.error_count); +} diff --git a/src/front/source.zig b/src/front/source.zig new file mode 100644 index 0000000..61d9c2b --- /dev/null +++ b/src/front/source.zig @@ -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); +} diff --git a/src/main.zig b/src/main.zig index b920ea6..5f7dd48 100644 --- a/src/main.zig +++ b/src/main.zig @@ -3,6 +3,7 @@ const Io = std.Io; const zdxc = @import("zdxc"); const shader = zdxc.dxil.shader; const container = zdxc.dxil.container; +const front = zdxc.front; const usage = \\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler @@ -10,15 +11,23 @@ const usage = \\USAGE: zdxc [options] \\ \\OPTIONS: - \\ -T Target profile (cs_6_0 .. cs_6_9, vs_, ps_, gs_) - \\ -E Entry point name (default: main) - \\ -Fo Output object file - \\ -spirv Generate SPIR-V - \\ --version Print version + \\ -T Target profile (cs_6_0 .. cs_6_9, vs_, ps_, gs_) + \\ -E Entry point name (default: main) + \\ -Fo Output object file + \\ -spirv Generate SPIR-V + \\ -D [=] Define a macro + \\ -I Add an include directory + \\ -P Preprocess only (to -Fi , or stdout) + \\ -Fi Output file for -P + \\ -HV 2021 HLSL version (only 2021 is supported) + \\ -enable-16bit-types Enable 16-bit types + \\ --version Print version \\ \\DEVELOPMENT (temporary, until the frontend lands): - \\ -zdxc-empty Emit an empty shader for -T instead of compiling - \\ -zdxc-check-hash Verify the container hash of + \\ -zdxc-empty Emit an empty shader for -T instead of compiling + \\ -zdxc-check-hash Verify the container hash of + \\ -zdxc-lex Print the tokens of , one per line (no preprocessing; + \\ `#line` lines are skipped) \\ ; @@ -28,8 +37,14 @@ const Options = struct { output: ?[]const u8 = null, input: ?[]const u8 = null, 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, check_hash: bool = false, + lex: bool = false, }; const Cli = struct { @@ -48,7 +63,7 @@ pub fn main(init: std.process.Init) !u8 { const io = init.io; var stderr_buf: [1024]u8 = undefined; 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); const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface }; @@ -60,36 +75,56 @@ pub fn main(init: std.process.Init) !u8 { 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 i: usize = 1; while (i < args.len) : (i += 1) { 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")) { - opts.profile = try next(cli, args, &i, a); + opts.profile = try optionValue(cli, args, &i, "-T"); } 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")) { - 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")) { 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")) { opts.empty = true; } else if (std.mem.eql(u8, a, "-zdxc-check-hash")) { opts.check_hash = true; + } else if (std.mem.eql(u8, a, "-zdxc-lex")) { + opts.lex = true; } else if (std.mem.eql(u8, a, "--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")) { try stdout.writeAll(usage); - return; + return null; } else if (a.len > 0 and a[0] == '-') { return cli.fail("unknown argument: '{s}'", .{a}); } else { @@ -97,27 +132,80 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: * 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) { 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)); - var view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{path}); - _ = &view; + const view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{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 }); return; } - const profile_str = opts.profile orelse return cli.fail("missing -T ", .{}); - const profile = shader.Profile.parse(profile_str) orelse return cli.fail("unknown profile '{s}'", .{profile_str}); + if (opts.lex) { + 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)", .{}); - if (profile.kind != .compute) return cli.fail("-zdxc-empty supports compute profiles only", .{}); + const profile: ?shader.Profile = if (opts.profile) |p| + 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 ", .{}); + 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) try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } }) 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 ", .{}); try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes }); diff --git a/src/root.zig b/src/root.zig index 3bad157..2934b18 100644 --- a/src/root.zig +++ b/src/root.zig @@ -1,5 +1,14 @@ //! 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 bitstream = @import("dxil/bitstream.zig"); pub const container = @import("dxil/container.zig"); @@ -16,6 +25,8 @@ pub const version = "0.0.0"; test { const std = @import("std"); + std.testing.refAllDecls(front); std.testing.refAllDecls(dxil); std.testing.refAllDecls(spirv); + _ = @import("diag.zig"); } diff --git a/test/oracle/pp.sh b/test/oracle/pp.sh new file mode 100644 index 0000000..1a3c6f1 --- /dev/null +++ b/test/oracle/pp.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# Preprocessor oracle: zdxc -P must produce the same token stream as dxc -P +# (ignoring #line markers and whitespace) over the DXC HLSL test corpus. +# +# Usage: test/oracle/pp.sh [corpus-dir...] +set -u + +ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1") +shift +DXC_ROOT=${DXC_ROOT:-..} +DXC=${DXC_BUILD:-$DXC_ROOT/build}/bin/dxc +[ $# -gt 0 ] || set -- "$DXC_ROOT/tools/clang/test/CodeGenHLSL" "$DXC_ROOT/tools/clang/test/CodeGenDXIL" "$DXC_ROOT/tools/clang/test/CodeGenSPIRV" +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +find "$@" -name '*.hlsl' | sort > "$TMP/files" + +check_one() { + f=$1 + run=$(grep -m1 'RUN:' "$f") + target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//') + [ -n "$target" ] || target=cs_6_0 + defs=$(printf '%s' "$run" | grep -oE -- '-D *[A-Za-z_][A-Za-z0-9_]*(=[^ ]*)?' | sed 's/-D */-D/' | tr '\n' ' ') + extra="" + printf '%s' "$run" | grep -q -- '-spirv' && extra="$extra -spirv" + printf '%s' "$run" | grep -q -- '-enable-16bit-types' && extra="$extra -enable-16bit-types" + id=$(printf '%s' "$f" | cksum | cut -d' ' -f1) + out="$TMP/$id" + # dxc -P exits 0 even on fatal errors (e.g. a missing #include); treat any + # reported error as "dxc rejected". + # shellcheck disable=SC2086 + "$DXC" -P -HV 2021 -T "$target" $extra $defs "$f" -Fi "$out.ref" >/dev/null 2>"$out.dxcerr" || { echo "SKIP $f"; return; } + grep -q 'error' "$out.dxcerr" && { echo "SKIP $f"; return; } + # shellcheck disable=SC2086 + if ! "$ZDXC" -P -T "$target" $extra $defs "$f" -Fi "$out.zd" > "$out.err" 2>&1; then + echo "FAIL $f (zdxc error: $(head -1 "$out.err"))" + return + fi + "$ZDXC" -zdxc-lex "$out.ref" > "$out.ref.tok" + "$ZDXC" -zdxc-lex "$out.zd" > "$out.zd.tok" + if cmp -s "$out.ref.tok" "$out.zd.tok"; then + echo "PASS $f" + else + echo "FAIL $f (first diff: $(diff "$out.ref.tok" "$out.zd.tok" | grep -m2 '^[<>]' | tr '\n' ' '))" + fi +} + +export -f check_one 2>/dev/null || true +export ZDXC DXC TMP +while read -r f; do check_one "$f"; done < "$TMP/files" > "$TMP/results" + +grep '^FAIL' "$TMP/results" | head -${SHOW_FAILS:-30} +pass=$(grep -c '^PASS' "$TMP/results") +fail=$(grep -c '^FAIL' "$TMP/results") +skip=$(grep -c '^SKIP' "$TMP/results") +echo "oracle pp: $pass passed, $fail failed, $skip skipped (dxc rejected)" +[ "$fail" -eq 0 ] diff --git a/vendor/PROVENANCE.md b/vendor/PROVENANCE.md index 2874f9f..9161555 100644 --- a/vendor/PROVENANCE.md +++ b/vendor/PROVENANCE.md @@ -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 | |---|---|---|---| -| _(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 in the DXC tree); SPIRV-Headers files are under the Khronos MIT-style license. diff --git a/vendor/hlsl-headers/LICENSE.txt b/vendor/hlsl-headers/LICENSE.txt new file mode 100644 index 0000000..94472c3 --- /dev/null +++ b/vendor/hlsl-headers/LICENSE.txt @@ -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. diff --git a/vendor/hlsl-headers/README.txt b/vendor/hlsl-headers/README.txt new file mode 100644 index 0000000..a760bb9 --- /dev/null +++ b/vendor/hlsl-headers/README.txt @@ -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. diff --git a/vendor/hlsl-headers/dx/linalg.h b/vendor/hlsl-headers/dx/linalg.h new file mode 100644 index 0000000..151b874 --- /dev/null +++ b/vendor/hlsl-headers/dx/linalg.h @@ -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 +#include + +#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 struct ComponentTypeTraits { + using Type = uint; + static const bool IsNativeScalar = false; + static const uint ElementsPerScalar = 4; +}; + +template struct TypeTraits { + static const ComponentEnum CompType = + (ComponentEnum)dxil::ComponentType::Invalid; +}; + +template struct IsComponentTypeAvailable { + static const bool value = true; +}; + +#if !__HLSL_ENABLE_16_BIT +template <> struct IsComponentTypeAvailable { + static const bool value = false; +}; +template <> struct IsComponentTypeAvailable { + static const bool value = false; +}; +template <> struct IsComponentTypeAvailable { + static const bool value = false; +}; +#endif + +template struct IsCompatibleVectorElement { + static const bool IsPackedCarrier = + hlsl::is_same::value || + hlsl::is_same::value; + static const bool value = + IsComponentTypeAvailable::value && + (hlsl::is_same::Type>::value || + (!ComponentTypeTraits::IsNativeScalar && IsPackedCarrier)); +}; + +template <> struct ComponentTypeTraits { + using Type = uint; + static const bool IsNativeScalar = false; + static const uint ElementsPerScalar = 2; +}; + +#define __MATRIX_SCALAR_COMPONENT_MAPPING(enum_val, type) \ + template <> struct ComponentTypeTraits { \ + using Type = type; \ + static const bool IsNativeScalar = true; \ + static const uint ElementsPerScalar = 1; \ + }; \ + template <> struct TypeTraits { \ + 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 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::ElementsPerScalar + + ComponentTypeTraits::ElementsPerScalar - 1) / + ComponentTypeTraits::ElementsPerScalar; +}; + +template struct DimMN { + static const SIZE_TYPE M = MVal; + static const SIZE_TYPE N = NVal; +}; + +template struct DimMN { + static const SIZE_TYPE M = NVal; + static const SIZE_TYPE N = MVal; +}; + +template +struct ScalarCountFromPackedComponents { + static const SIZE_TYPE ElementsPerScalar = + ComponentTypeTraits::ElementsPerScalar; + static const SIZE_TYPE Value = + (PackedComponentCount + ElementsPerScalar - 1) / ElementsPerScalar; +}; + +template struct DefaultAlign { + enum { + MinDim = M < N ? M : N, + ScalarCount = ScalarCountFromPackedComponents::Value, + ByteAlign = ScalarCount * 4, + MinByteAlign = ByteAlign < 4 ? 4 : ByteAlign, + Value = MinByteAlign < 16 ? MinByteAlign : 16 + }; +}; + +} // namespace __detail + +template struct VectorRef { + ByteAddressBuffer Buf; + uint Offset; +}; + +template struct InterpretedVector { + vector Data; + static const ComponentEnum Interpretation = CT; + static const SIZE_TYPE Size = + __detail::ComponentTypeTraits::ElementsPerScalar * N; +}; + +template +typename hlsl::enable_if< __detail::IsCompatibleVectorElement::value, + InterpretedVector >::type +MakeInterpretedVector(vector Vec) { + InterpretedVector IV = {Vec}; + return IV; +} + +template +typename hlsl::enable_if< + DestCT != OriginCT && __detail::IsComponentTypeAvailable::value && + __detail::IsCompatibleVectorElement::value, + InterpretedVector::Type, + __detail::DstN::Value, + DestCT> >::type +Convert(vector Vec) { + vector::Type, + __detail::DstN::Value> + Result; + dx::__builtin_LinAlg_Convert(Result, Vec, OriginCT, DestCT); + return MakeInterpretedVector(Result); +} + +template +typename hlsl::enable_if< + DestCT == OriginCT && + __detail::IsCompatibleVectorElement::value, + InterpretedVector >::type +Convert(vector Vec) { + return MakeInterpretedVector(Vec); +} + +template +class Matrix { + using ElementType = typename __detail::ComponentTypeTraits::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::ElementsPerScalar; + static const bool IsNativeScalar = + __detail::ComponentTypeTraits::IsNativeScalar; + + using HandleT = __builtin_LinAlgMatrix + [[__LinAlgMatrix_Attributes(CT, M, N, Use, Scope)]]; + HandleT __handle; + + template + [[nodiscard]] Matrix::M, + __detail::DimMN::N, NewUse, Scope> + Cast() { + Matrix::M, + __detail::DimMN::N, NewUse, Scope> + Result; + dx::__builtin_LinAlg_CopyConvertMatrix(Result.__handle, __handle, + Transpose); + return Result; + } + + template + [[nodiscard]] static + typename hlsl::enable_if::value, Matrix>::type + Splat(Ty Val) { + Matrix Result; + dx::__builtin_LinAlg_FillMatrix(Result.__handle, hlsl::is_signed::value, + Val); + return Result; + } + + template ::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 ::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 + [[nodiscard]] static typename hlsl::enable_if< + (hlsl::is_same::type, + ElementType>::value || + hlsl::is_integral_or_packed_integral< + typename hlsl::strip_vector_type::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 + typename hlsl::enable_if::type + Length() { + return dx::__builtin_LinAlg_MatrixLength(__handle); + } + + template + typename hlsl::enable_if::type + GetCoordinate(uint Index) { + return dx::__builtin_LinAlg_MatrixGetCoordinate(__handle, Index); + } + + template + typename hlsl::enable_if::type + Get(uint Index) { + ElementType Result; + dx::__builtin_LinAlg_MatrixGetElement(Result, __handle, Index); + return Result; + } + + template + typename hlsl::enable_if::type + Set(uint Index, ElementType Value) { + dx::__builtin_LinAlg_MatrixSetElement(__handle, __handle, Index, Value); + } + + template ::Value> + void Store(RWByteAddressBuffer Res, uint StartOffset, uint Stride, + MatrixLayoutEnum Layout) { + dx::__builtin_LinAlg_MatrixStoreToDescriptor(__handle, Res, StartOffset, + Stride, Layout, Align); + } + + template + typename hlsl::enable_if< + (hlsl::is_same::type, + ElementType>::value || + hlsl::is_integral_or_packed_integral< + typename hlsl::strip_vector_type::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 ::Value, + MatrixUseEnum UseLocal = Use> + typename hlsl::enable_if::type + InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset, uint Stride, + MatrixLayoutEnum Layout) { + dx::__builtin_LinAlg_MatrixAccumulateToDescriptor( + __handle, Res, StartOffset, Stride, Layout, Align); + } + + template + typename hlsl::enable_if< + hlsl::is_same::type, + ElementType>::value && + hlsl::is_arithmetic_vector::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 hlsl::enable_if< + hlsl::is_same::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 + typename hlsl::enable_if::type + Accumulate(const Matrix MatrixA) { + dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixA.__handle); + } + + template + typename hlsl::enable_if::type + Accumulate(const Matrix MatrixB) { + dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixB.__handle); + } + + template + typename hlsl::enable_if::type + MultiplyAccumulate(const Matrix MatrixA, + const Matrix 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 +class Matrix { + using ElementType = typename __detail::ComponentTypeTraits::Type; + + using HandleT = __builtin_LinAlgMatrix + [[__LinAlgMatrix_Attributes(CT, M, N, Use, MatrixScope::Thread)]]; + HandleT __handle; + + template + [[nodiscard]] static + typename hlsl::enable_if::type + Load(ByteAddressBuffer Res, uint StartOffset, uint Stride) { + Matrix Result; + dx::__builtin_LinAlg_MatrixLoadFromDescriptor( + Result.__handle, Res, StartOffset, Stride, Layout, Align); + return Result; + } + + template + typename hlsl::enable_if::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 +[[nodiscard]] Matrix +Multiply(const Matrix MatrixA, + const Matrix MatrixB) { + Matrix Result; + dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, + MatrixB.__handle); + return Result; +} + +template +[[nodiscard]] Matrix +Multiply(const Matrix MatrixA, + const Matrix MatrixB) { + Matrix Result; + dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, + MatrixB.__handle); + return Result; +} + +template +[[nodiscard]] Matrix +Multiply( + const Matrix MatrixA, + const Matrix MatrixB) { + Matrix Result; + dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, + MatrixB.__handle); + return Result; +} + +template +[[nodiscard]] Matrix +Multiply( + const Matrix MatrixA, + const Matrix MatrixB) { + Matrix 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 hlsl::enable_if::value, + vector >::type +Multiply(Matrix MatrixA, + vector Vec) { + vector Result; + dx::__builtin_LinAlg_MatrixVectorMultiply( + Result, MatrixA.__handle, hlsl::is_signed::value, Vec, + __detail::TypeTraits::CompType); + return Result; +} + +template +typename hlsl::enable_if< + InterpretedVector::Size == K && + __detail::IsCompatibleVectorElement::value, + vector >::type +Multiply(Matrix MatrixA, + InterpretedVector InterpVec) { + vector Result; + dx::__builtin_LinAlg_MatrixVectorMultiply( + Result, MatrixA.__handle, hlsl::is_signed::value, + InterpVec.Data, InterpVec.Interpretation); + return Result; +} + +template +typename hlsl::enable_if::value && + hlsl::is_arithmetic::value, + vector >::type +MultiplyAdd(Matrix MatrixA, + vector Vec, vector Bias) { + + InterpretedVector::CompType> + BiasConvInterp = Convert<__detail::TypeTraits::CompType, + __detail::TypeTraits::CompType>(Bias); + + vector Result; + dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( + Result, MatrixA.__handle, hlsl::is_signed::value, Vec, + __detail::TypeTraits::CompType, BiasConvInterp.Data); + return Result; +} + +template +typename hlsl::enable_if< + VecK == __detail::ScalarCountFromPackedComponents::Value && + __detail::IsCompatibleVectorElement::value && + hlsl::is_arithmetic::value, + vector >::type +MultiplyAdd(Matrix MatrixA, + InterpretedVector InterpVec, + vector Bias) { + + InterpretedVector::CompType> + BiasConvInterp = Convert<__detail::TypeTraits::CompType, + __detail::TypeTraits::CompType>(Bias); + + vector Result; + dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( + Result, MatrixA.__handle, hlsl::is_signed::value, + InterpVec.Data, InterpVec.Interpretation, BiasConvInterp.Data); + return Result; +} + +template +typename hlsl::enable_if::value, + vector >::type +MultiplyAdd(Matrix MatrixA, + vector Vec, VectorRef BiasRef) { + + using BiasVecTy = + vector::Type, + __detail::ScalarCountFromPackedComponents::Value>; + BiasVecTy Bias = BiasRef.Buf.template Load(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, and if OutputTy is half, Convert will return + // vector instead of vector. + // https://github.com/microsoft/DirectXShaderCompiler/issues/8418 + // + // Convert to OutputTy vector with padding + using BiasConvInterpPaddedTy = InterpretedVector< + OutputTy, + __detail::DstN< + __detail::TypeTraits::CompType, BiasCT, + __detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value, + __detail::TypeTraits::CompType>; + + BiasConvInterpPaddedTy BiasConvInterpPadded = + Convert<__detail::TypeTraits::CompType, BiasCT>(Bias); + + // Truncate the vector to the correct size M + vector BiasConv = (vector)BiasConvInterpPadded.Data; + + vector Result; + dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( + Result, MatrixA.__handle, hlsl::is_signed::value, Vec, + __detail::TypeTraits::CompType, BiasConv); + return Result; +} + +template +typename hlsl::enable_if< + VecK == __detail::ScalarCountFromPackedComponents::Value && + __detail::IsCompatibleVectorElement::value, + vector >::type +MultiplyAdd(Matrix MatrixA, + InterpretedVector InterpVec, + VectorRef BiasRef) { + using BiasVecTy = + vector::Type, + __detail::ScalarCountFromPackedComponents::Value>; + BiasVecTy Bias = BiasRef.Buf.template Load(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, and if OutputTy is half, Convert will return + // vector instead of vector. + // https://github.com/microsoft/DirectXShaderCompiler/issues/8418 + // + // Convert to OutputTy vector with padding + using BiasConvInterpPaddedTy = InterpretedVector< + OutputTy, + __detail::DstN< + __detail::TypeTraits::CompType, BiasCT, + __detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value, + __detail::TypeTraits::CompType>; + + BiasConvInterpPaddedTy BiasConvInterpPadded = + Convert<__detail::TypeTraits::CompType, BiasCT>(Bias); + + // Truncate the vector to the correct size M + vector BiasConv = (vector)BiasConvInterpPadded.Data; + + vector Result; + dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( + Result, MatrixA.__handle, hlsl::is_signed::value, + InterpVec.Data, InterpVec.Interpretation, BiasConv); + return Result; +} + +// Outer product functions +template +[[nodiscard]] typename hlsl::enable_if< + hlsl::is_arithmetic::value, + Matrix >::type +OuterProduct(vector VecA, vector VecB) { + Matrix Result; + dx::__builtin_LinAlg_MatrixOuterProduct( + Result.__handle, hlsl::is_signed::value, VecA, VecB); + return Result; +} + +template +typename hlsl::enable_if::value, void>::type +InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset, + vector 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_ diff --git a/vendor/hlsl-headers/enable_if b/vendor/hlsl-headers/enable_if new file mode 100644 index 0000000..d63354f --- /dev/null +++ b/vendor/hlsl-headers/enable_if @@ -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 struct enable_if {}; + +template struct enable_if { + using type = T; +}; + +} // namespace hlsl + +#endif // __HLSL_VERSION >= 2021 + +#endif // __HLSL_ENABLE_IF diff --git a/vendor/hlsl-headers/type_traits b/vendor/hlsl-headers/type_traits new file mode 100644 index 0000000..f2256a2 --- /dev/null +++ b/vendor/hlsl-headers/type_traits @@ -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 struct is_same { + static const bool value = false; +}; + +template struct is_same { + static const bool value = true; +}; + +template struct is_arithmetic { + static const bool value = false; +}; + +#define __ARITHMETIC_TYPE(type) \ + template <> struct is_arithmetic { \ + 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 struct is_integral { + static const bool value = false; +}; + +#define __INTEGRAL_TYPE(type) \ + template <> struct is_integral { \ + 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 struct is_packed_integral { + static const bool value = false; +}; + +#if __hlsl_dx_compiler +template <> struct is_packed_integral { + static const bool value = true; +}; + +template <> struct is_packed_integral { + static const bool value = true; +}; +#endif + +template struct is_integral_or_packed_integral { + static const bool value = + is_integral::value || is_packed_integral::value; +}; + +template struct is_signed { + static const bool value = true; +}; + +#define __UNSIGNED_TYPE(type) \ + template <> struct is_signed { \ + 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 struct is_vector { + static const bool value = false; +}; + +template struct is_vector > { + static const bool value = true; +}; + +template struct strip_vector_type { + using type = T; +}; + +template struct strip_vector_type > { + using type = T; +}; + +template struct is_arithmetic_vector { + static const bool value = + is_arithmetic::value || + (is_vector::value && + is_arithmetic::type>::value); +}; + +} // namespace hlsl + +#endif // __HLSL_VERSION >= 2021 +#endif // __HLSL_TYPE_TRAITS diff --git a/vendor/hlsl-headers/vector_utils b/vendor/hlsl-headers/vector_utils new file mode 100644 index 0000000..54f9116 --- /dev/null +++ b/vendor/hlsl-headers/vector_utils @@ -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 + +namespace hlsl { + +template +typename hlsl::enable_if >::type +slice(vector In) { + vector Result = (vector)0; + + [unroll] + for (int I = 0; I < OSz; ++I) + Result[I] = In[I + Off]; + + return Result; +} + +template +vector slice(vector In) { + return slice<0, OSz, T, ISz>(In); +} + +} // namespace hlsl + +#endif // __HLSL_VERSION >= 2021 +#endif // __HLSL_VECTOR_UTILS diff --git a/vendor/hlsl-headers/vk/khr/cooperative_matrix.h b/vendor/hlsl-headers/vk/khr/cooperative_matrix.h new file mode 100644 index 0000000..9d2ced0 --- /dev/null +++ b/vendor/hlsl-headers/vk/khr/cooperative_matrix.h @@ -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 + +namespace vk { +namespace khr { + +// The base cooperative matrix class. The template arguments correspond to the +// operands in the OpTypeCooperativeMatrixKHR instruction. +template +class CooperativeMatrix { + template + CooperativeMatrix 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 + void Store(WorkgroupSpirvPointer data, uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access + // operands. + template + void Store(WorkgroupSpirvPointer data, uint32_t stride) { + Store(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 + void Store(RWStructuredBuffer data, uint32_t index, uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access + // operands. + template + void Store(RWStructuredBuffer data, uint32_t index, uint32_t stride) { + Store(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 + void CoherentStore(globallycoherent RWStructuredBuffer data, + uint32_t index, uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access operands + // template argument. + template + void CoherentStore(globallycoherent RWStructuredBuffer data, + uint32_t index, uint32_t stride) { + CoherentStore(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 + static CooperativeMatrix Load(WorkgroupSpirvPointer data, + uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access + // operands. + template + static CooperativeMatrix Load(WorkgroupSpirvPointer data, + uint32_t stride) { + return Load(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 + static CooperativeMatrix Load(RWStructuredBuffer data, uint32_t index, + uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access + // operands. + template + static CooperativeMatrix Load(RWStructuredBuffer data, uint32_t index, + uint32_t stride) { + return Load(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 + static CooperativeMatrix + CoherentLoad(globallycoherent RWStructuredBuffer data, uint32_t index, + uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access operands + // template argument. + template + static CooperativeMatrix + CoherentLoad(globallycoherent RWStructuredBuffer data, uint32_t index, + uint32_t stride) { + return CoherentLoad(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 + static CooperativeMatrix Load(StructuredBuffer data, uint32_t index, + uint32_t stride); + + // Same as above, but uses MemoryAccessMaskNone for the memory access + // operands. + template + static CooperativeMatrix Load(StructuredBuffer data, uint32_t index, + uint32_t stride) { + return Load(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, vk::integral_constant, + vk::integral_constant, vk::integral_constant >; + + [[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 +using CooperativeMatrixA = + CooperativeMatrix; + +// Cooperative matrix that can be used in the "b" position of a multiply add +// instruction (r = (a * b) + c). +template +using CooperativeMatrixB = + CooperativeMatrix; + +// Cooperative matrix that can be used in the "r" and "c" position of a multiply +// add instruction (r = (a * b) + c). +template +using CooperativeMatrixAccumulator = + CooperativeMatrix; + +// 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 +CooperativeMatrixAccumulator +cooperativeMatrixMultiplyAdd( + CooperativeMatrixA a, + CooperativeMatrixB b, + CooperativeMatrixAccumulator 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 +CooperativeMatrixAccumulator +cooperativeMatrixSaturatingMultiplyAdd( + CooperativeMatrixA a, + CooperativeMatrixB b, + CooperativeMatrixAccumulator c); + +} // namespace khr +} // namespace vk + +#include +#endif // _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_ diff --git a/vendor/hlsl-headers/vk/khr/cooperative_matrix.impl b/vendor/hlsl-headers/vk/khr/cooperative_matrix.impl new file mode 100644 index 0000000..7446d33 --- /dev/null +++ b/vendor/hlsl-headers/vk/khr/cooperative_matrix.impl @@ -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 + +template +[[vk::ext_instruction(/* OpMatrixTimesScalar */ 143)]] ResultType +__builtin_spv_MatrixTimesScalar(ResultType a, ComponentType b); + +template +[[vk::ext_instruction(/* OpCompositeExtract */ 81)]] ComponentType +__builtin_spv_ExtractFromCooperativeMatrix( + typename vk::khr::CooperativeMatrix::SpirvMatrixType matrix, + uint32_t index); + +template +[[vk::ext_instruction(/* OpCompositeConstruct */ 80)]] CoopMatrixType +__builtin_spv_ConstructCooperativeMatrix(ComponentType value); + +template +[[vk::ext_instruction(/* OpAccessChain */ 65)]] ResultPointerType +__builtin_spv_AccessChain([[vk::ext_reference]] BaseType base, uint32_t index); + +template +[[vk::ext_instruction(/* OpLoad */ 61)]] ObjectType +__builtin_spv_LoadPointer(PointerType base); + +template +[[vk::ext_instruction(/* OpLoad */ 62)]] void +__builtin_spv_StorePointer(PointerType base, ObjectType object); + +template +[[vk::ext_instruction(/* OpCompositeInsert */ 82)]] +typename vk::khr::CooperativeMatrix::SpirvMatrixType +__builtin_spv_InsertIntoCooperativeMatrix( + ComponentType value, + typename vk::khr::CooperativeMatrix::SpirvMatrixType matrix, + uint32_t index); + +// Define the load and store instructions +template +[[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 +[[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 +[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType +__builtin_spv_CooperativeMatrixWorkgroupLoadKHR( + vk::WorkgroupSpirvPointer pointer, + vk::CooperativeMatrixLayout memory_layout, uint stride, + [[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope); + +template +[[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 +[[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 +[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void +__builtin_spv_CooperativeMatrixWorkgroupStoreKHR( + vk::WorkgroupSpirvPointer 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 uint __builtin_spv_CooperativeMatrixLengthKHR(); + +// Arithmetic Instructions +template +[[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 +template +CooperativeMatrix +CooperativeMatrix::cast() { + using ResultType = + CooperativeMatrix; + ResultType result; + result._matrix = util::ConversionSelector:: + template Convert(_matrix); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::negate() { + CooperativeMatrix result; + result._matrix = util::ArithmeticSelector::Negate(_matrix); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::operator+( + CooperativeMatrix other) { + CooperativeMatrix result; + result._matrix = + util::ArithmeticSelector::Add(_matrix, other._matrix); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::operator-( + CooperativeMatrix other) { + CooperativeMatrix result; + result._matrix = + util::ArithmeticSelector::Sub(_matrix, other._matrix); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::operator*( + CooperativeMatrix other) { + CooperativeMatrix result; + result._matrix = + util::ArithmeticSelector::Mul(_matrix, other._matrix); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::operator/( + CooperativeMatrix other) { + CooperativeMatrix result; + result._matrix = + util::ArithmeticSelector::Div(_matrix, other._matrix); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::operator*( + ComponentType scalar) { + CooperativeMatrix result; + result._matrix = __builtin_spv_MatrixTimesScalar(_matrix, scalar); + return result; +} + +template +template +void CooperativeMatrix::Store( + WorkgroupSpirvPointer data, uint32_t stride) { + __builtin_spv_CooperativeMatrixWorkgroupStoreKHR( + data, _matrix, layout, stride, + memoryAccessOperands | MemoryAccessNonPrivatePointerMask | + MemoryAccessMakePointerAvailableMask, + ScopeWorkgroup); +} + +template +template +void CooperativeMatrix::Store( + RWStructuredBuffer data, uint32_t index, uint32_t stride) { + __builtin_spv_CooperativeMatrixStoreKHR(data[index], _matrix, layout, stride, + memoryAccessOperands); +} + +template +template +void CooperativeMatrix::CoherentStore( + globallycoherent RWStructuredBuffer data, uint32_t index, + uint32_t stride) { + __builtin_spv_CooperativeMatrixStoreKHR( + data[index], _matrix, layout, stride, + memoryAccessOperands | MemoryAccessNonPrivatePointerMask | + MemoryAccessMakePointerAvailableMask, + ScopeQueueFamily); +} + +template +template +CooperativeMatrix +CooperativeMatrix::Load( + vk::WorkgroupSpirvPointer buffer, uint32_t stride) { + CooperativeMatrix result; + result._matrix = + __builtin_spv_CooperativeMatrixWorkgroupLoadKHR( + buffer, layout, stride, + memoryAccessOperands | MemoryAccessNonPrivatePointerMask | + MemoryAccessMakePointerVisibleMask, + ScopeWorkgroup); + return result; +} + +template +template +CooperativeMatrix +CooperativeMatrix::Load( + RWStructuredBuffer buffer, uint32_t index, uint32_t stride) { + CooperativeMatrix result; + result._matrix = __builtin_spv_CooperativeMatrixLoadKHR( + buffer[index], layout, stride, memoryAccessOperands); + return result; +} + +template +template +CooperativeMatrix +CooperativeMatrix::CoherentLoad( + RWStructuredBuffer buffer, uint32_t index, uint32_t stride) { + CooperativeMatrix result; + result._matrix = __builtin_spv_CooperativeMatrixLoadKHR( + buffer[index], layout, stride, + memoryAccessOperands | MemoryAccessNonPrivatePointerMask | + MemoryAccessMakePointerVisibleMask, + ScopeQueueFamily); + return result; +} + +template +template +CooperativeMatrix +CooperativeMatrix::Load( + StructuredBuffer buffer, uint32_t index, uint32_t stride) { + CooperativeMatrix result; + result._matrix = __builtin_spv_CooperativeMatrixLoadKHR( + buffer[index], layout, stride, MemoryAccessMaskNone); + return result; +} + +template +CooperativeMatrix +CooperativeMatrix::Splat( + ComponentType v) { + CooperativeMatrix result; + result._matrix = __builtin_spv_ConstructCooperativeMatrix(v); + return result; +} + +template +uint CooperativeMatrix::GetLength() { + return __builtin_spv_CooperativeMatrixLengthKHR(); +} + +template +ComponentType CooperativeMatrix::Get( + uint32_t index) { + // clang-format off + using ComponentPtr = vk::SpirvOpaqueType< + /* OpTypePointer */ 32, + /* function storage class */ vk::Literal >, + ComponentType>; + // clang-format on + ComponentPtr ptr = __builtin_spv_AccessChain(_matrix, index); + return __builtin_spv_LoadPointer(ptr); +} + +template +void CooperativeMatrix::Set( + ComponentType value, uint32_t index) { + // clang-format off + using ComponentPtr = vk::SpirvOpaqueType< + /* OpTypePointer */ 32, + /* function storage class */ vk::Literal >, + ComponentType>; + // clang-format on + ComponentPtr ptr = __builtin_spv_AccessChain(_matrix, index); + return __builtin_spv_StorePointer(ptr, value); +} + +template +CooperativeMatrixAccumulator +cooperativeMatrixMultiplyAdd( + CooperativeMatrixA a, + CooperativeMatrixB b, + CooperativeMatrixAccumulator 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 result; + result._matrix = __builtin_spv_CooperativeMatrixMulAddKHR< + typename CooperativeMatrixAccumulator::SpirvMatrixType>( + a._matrix, b._matrix, c._matrix, operands); + return result; +} + +template +CooperativeMatrixAccumulator +cooperativeMatrixSaturatingMultiplyAdd( + CooperativeMatrixA a, + CooperativeMatrixB b, + CooperativeMatrixAccumulator 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 result; + result._matrix = __builtin_spv_CooperativeMatrixMulAddKHR< + typename CooperativeMatrixAccumulator::SpirvMatrixType>( + a._matrix, b._matrix, c._matrix, operands); + return result; +} + +} // namespace khr +} // namespace vk diff --git a/vendor/hlsl-headers/vk/opcode_selector.h b/vendor/hlsl-headers/vk/opcode_selector.h new file mode 100644 index 0000000..bc8672c --- /dev/null +++ b/vendor/hlsl-headers/vk/opcode_selector.h @@ -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 \ + [[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 \ + [[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 \ + [[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 ArithmeticSelector; + +#define ARITHMETIC_SELECTOR(BaseType, OpNegate, OpAdd, OpSub, OpMul, OpDiv, \ + SIGNED_INTEGER_TYPE) \ + template <> class ArithmeticSelector { \ + template static T Negate(T a) { return OpNegate(a); } \ + template static T Add(T a, T b) { return OpAdd(a, b); } \ + template static T Sub(T a, T b) { return OpSub(a, b); } \ + template static T Mul(T a, T b) { return OpMul(a, b); } \ + template 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 ConversionSelector; + +#define CONVERSION_SELECTOR(SourceType, TargetType, OpConvert) \ + template <> class ConversionSelector { \ + template static T Convert(S a) { \ + return OpConvert(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_ diff --git a/vendor/hlsl-headers/vk/spirv.h b/vendor/hlsl-headers/vk/spirv.h new file mode 100644 index 0000000..69bb53b --- /dev/null +++ b/vendor/hlsl-headers/vk/spirv.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 +using WorkgroupSpirvPointer = const vk::SpirvOpaqueType< + /* OpTypePointer */ 32, + vk::Literal >, + 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 +[[vk::ext_instruction(/* OpCopyObject */ 83)]] WorkgroupSpirvPointer +GetGroupSharedAddress([[vk::ext_reference]] T v); + +} // namespace vk + +#endif // _HLSL_VK_SPIRV_H_ diff --git a/vendor/hlsl_headers.zig b/vendor/hlsl_headers.zig new file mode 100644 index 0000000..2541692 --- /dev/null +++ b/vendor/hlsl_headers.zig @@ -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 `). +//! 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");