Compare commits

...

16 Commits

Author SHA1 Message Date
Peter Li 05076bb91a zdxc: make the tree a clean public source drop
Move the oracle tests, the benchmark, the agent skill and the libzdxc
investigation notes to the zdxc-internal development repo, which builds
this tree as a path dependency. The public build keeps install, run and
test. build.zig.zon now lists tools/ (the build needs its generators)
and docs/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:39:53 -08:00
Peter Li 33d390816f removing the zdxc binary 2026-11-01 15:26:33 -08:00
Peter Li 44b8e0bd26 zdxc: --job=<job.json> batch mode
Compile every shader a JSON job file lists in one process, on all cores.
Each job is a dxc command line; shared args come first. Outputs are
byte-identical to separate runs and each job's diagnostics print together
in job order. 1481 corpus shaders: 0.064 s, against 1.09 s for one zdxc
per shader on 10 cores and 1.68 s for dxc.

Also: an unreadable input exits 1 as in dxc (was 5), and stdout/stderr
write in streaming mode so `2>> log` appends instead of overwriting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:46:47 -08:00
Peter Li c51e594db8 zdxc: number DXIL instructions once per function
The bitcode writer found an instruction's value ID by counting the
non-void instructions before it, for every operand: quadratic in the
function's size. Large functions (unrolled loops, -O0 hull shaders) took
up to 190 ms; the IDs are now computed once per function. Output is
byte-identical; SubD11_SubDToBezierHS4444 goes from 192 ms to 10 ms
(dxc: 64 ms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:27:47 -08:00
Peter Li b5a47b7c8e zdxc: partial stores to shared memory; one SPIR-V type per strided array
Writing some components of a vector or matrix in an RW structured
buffer or groupshared memory read the whole value and wrote it all
back, racing with other threads writing the other components. Those
stores now write only the named components, as dxc does. Matrix rows
and elements of buffer matrices (W[i][1][2] = x, B[i].m[r] = v, at
constant or dynamic rows) are stored element by element instead of
being rejected.

SPIR-V arrays with the same element, length and stride are now one
type, so buffers of the same element share their runtime array.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:12:38 -08:00
Peter Li bf073b8907 zdxc: -Zpr / -Zpc and #pragma pack_matrix
-Zpr and #pragma pack_matrix were accepted but ignored, so row-major
matrices silently got the column-major layout. Now, as in dxc:

- #pragma pack_matrix sets the orientation of matrices declared after
  it and may come between any two tokens; typedefs keep theirs.
- -Zpr is the default for matrices with neither; -Zpc is accepted and
  the two together are an error.
- Entry parameters take an orientation written on them or the
  pragma's, not a typedef's (dxc's signatures lose that sugar).
- Structured buffer matrix elements follow -Zpr only in DXIL; in
  SPIR-V they take the template argument's orientation too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:53:09 -08:00
Peter Li 1cbdff697b zdxc: nested types of template instances; typedef members as dxc
Types declared in structs, template ones included, are accepted as the
last part of a qualified type name (TO<float>::In), which the parser
lost with the template's scope. typedef members are reported in struct
templates too (at the definition, as dxc), while alias declarations
(using F = float;) are allowed in any struct, as in dxc. Each HLSL
struct gets a module type of its own: struct types are named, and
same-named structs (two instances' nested In, or a ConstantBuffer<S>
class type and S) shared one layout, which crashed dxv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:58:07 -07:00
Peter Li 964ffde8e7 zdxc: mangle template instances, classes and scoped names as dxc
Structs and enums remember their enclosing namespaces and structs, and
struct template instances their name and arguments, so mangled names
spell them as dxc does: U/V for struct/class, ?$Name@<args>@ for
instances (type arguments, $0<n> and $0?<n> integral ones, with names
of their own), each enclosing scope after the name, with back-references.
Exported functions whose signature holds a resource or matrix handle get
dxc's error instead of an invalid module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:39:38 -07:00
Peter Li 8ec0dd4b31 zdxc: keep [noinline] functions in DXIL libraries
[noinline] plain functions in libraries become internal functions of
their own (noinline nounwind) instead of being inlined, passed values as
exported functions are: scalars and vectors by value, structs and out /
inout values by pointer (through temporaries at the call). RDAT lists
them, and each function's shader flags, minimum shader model and stage
mask merge in its callees' (dxc's ComputeShaderCompatInfo), as do the
LinAlg extended properties. Functions with resources, matrix handles,
arrays, matrices or groupshared parameters are still inlined (the
validator rejects resources, LinAlg matrices included, in signatures).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:28:56 -07:00
Peter Li 506d9c0b9d zdxc: SM 6.10 LinAlg in libraries
Write each library function's RDAT ExtendedProperties the way dxc's
AddLinAlgFunctionProperties does: matrix constructions with their
operation shapes, thread mat-vec multiplies, wave and thread-group
matrix multiplies, outer products and accumulating stores, merged from
callees, in the extended property record tables (part types 13-20)
with record deduplication. Removes the library LinAlg gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:07:09 -07:00
Peter Li edddf5e5f8 out / inout resource parameters
- Resource locals may be declared without an initializer (an alias of
  what is stored into them; reading one first is reported).
- DXIL: inlined calls write out resources into the caller's alias; a
  resource written back to the global it is is a no-op.
- SPIR-V: out / inout resource parameters leave the parameter list (an
  inout one's value comes in by value); the callee works on a local and
  what it holds at the end is traced to a parameter or global, which the
  caller stores into the argument after the call.
- An acceleration structure that is only declared gets the ray query
  capability its type needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:55:37 -07:00
Peter Li d6b2c9e712 Arrays of resources as function parameters
- DXIL: a local array of resources (a parameter's copy) aliases the
  resource array stored into it; elements index that array.
- SPIR-V: a whole resource array read to pass on stays its variable, so
  the callee is specialized on it; arrays read whole are not flattened
  (their bindings are still numbered per element), which also lets
  global structs holding resource arrays be passed to functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:10:48 -07:00
Peter Li 076f0f7e2b SPIR-V: resources in structs (locals, values, parameters, returns)
- An IR pass for SPIR-V splits structs holding resources: resource
  members of locals become resource locals, struct values carry their
  resources alongside (construct / extract / insert / load / store),
  parameters holding resources (by value or reference, including
  `this`) gain a resource parameter per member, and functions returning
  resources return the parameter or global they trace to.
- Struct values in SPIR-V leave resource members out.
- Arrays of global structs of resources: an element per resource
  variable named by flattened index (globals[5].t), and the whole struct
  reserves one consecutive binding range, as dxc numbers them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:55:56 -07:00
Peter Li 99e3591481 Resources in structs (DXIL), global structs of resources (both)
- DXIL: structs and arrays holding resources as values (data plus the
  resources, statically known) and as locals (data in memory, a
  resource slot per member): copies, nested structs, arrays, init lists,
  function arguments and returns, and functions returning resources.
- Global structs with resources: each resource is its own global named
  by its path (g.tex), bound like other unbound resources; data members
  stay in $Globals with resources taking no space in the layout.
- SPIR-V: struct types drop resource members (member indices remapped);
  a global struct of textures and samplers gets a binding per resource
  and turns on per-element array bindings, as dxc does; dxc's errors
  for structs with buffers or mixed members.
- LinAlg vectors of one element stay native vectors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:12:07 -07:00
Peter Li dc90b606a3 SM 6.9 long vectors (DXIL)
- vector<T, N> with N up to 1024 from shader model 6.9 (vector lengths
  and shapes widen to u16); intrinsic layouts accept long vectors.
- DXIL keeps the scalarized form: buffers, groupshared memory, structs,
  intrinsics and LinAlg vector operands work for any length.
- dxc's diagnostics: no swizzles on long vectors, and none in cbuffers,
  tbuffers, $Globals, ConstantBuffer/TextureBuffer, patches, streams or
  entry point parameters / return types.
- SPIR-V reports long vectors as unsupported (Vulkan has none; dxc's
  output is invalid).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:49:41 -07:00
Peter Li 92a5690d9a SM 6.10 linear algebra (DXIL)
- __builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
  scope)]] as a type; matrices live in locals, statics and structs as
  matrix-typed allocas (as dxc -Od); !dx.targetTypes.
- All 21 dx::__builtin_LinAlg_* builtins lowered to DXIL ops 322-342
  with dxc's overload names (matrix, native vector and scalar operands;
  results stored to the out / ref argument).
- The LinearAlgebra shader flag; PSV0 LinAlgRuntimeInfo (constructions,
  multiplies, outer products, accumulate stores), byte-identical to dxc
  where matrix loads are traceable.
- groupshared parameters alias the caller's variable (they were copied);
  constants forwarded through locals within a block (immediates through
  parameters); enum static consts folded.
- Linear algebra in libraries (RDAT properties) and long vectors are
  reported as not supported yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:25:57 -07:00
139 changed files with 2720 additions and 3015 deletions

View File

@ -1,26 +0,0 @@
---
name: zig
description: Work on Zig 0.17 code and build files using the documentation and standard-library source shipped with the active compiler. Use for writing, reviewing, debugging, or migrating Zig in this repository.
---
# Zig 0.17
Use the installed Zig toolchain as the source of truth. Do not rely on remembered
APIs or hand-maintained summaries when the compiler distribution can answer the
question directly.
- Run `zig env` to locate `zig_exe`, `lib_dir`, and `std_dir`; do not assume a
particular installation path.
- Consult `<directory containing zig_exe>/doc/langref.html` for language syntax,
semantics, and builtins.
- Search `std_dir` for exact APIs, implementations, and tests. Use them as
examples of both correct usage and Zig coding style; follow standard-library
conventions.
- Use compiler and test failures to verify any inferred API usage.
For `if` conditions, put continuation `and`/`or` operators at the start of
the next line. Run `zig fmt` on changed Zig files.
If the installed documentation is unavailable, use the versioned official
reference at <https://ziglang.org/documentation/0.17.0/>; download a copy once and
avoid unnecessary traffic.

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
zig-out/
.zig-cache/
.zig-pkg/
test-out/

View File

@ -1,121 +0,0 @@
//! Preprocessor benchmark: lexes / preprocesses a set of files in-process
//! and reports the best-of-N wall time and throughput.
//!
//! Usage: pp_bench [-mode lex|load|pp|print|parse] [-iters N] <file-list.txt>
//! The file list has one path per line. File contents are read once and
//! served from memory, so disk I/O is excluded from the timings.
const std = @import("std");
const Io = std.Io;
const zdxc = @import("zdxc");
const front = zdxc.front;
const Mode = enum { lex, load, pp, print, parse };
/// Serves each path from memory after the first read.
const CachedFs = struct {
io: Io,
gpa: std.mem.Allocator,
files: std.StringHashMapUnmanaged(?[]const u8) = .empty,
fn fileSystem(c: *CachedFs) front.source.FileSystem {
return .{ .ctx = c, .readFn = readImpl };
}
fn readImpl(ctx: *anyopaque, _: std.mem.Allocator, path: []const u8) ?[]const u8 {
const c: *CachedFs = @ptrCast(@alignCast(ctx));
const gop = c.files.getOrPut(c.gpa, path) catch return null;
if (!gop.found_existing) {
gop.key_ptr.* = c.gpa.dupe(u8, path) catch return null;
gop.value_ptr.* = Io.Dir.cwd().readFileAlloc(c.io, path, c.gpa, .limited(256 << 20)) catch null;
}
return gop.value_ptr.*;
}
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const io = init.io;
const arena = init.arena.allocator();
const args = try init.minimal.args.toSlice(arena);
var mode: Mode = .pp;
var iters: usize = 5;
var list_path: ?[]const u8 = null;
var i: usize = 1;
while (i < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "-mode")) {
i += 1;
mode = std.meta.stringToEnum(Mode, args[i]) orelse return error.BadMode;
} else if (std.mem.eql(u8, args[i], "-iters")) {
i += 1;
iters = try std.fmt.parseInt(usize, args[i], 10);
} else list_path = args[i];
}
const list = try Io.Dir.cwd().readFileAlloc(io, list_path orelse return error.MissingFileList, arena, .limited(64 << 20));
var paths: std.ArrayList([]const u8) = .empty;
var it = std.mem.tokenizeScalar(u8, list, '\n');
while (it.next()) |p| try paths.append(arena, p);
var cfs: CachedFs = .{ .io = io, .gpa = gpa };
var total_bytes: usize = 0;
for (paths.items) |p| {
if (CachedFs.readImpl(&cfs, gpa, p)) |text| total_bytes += text.len;
}
var best: u64 = std.math.maxInt(u64);
var checksum: u64 = 0;
for (0..iters) |_| {
const start = Io.Timestamp.now(io, .awake);
checksum = 0;
for (paths.items) |p| checksum +%= try runOne(gpa, &cfs, p, mode);
const ns: u64 = @intCast(start.durationTo(Io.Timestamp.now(io, .awake)).nanoseconds);
best = @min(best, ns);
}
var buf: [256]u8 = undefined;
var w = Io.File.Writer.init(.stdout(), io, &buf);
const mb = @as(f64, @floatFromInt(total_bytes)) / (1024.0 * 1024.0);
const secs = @as(f64, @floatFromInt(best)) / 1e9;
try w.interface.print("{s}: {d} files, {d:.1} MB, best {d:.2} ms, {d:.0} MB/s (checksum {d})\n", .{
@tagName(mode), paths.items.len, mb, secs * 1000.0, mb / secs, checksum,
});
try w.interface.flush();
}
fn runOne(gpa: std.mem.Allocator, cfs: *CachedFs, path: []const u8, mode: Mode) !u64 {
var arena_state: std.heap.ArenaAllocator = .init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
if (mode == .lex) {
const text = CachedFs.readImpl(cfs, gpa, path) orelse return 0;
var lx = front.lexer.Lexer.init(text, 0);
var n: u64 = 0;
while (lx.next().kind != .eof) n += 1;
return n;
}
var sm = front.source.SourceManager.init(arena, cfs.fileSystem());
if (mode == .load) {
const id = try sm.load(path) orelse return 0;
return sm.file(id).line_starts.len;
}
var diags = zdxc.Diagnostics.init(arena);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{});
if (!try pp.enterMainFile(path)) return 0;
if (mode == .parse) {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
const tu = try parser.parseTranslationUnit();
return tu.decls.len + diags.error_count;
}
if (mode == .print) {
var out: Io.Writer.Allocating = .init(arena);
try front.pp_print.print(&pp, &out.writer);
return out.written().len;
}
var n: u64 = 0;
while ((try pp.next()).kind != .eof) n += 1;
return n;
}

View File

@ -65,82 +65,4 @@ pub fn build(b: *std.Build) void {
test_step.dependOn(&b.addRunArtifact(mod_tests).step);
const exe_tests = b.addTest(.{ .root_module = exe.root_module });
test_step.dependOn(&b.addRunArtifact(exe_tests).step);
// Oracle checks: compare zdxc output against the DXC build in ../build.
const oracle_step = b.step("oracle", "Validate zdxc output with dxv and spirv-val");
const oracle = b.addSystemCommand(&.{ "sh", "test/oracle/m0.sh" });
oracle.addArtifactArg(exe);
oracle.setCwd(b.path("."));
oracle.has_side_effects = true;
oracle_step.dependOn(&oracle.step);
const dxil_checks = b.addSystemCommand(&.{ "sh", "test/dxil/check.sh" });
dxil_checks.addArtifactArg(exe);
dxil_checks.setCwd(b.path("."));
dxil_checks.has_side_effects = true;
oracle_step.dependOn(&dxil_checks.step);
const spirv_checks = b.addSystemCommand(&.{ "sh", "test/spirv/check.sh" });
spirv_checks.addArtifactArg(exe);
spirv_checks.setCwd(b.path("."));
spirv_checks.has_side_effects = true;
oracle_step.dependOn(&spirv_checks.step);
const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc");
const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" });
oracle_parse.addArtifactArg(exe);
oracle_parse.setCwd(b.path("."));
oracle_parse.has_side_effects = true;
oracle_parse_step.dependOn(&oracle_parse.step);
const oracle_sema_step = b.step("oracle-sema", "Check that Sema accepts every dxc-valid corpus file");
const oracle_sema = b.addSystemCommand(&.{ "sh", "test/oracle/sema.sh" });
oracle_sema.addArtifactArg(exe);
oracle_sema.setCwd(b.path("."));
oracle_sema.has_side_effects = true;
oracle_sema.step.dependOn(&oracle_parse.step); // builds the corpus list
oracle_sema_step.dependOn(&oracle_sema.step);
const oracle_codegen_step = b.step("oracle-codegen", "Compile the dxc-valid corpus to SPIR-V and DXIL and validate the output");
for ([_][]const u8{ "spirv", "dxil" }) |backend| {
const run = b.addSystemCommand(&.{ "sh", "test/oracle/codegen.sh" });
run.addArtifactArg(exe);
run.addArg(backend);
run.setCwd(b.path("."));
run.has_side_effects = true;
run.step.dependOn(&oracle_parse.step); // builds the corpus list
oracle_codegen_step.dependOn(&run.step);
}
const oracle_verify_step = b.step("oracle-verify", "Compare Sema errors with dxc's SemaHLSL -verify expectations");
const oracle_verify = b.addSystemCommand(&.{ "sh", "test/oracle/verify.sh" });
oracle_verify.addArtifactArg(exe);
oracle_verify.setCwd(b.path("."));
oracle_verify.has_side_effects = true;
oracle_verify_step.dependOn(&oracle_verify.step);
const oracle_cli_step = b.step("oracle-cli", "Parse every dxc command line in the DXC test corpus");
const oracle_cli = b.addSystemCommand(&.{ "sh", "test/oracle/cli.sh" });
oracle_cli.addArtifactArg(exe);
oracle_cli.setCwd(b.path("."));
oracle_cli.has_side_effects = true;
oracle_cli_step.dependOn(&oracle_cli.step);
// Benchmarks always build optimized so numbers are comparable.
const bench = b.addExecutable(.{
.name = "pp_bench",
.root_module = b.createModule(.{
.root_source_file = b.path("bench/pp_bench.zig"),
.target = target,
.optimize = .ReleaseFast,
.imports = &.{.{ .name = "zdxc", .module = mod }},
}),
});
const bench_step = b.step("bench", "Build the preprocessor benchmark (zig-out/bin/pp_bench)");
bench_step.dependOn(&b.addInstallArtifact(bench, .{}).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);
}

View File

@ -8,7 +8,9 @@
.paths = .{
"build.zig",
"build.zig.zon",
"docs",
"src",
"tools",
"vendor",
},
}

64
docs/batch.md Normal file
View File

@ -0,0 +1,64 @@
# Batch mode: `--job=<job.json>`
`zdxc --job=build/shaders.json` compiles every shader a job file lists in
one process, on all cores. Starting a process costs more than compiling most
shaders (about 2 ms against a few hundred microseconds), so a build with many
shaders is much faster this way than with one compiler run per shader.
On the 1,481 corpus shaders zdxc compiles (10-core M-series Mac, release
build):
| How | Wall time |
| ------------------------------------------- | --------: |
| `zdxc --job`, all cores | 0.064 s |
| `zdxc --job`, `"threads": 1` | 0.24 s |
| one `zdxc` per shader, 10 in parallel | 1.09 s |
| one `dxc` per shader, 10 in parallel | 1.68 s |
## The job file
```json
{
"threads": 8,
"args": ["-HV", "2021", "-I", "shaders/include"],
"jobs": [
{ "args": ["-T", "cs_6_0", "shaders/blur.hlsl", "-Fo", "out/blur.dxo"] },
{ "args": ["-T", "ps_6_0", "-E", "PS", "shaders/mesh.hlsl", "-Fo", "out/mesh_ps.dxo"] },
{ "args": ["-T", "vs_6_0", "-E", "VS", "-spirv", "shaders/mesh.hlsl", "-Fo", "out/mesh_vs.spv"] }
]
}
```
- `jobs` (required): each job's `args` is a dxc command line without the
program name — any option zdxc accepts on its own command line.
- `args` (optional): options shared by every job.
- `threads` (optional): how many shaders compile at once. Defaults to the
number of CPUs.
A job's full command line is the file's `args`, then any options given next
to `--job` on the real command line, then the job's own `args`. So
`zdxc --job=shaders.json -O3 -Qstrip_debug` adds `-O3 -Qstrip_debug` to every
job, and a job can override a shared option where a later option wins on the
command line. Unknown fields are errors, reported with their line and column.
Paths in the file are relative to the current directory, as on the command
line, not to the job file. `--job` cannot appear inside a job file.
## Output and exit code
Every job writes its own `-Fo` / `-Fh` / ... outputs. What a job prints —
diagnostics, and text output such as `-P` without a file — comes out
exactly as one zdxc run of that command line would print it, kept together
and in job order, whatever order the jobs finish in. The outputs are
byte-identical to separate runs.
When jobs fail, the other jobs still run, and a last line says how many
failed:
```
zdxc: 2 of 112 jobs failed
```
The exit code is 0 when every job succeeds; otherwise 1 if any job failed
on its command line or on I/O (a missing input, an unwritable output), else
5 (compile errors) — the codes one zdxc run uses.

View File

@ -1,310 +0,0 @@
# libzdxc: matching DXC's library API
Status: investigation notes, not yet implemented. Source references are to the
DXC tree at `f9fc72ad3`.
## How DXC works as a library
`dxcompiler` (`libdxcompiler.so` / `.dylib`, `dxcompiler.dll`) exports
exactly two C symbols (`tools/clang/tools/dxcompiler/dxcompiler.def`):
```c
HRESULT DxcCreateInstance (REFCLSID rclsid, REFIID riid, void **ppv);
HRESULT DxcCreateInstance2(IMalloc *pMalloc, REFCLSID rclsid, REFIID riid, void **ppv);
```
Everything else is a COM-style interface reached from those two calls.
`DxcCreateInstance` is a CLSID switch (`dxcapi.cpp`,
`ThreadMallocDxcCreateInstance`) that returns `REGDB_E_CLASSNOTREG`
(0x80040154) for unknown classes. `DxcCreateInstance2` installs a
caller-supplied `IMalloc` as the allocator for that object's lifetime.
The `dxc` executable is itself a thin client. It `dlopen`s dxcompiler through
`include/dxc/Support/dxcapi.use.h` and drives it with `CLSID_DxcCompiler`,
`CLSID_DxcLibrary`, and so on (`tools/clang/tools/dxclib/dxc.cpp`). The command
line and the API share one option parser: the arguments passed to
`IDxcCompiler3::Compile` are dxc command-line flags as wide strings.
### Classes and interfaces
| CLSID | Interfaces it answers `QueryInterface` for | Typical use |
|---|---|---|
| `CLSID_DxcCompiler` | `IDxcCompiler3`, `IDxcVersionInfo`, `IDxcVersionInfo2/3`, `IDxcLangExtensions*`, `IDxcContainerEvent`; legacy `IDxcCompiler`, `IDxcCompiler2` via an adapter sub-object (`dxcompilerobj.cpp:499`) | compile, preprocess, disassemble |
| `CLSID_DxcUtils` == `CLSID_DxcLibrary` (same GUID) | `IDxcUtils`, legacy `IDxcLibrary` | blobs, default include handler, `BuildArguments`, `CreateReflection`, `GetDxilContainerPart` |
| `CLSID_DxcCompilerArgs` | `IDxcCompilerArgs` | building argument lists |
| `CLSID_DxcValidator` | `IDxcValidator`, `IDxcValidator2`, `IDxcVersionInfo` | validation and signing (also exported by the separate `dxil` library) |
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection` | listing container parts, `ID3D12ShaderReflection` |
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder` | adding and removing parts |
| `CLSID_DxcAssembler`, `CLSID_DxcOptimizer`, `CLSID_DxcLinker`, `CLSID_DxcPdbUtils`, `CLSID_DxcRewriter`, `CLSID_DxcIntelliSense` | — | LLVM-IR tooling, PDBs, IntelliSense |
### Compile contract (`IDxcCompiler3::Compile`, `dxcompilerobj.cpp:517`)
- Inputs: a `DxcBuffer` (pointer, size, code page; 0 means detect a BOM,
otherwise treat as UTF-8), `LPCWSTR` argv, an optional `IDxcIncludeHandler`,
and an `riid` that must be `IDxcResult` or `IDxcOperationResult`. Any other
`riid`, a null source, or a null argv with `argCount > 0` returns
`E_INVALIDARG`.
- **Compile errors do not fail the call.** `Compile` returns `S_OK` and the
result's `GetStatus` reports `E_FAIL`. The call itself fails only for API
misuse or out-of-memory. Clients depend on this.
- Outputs are keyed by `DXC_OUT_KIND`: `OBJECT` (DXIL container or SPIR-V
words), `ERRORS` (UTF-8 diagnostic text, also present on success when there
are warnings), `HLSL` (`-P`), `REFLECTION`, `SHADER_HASH`, `ROOT_SIGNATURE`,
`PDB`, and others. Each output can carry a name taken from the flags (`-Fo`,
`-Fre`, `-Fsh`, ...). The library never writes files; the client does.
- The source name is the first positional argument, or `hlsl.hlsl` if there is
none (`dxcompilerobj.cpp:588`). That name appears in diagnostics.
- Includes go through a virtual file system (`dxcfilesystem.cpp`). Clang's
header search builds each candidate path (including file's directory, then
`-I` directories) and passes it through `NormalizePathW` (`Support/Path.h`):
`\` becomes `/` on Unix, doubled slashes collapse, and relative paths get a
`./` prefix. Each candidate is then handed to `LoadSource`. **A failed
`LoadSource` means "try the next candidate", not "abort".** With a null
handler, nothing except the main buffer resolves, and DXC never touches the
disk itself. `IDxcUtils::CreateDefaultIncludeHandler` is the one that reads
from disk (`dxclibrary.cpp:41`).
## ABI facts libzdxc must match
These are exactly where a "looks right" reimplementation silently breaks.
1. **Vtable layout.** On Unix, `IUnknown` has three pure virtuals and *no
virtual destructor*. The destructor was removed specifically for ABI
(`47f31378a`, #3793). An interface pointer points at a vptr, and the vtable
is the base's slots followed by each derived interface's methods in
declaration order. This holds on both Itanium and MSVC, so one Zig
`extern struct { vtable: *const VTable }` layout serves both.
2. **Calling convention.** `STDMETHODCALLTYPE` and `__stdcall` are empty on Unix
(plain C convention). On Windows, use `callconv(.winapi)`. Two methods,
`IDxcResult::GetOutputByIndex` and `PrimaryOutput`, are declared without
`STDMETHODCALLTYPE`. They only differ on 32-bit Windows (`__thiscall`), which
can be ignored unless x86-32 is a target.
3. **`BOOL` is `bool` (1 byte) on Unix** (`WinAdapter.h:306`) and `int`
(4 bytes) on Windows. This affects `IDxcResult::HasOutput`,
`IDxcBlobEncoding::GetEncoding(BOOL *)`, and `IDxcPdbUtils::IsFullPDB`.
4. **`WCHAR` is `wchar_t`: UTF-32 on Unix, UTF-16 on Windows.** All `LPCWSTR`
arguments, file names passed to `LoadSource`, and `IDxcBlobWide` contents
follow this. `DXC_CP_WIDE` is `DXC_CP_UTF32` on Unix.
5. **`ULONG` is `unsigned long` on Unix** (64-bit on LP64). That is what
`AddRef`/`Release` return; in Zig that is `c_ulong`.
6. **GUIDs.** `__uuidof` is emulated on the client side through
`CROSS_PLATFORM_UUIDOF` templates, so the library only needs to compare
16-byte `GUID` values.
7. **HRESULTs** use the Windows values: `E_NOINTERFACE` 0x80004002, `E_NOTIMPL`
0x80004001, `E_POINTER` 0x80004003, `E_INVALIDARG`, `E_OUTOFMEMORY`,
`E_FAIL`, `REGDB_E_CLASSNOTREG`.
8. **Ownership.** Every returned interface carries one reference. Reference
counts must be atomic: DXC lets separate instances run on separate threads,
and clients release objects from any thread. Objects that clients pass in
(include handler, blobs) are borrowed; take an `AddRef` only when keeping
them.
9. **No unwinding across the boundary.** Every exported function and vtable
entry must catch every Zig error and turn it into an HRESULT.
## Proposed shape
### Layering
```
src/compile.zig Zig-native API: compile(gpa, Request) -> Result
Request { source, name, args: []const []const u8, fs: source.FileSystem }
Result { status, outputs: [kind]?Output } (bytes + name + code page)
src/options.zig dxc argv parser built on options_table (moved out of main.zig)
src/capi/ COM layer; the only code that knows about GUIDs and vtables
types.zig GUID, HRESULT, BOOL/WCHAR per target, CLSIDs/IIDs from dxcapi.h
object.zig Object(Impl, .{ interfaces... }) — atomic refcount, comptime QI table
blob.zig IDxcBlob / Encoding / Utf8 / Wide over owned, pinned, or IMalloc memory
result.zig IDxcResult + IDxcOperationResult over compile.Result
include.zig IDxcIncludeHandler -> source.FileSystem adapter (+ default disk handler)
compiler.zig IDxcCompiler3 (+ legacy IDxcCompiler/2 adapter), IDxcVersionInfo
utils.zig IDxcUtils, IDxcLibrary, IDxcCompilerArgs
exports.zig export fn DxcCreateInstance / DxcCreateInstance2
src/main.zig CLI built on compile.zig — the same relationship dxc has with dxcompiler
```
The important split is that `compile.zig` is the real library and `capi/` is a
translation shell. The CLI and the COM layer then exercise one code path. Zig
users can import the `zdxc` module and call `compile` directly with no COM.
Existing pieces already fit:
- `source.FileSystem` is a vtable, so an `IDxcIncludeHandler` adapter is a
single `read` implementation. It converts the candidate path to `WCHAR`,
calls `LoadSource`, decodes the blob to UTF-8, and maps failure to `null`.
The preprocessor must still produce dxc's candidate-path sequence and
`NormalizePathW` spelling, because handlers often match on exact strings.
Add an oracle test that logs `LoadSource` calls from both libraries.
- `Diagnostics.render` already writes to an `Io.Writer`. `DXC_OUT_ERRORS` is
that text rendered without color, in dxc's default format.
- `DxcCreateInstance2`'s `IMalloc` wraps directly into a `std.mem.Allocator`
(`Alloc` / `Realloc` / `Free`), which becomes the `gpa` for that object.
### Build artifacts
- `zig build` installs `libzdxc` both as a static library and as a shared
library. An option such as `-Ddxcompiler-name` would also name the shared
library `libdxcompiler.{so,dylib}` / `dxcompiler.dll`, so existing loaders
(`dxcapi.use.h`, hassle-rs, engines that `dlopen` by name) work unmodified.
- Optionally, add a `dxil` shim exporting `DxcCreateInstance` for
`CLSID_DxcValidator` only. Some clients, such as wgpu through hassle-rs,
require `dxil.dll` to load. Since zdxc signs its own output, that validator
can re-check the hash and return `S_OK`.
- Ship no headers of our own: clients keep using DXC's `dxcapi.h`. The ABI is
the contract.
### Staging
| Stage | Surface | Who needs it |
|---|---|---|
| L0 | exports, `IUnknown` machinery, blob family, `IDxcUtils` (`CreateBlob`, `CreateBlobFromPinned`, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8`), `IDxcCompiler3::Compile` (no `Disassemble`), `IDxcResult`, `IDxcVersionInfo` | modern engines; enough to run the drop-in oracle |
| L1 | legacy `IDxcLibrary`, `IDxcCompiler`/`IDxcCompiler2` (`Compile`, `Preprocess`), `IDxcOperationResult`, `IDxcCompilerArgs`, `IDxcUtils::BuildArguments` | hassle-rs and wgpu, older engines, `-P` users |
| L2 | `IDxcContainerReflection` (part listing), `IDxcUtils::GetDxilContainerPart`, `IDxcContainerBuilder`, `IDxcValidator` (hash check) | tooling that inspects containers |
| L3 | `IDxcUtils::CreateReflection` / `GetPartReflection` → `ID3D12ShaderReflection` (`d3d12shader.h`) | engines building root signatures from reflection |
| — | `Disassemble`, assembler, optimizer, linker, PDB utils, IntelliSense, rewriter, DIA | return `E_NOTIMPL` or `REGDB_E_CLASSNOTREG`, matching the plan's dropped list |
L3 is the expensive stage. DXC's `ID3D12ShaderReflection` reads the DXIL
module from the container's STAT part and walks its metadata, plus RDAT for
libraries. zdxc can serve it from bytes it wrote itself, but the reflection
interface is large (types, variables, constant buffers, bindings). Because
`CreateReflection` takes only a blob, the data must come from the container,
not from the compiler's memory. Schedule this alongside M0.1's reflection-match
exit criterion. SPIR-V clients use SPIRV-Reflect, not DXC, so it is DXIL-only.
Versioning: `IDxcVersionInfo::GetVersion` should report the DXC version
whose behavior zdxc matches (clients gate features on it), and
`IDxcVersionInfo3::GetCustomVersionString` should report `zdxc <version>`.
## Being a backend for Slang and SDL_shadercross
Read from Slang `c959b56` (`source/compiler-core/slang-dxc-compiler.cpp`) and
SDL_shadercross `1ff05be` (`src/SDL_shadercross.c`,
`cmake/FindDirectXShaderCompiler.cmake`). Neither client needs code changes:
both reach DXC only through `DxcCreateInstance`, so a library that matches the
ABI and is installed under DXC's names is a drop-in replacement. Both feed
DXC *machine-generated* HLSL, which makes them good acceptance corpora.
### SDL_shadercross (smallest surface; best first target)
- **Linking:** the DXC library is linked at build time (`extern
DxcCreateInstance`), not loaded with `dlopen`. CMake finds it either as a
vendored DXC subproject or through `FindDirectXShaderCompiler.cmake` with
`DirectXShaderCompiler_ROOT`. On non-Windows, that module *requires*
`dxcapi.h` in an include directory plus `libdxcompiler` and `libdxil`
libraries, even though the C code declares its own vtables and never includes
the header. So a zdxc install tree would need `include/dxcapi.h` (a
placeholder file would satisfy the lookup), `lib/libdxcompiler.*`, and a
`lib/libdxil.*` stub.
- **API used:** `CLSID_DxcCompiler`→`IDxcCompiler3::Compile`,
`CLSID_DxcUtils`→`IDxcUtils::CreateDefaultIncludeHandler`, and on
`IDxcResult`: `GetStatus`, `GetOutput(DXC_OUT_OBJECT, IID_IDxcBlob)`,
`GetOutput(DXC_OUT_ERRORS, IID_IDxcBlobUtf8)` (read on success too, for
warnings). That is exactly L0.
- **Inputs:** `DxcBuffer.Size = strlen + 1`, so **the source buffer includes
its NUL terminator**, and the encoding is `DXC_CP_ACP` (0). Arguments are
`-D…`, `-E`, `-I <dir>`, `-T {vs,ps,cs}_6_0` only, an optional bare source
name, and `-Zi` for debug builds. For SPIR-V: `-spirv
-fspv-flatten-resource-arrays -fspv-preserve-interface`, plus
`-fspv-preserve-bindings` unless unused bindings are culled, and
`-fspv-debug=vulkan-with-source` for debug builds. There is no `-HV`, so
dxc's default of 2021 applies.
- **Pipeline:** by default, `CompileDXILFromHLSL` **round-trips**:
HLSL →(DXC `-spirv`)→ SPIR-V →(SPIRV-Cross, `HLSL_SHADER_MODEL`)→ HLSL
→(DXC)→ DXIL. MSL output and all resource reflection come from SPIRV-Cross
reading DXC's SPIR-V, and DXC's own reflection is never used. Consequences:
- Both backends are on the critical path, and the DXIL backend must accept
SPIRV-Cross-generated HLSL.
- zdxc's SPIR-V must satisfy SPIRV-Cross, not just `spirv-val`. That means
the names, decorations, and interface variables reflection depends on, and
the three `-fspv-*` flags above.
- No `ID3D12ShaderReflection`, linker, or disassembler is needed.
- **Fit with the plan:** vs/ps/cs at 6.0 is inside M0.1. Shadercross is the
cheapest real client: L0 plus four `-fspv-*` flags.
### Slang
- **Platform gate:** `SLANG_ENABLE_DXIL_SUPPORT` defaults to **0 on Apple
platforms**, so stock Slang on macOS never calls dxcompiler. Testing on this
Mac needs a Slang build configured with it set to 1, or a Linux/Windows host.
- **Loading:** `dlopen("dxcompiler")` (or a path set with
`setDownstreamCompilerPath(SLANG_PASS_THROUGH_DXC, …)`). It tries `dxil`
first but ignores failure, so no dxil stub is needed.
`findFuncByName("DxcCreateInstance")`.
- **API used (legacy interfaces, so L1 is required):**
- `IDxcCompiler` and `IDxcLibrary::CreateBlobWithEncodingFromPinned`
(code page 0).
- `IDxcCompiler::Compile(source, name, entry, profile, args, …, includeHandler)`
with no defines.
- On `IDxcOperationResult`: `GetStatus`, `GetResult`, `GetErrorBuffer`.
- It queries `IDxcResult` from the operation result for `DXC_OUT_PDB` only
when PDB output is requested.
- **Version probing decides the language version.** Slang calls
`IDxcVersionInfo::GetVersion`, `IDxcVersionInfo2::GetCommitInfo`, and
`IDxcVersionInfo3::GetCustomVersionString`, and adds `-HV 2021` only if the
version is ≥ 1.7. The oracle reports `1.11(5583-f9fc72ad)`, so libzdxc should
report 1.11. The strings returned by `GetCommitInfo` and
`GetCustomVersionString` are freed by the client with `CoTaskMemFree`, which
is `free` on Unix (`WinAdapter.h:47`) and `CoTaskMemAlloc` on Windows. **So
libzdxc must allocate those with libc `malloc` / `CoTaskMemAlloc`, not a Zig
allocator**, which means the shared library links libc.
- **Include handler blobs are not real DXC blobs.** Slang's `LoadSource`
returns an `ISlangBlob` cast to `IDxcBlob*`. Only `GetBufferPointer` and
`GetBufferSize` can be trusted, and `QueryInterface` for `IDxcBlobEncoding`
fails. libzdxc must treat such blobs as raw bytes with BOM detection, never
assume they are its own blob type, and never downcast. Slang also resolves
includes itself from its search directories, so its handler is called with
dxc's candidate paths.
- **Arguments:** `-Zpr`, `-Gis`, `-denorm <mode>`, `-O0..3`/`-Od`, `-Zi`,
`-WX`, `-no-warnings` (always), `-enable-16bit-types`,
`-enable/-disable-payload-qualifiers`, plus user pass-through. Profiles
cover every stage, including `lib_6_x` for ray tracing.
- **Diagnostics:** Slang parses `ERRORS` as clang-style
`file:line:col: error|warning: msg`. That is zdxc's `clang` format, which
must stay the default for library output.
- **Optional extras:**
- `IDxcLinker` (`RegisterLibrary` + `Link`), used only when linking
precompiled DXIL modules. Slang then compiles the source as `lib_6_x`.
- `IDxcCompiler::Disassemble`, used only for `-target dxil-asm`.
Both are on the plan's dropped list; with them returning
`REGDB_E_CLASSNOTREG` / `E_NOTIMPL`, ordinary single-module compiles still
work.
- **Fit with the plan:** single-entry vs/ps/cs is M0.1. The rest of Slang's
stage coverage follows the plan's later milestones (hs/ds, ms/as, then `lib_`
at M0.5).
### Revised staging
1. **L0 + shadercross acceptance.** Build `test/clients/shadercross.sh`: build
shadercross against a zdxc install tree, run its CLI over its test shaders
for SPIR-V, DXIL (round-trip), and MSL, and compare with the same run
against DXC (DXIL through `dxv`, SPIR-V through `spirv-val`, MSL text
directly).
2. **L1 + Slang acceptance** on Linux, or a Slang built with
`SLANG_ENABLE_DXIL_SUPPORT=1`. Corpus: `slangc -target hlsl` output from
Slang's tests, compiled through both libraries.
3. Linker and disassembler only if Slang's precompiled-module or `dxil-asm`
paths turn out to matter.
## Testing
An ABI harness under `test/capi/`, written in C++ and compiled with
`zig c++` against the DXC tree's `include/dxc/dxcapi.h` (read in place, not
vendored). It `dlopen`s a library by path and runs a fixed script: create each
CLSID, query each IID, compile the oracle corpus through `IDxcCompiler3` and
the legacy interface, use a logging include handler, and dump status, the
output kinds present, error text, and object bytes. Running it against
`build/lib/libdxcompiler.dylib` and against libzdxc, then diffing (objects
compared through `dxv`, as the CLI oracle already does), gives drop-in
compatibility the same oracle treatment as the CLI.
## Open questions
- Should `zig build` produce the drop-in name by default, or opt-in only?
- Acceptance order: SDL_shadercross first, then Slang (see above). hassle-rs
and wgpu also use the legacy interfaces, so L1 for Slang covers them too
(not yet verified against hassle-rs source).
- Shadercross's lookup needs a `dxcapi.h` to exist. Ship a placeholder, or
install DXC's header? Its license (NCSA) allows redistribution, but the
project rule only allows vendoring data files.
- Does any target need 32-bit Windows? That would force the `__thiscall`
handling for the two `IDxcResult` methods.

File diff suppressed because it is too large Load Diff

View File

@ -25,6 +25,13 @@ pub const Info = struct {
flags: u64 = 0,
min_minor: u8 = 0,
mask: u32 = op_compat.all_stages,
/// A callee's requirements added to its caller's.
pub fn merge(info: *Info, callee: Info) void {
info.flags |= callee.flags;
info.min_minor = @max(info.min_minor, callee.min_minor);
info.mask &= callee.mask;
}
};
pub const bit = struct {
@ -50,6 +57,7 @@ pub const bit = struct {
pub const extended_command_info = 1 << 38;
pub const uses_derivatives = 1 << 39;
pub const requires_group = 1 << 40;
pub const linear_algebra = 1 << 41;
/// Not part of the module's flags.
pub const local = uses_derivatives | requires_group;
};
@ -148,6 +156,7 @@ pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) I
const args = inst.op.call.args;
if ((code >= 110 and code <= 123) or (code >= 135 and code <= 136) or (code >= 165 and code <= 167) or code == 222 or (code >= 312 and code <= 313)) fl |= bit.wave;
if (code >= 174 and code <= 177) fl |= bit.sampler_feedback;
if (code >= 322 and code <= 342) fl |= bit.linear_algebra;
switch (code) {
71 => check_access = true,
50 => fl |= bit.msad,
@ -227,7 +236,7 @@ pub fn featureInfo(fl: u64) u64 {
.{ bit.view_id, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ bit.wave, 0x4000 },
.{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 },
.{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 },
.{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
};
var out: u64 = 0;

400
src/dxil/linalg_info.zig Normal file
View File

@ -0,0 +1,400 @@
//! The SM 6.10 linear algebra usage the PSV0 part records (and the
//! validator recomputes from the module): matrix constructions, matrix-
//! vector and matrix-matrix multiplies, outer products and accumulating
//! stores. A port of dxc's LinAlgRuntimeInfoCollector.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const rdat = @import("rdat.zig");
/// A matrix type's attributes (`!dx.targetTypes`).
pub const Matrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
pub const Shape = struct { m: u32, n: u32, k: u32 };
/// The serialized tables (PSVLinAlg*0 records) and the shape index runs to
/// put in the semantic index table first.
pub const Tables = struct {
shapes: []const Shape,
/// PSVLinAlgRuntimeInfo0 record bytes, per table in declaration order:
/// constructions, thread mat-vec multiplies, wave multiplies,
/// thread-group multiplies, outer products, accumulate stores.
records: [6][]const u8,
counts: [6]u32,
sizes: [6]u32 = .{ 12, 4, 12, 12, 4, 4 },
semantic_indices: []const u32,
pub fn empty(t: Tables) bool {
if (t.shapes.len > 0) return false;
for (t.counts) |c| if (c > 0) return false;
return true;
}
};
const Key2 = [2]u8;
const Key3 = [3]u8;
const Key4 = [4]u8;
pub const Info = struct {
constructions: std.AutoArrayHashMapUnmanaged(Key2, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
matvec: std.AutoArrayHashMapUnmanaged(Key3, u8) = .empty,
multiplies: std.AutoArrayHashMapUnmanaged(Key4, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
outer: std.AutoArrayHashMapUnmanaged(Key2, void) = .empty,
accumulate: std.AutoArrayHashMapUnmanaged(u8, u8) = .empty,
};
const transposed: u8 = 1;
const non_mul_optimal: u8 = 2;
pub const Matrices = []const struct { module.TypeId, Matrix };
/// Collects the usage in every function of `m`; `matrices` maps matrix
/// types to their attributes.
pub fn collect(a: Allocator, m: *const module.Module, matrices: Matrices) Allocator.Error!Tables {
var info: Info = .{};
const c: C = .{ .m = m, .mats = matrices };
for (m.functions.items) |*f| try collectFunction(a, c, &info, f);
return serialize(a, &info);
}
/// The usage of function `func` and of the functions it calls (dxc merges
/// callee usage into callers).
pub fn functionInfo(a: Allocator, m: *const module.Module, matrices: Matrices, func: u32) Allocator.Error!Info {
var info: Info = .{};
const c: C = .{ .m = m, .mats = matrices };
var seen: std.AutoArrayHashMapUnmanaged(u32, void) = .empty;
try seen.put(a, func, {});
var k: usize = 0;
while (k < seen.count()) : (k += 1) {
const f = &m.functions.items[seen.keys()[k]];
try collectFunction(a, c, &info, f);
for (f.insts.items) |inst| if (inst.op == .call) {
const callee = inst.op.call.callee;
if (m.functions.items[callee].num_blocks > 0) try seen.put(a, callee, {});
};
}
return info;
}
const C = struct {
m: *const module.Module,
mats: Matrices,
fn matrix(c: @This(), ty: ?module.TypeId) ?Matrix {
const t = ty orelse return null;
for (c.mats) |x| if (x[0] == t) return x[1];
return null;
}
fn constInt(c: @This(), v: module.Value) ?u32 {
if (v != .constant) return null;
return switch (c.m.constants.items[v.constant].kind) {
.int => |x| @truncate(@as(u64, @bitCast(x))),
else => null,
};
}
/// DXIL::ComponentType of a scalar (or a vector's element).
fn component(c: @This(), ty: module.TypeId, signed: bool) u8 {
const t = switch (c.m.types.items[ty]) {
.vector => |v| c.m.types.items[v.elem],
else => |x| x,
};
return switch (t) {
.half => 8,
.float => 9,
.double => 10,
.int => |w| switch (w) {
8 => if (signed) 19 else 20,
16 => if (signed) 2 else 3,
32 => if (signed) 4 else 5,
64 => if (signed) 6 else 7,
else => 0,
},
else => 0,
};
}
};
fn collectFunction(a: Allocator, c: C, info: *Info, f: *const module.Function) Allocator.Error!void {
const m = c.m;
const fty = m.types.items[f.ty].function;
const typeOf = struct {
fn t(mm: *const module.Module, ff: *const module.Function, ft: @FieldType(module.Type, "function"), v: module.Value) ?module.TypeId {
return switch (v) {
.global => |g| mm.globals.items[g].ptr_ty,
.function => null,
.constant => |k| mm.constants.items[k].ty,
.arg => |x| ft.params[x],
.inst => |i| ff.insts.items[i].ty,
};
}
}.t;
for (f.insts.items) |inst| {
if (inst.op != .call) continue;
const call = inst.op.call;
if (!std.mem.startsWith(u8, m.functions.items[call.callee].name, "dx.op.linAlg") or call.args.len == 0) continue;
const op = c.constInt(call.args[0]) orelse continue;
const arg = struct {
fn t(cc: C, ff: *const module.Function, ft: @FieldType(module.Type, "function"), args: []const module.Value, k: usize) ?module.TypeId {
return if (k < args.len) typeOf(cc.m, ff, ft, args[k]) else null;
}
}.t;
switch (op) {
336, 337 => {
const mat = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const signed = (c.constInt(call.args[2]) orelse 0) != 0;
const key: Key3 = .{ c.component(inst.ty, signed), @intCast(mat.comp), @intCast(c.constInt(call.args[4]) orelse 0) };
const gop = try info.matvec.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= layoutFlags(c, f, call.args[1]);
},
334, 322 => {
const r = c.matrix(inst.ty) orelse continue;
const ma = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const mb = c.matrix(arg(c, f, fty, call.args, 2)) orelse continue;
const key: Key4 = .{ @intCast(r.scope), @intCast(r.comp), @intCast(ma.comp), @intCast(mb.comp) };
const gop = try info.multiplies.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.put(a, .{ .m = ma.m, .n = mb.n, .k = ma.n }, {});
},
340 => {
const r = c.matrix(inst.ty) orelse continue;
const signed = (c.constInt(call.args[1]) orelse 0) != 0;
const vt = arg(c, f, fty, call.args, 2) orelse continue;
try info.outer.put(a, .{ @intCast(r.comp), c.component(vt, signed) }, {});
},
338, 339 => {
const mat = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const gop = try info.accumulate.getOrPut(a, @intCast(mat.comp));
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= if (op == 338) 1 else 2;
},
342 => {
const vt = arg(c, f, fty, call.args, 4) orelse continue;
const gop = try info.accumulate.getOrPut(a, c.component(vt, true));
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= 1;
},
else => {
try construction(a, info, c.matrix(inst.ty));
for (call.args, 0..) |_, k| try construction(a, info, c.matrix(arg(c, f, fty, call.args, k)));
},
}
}
}
fn construction(a: Allocator, info: *Info, mat: ?Matrix) Allocator.Error!void {
const x = mat orelse return;
if (x.scope == 0) return; // Thread
const shape: Shape = .{
.m = if (x.use == 1) 0 else x.m,
.n = if (x.use == 0) 0 else x.n,
.k = if (x.use == 2) 0 else if (x.use == 0) x.n else x.m,
};
const gop = try info.constructions.getOrPut(a, .{ @intCast(x.comp), @intCast(x.use) });
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.put(a, shape, {});
}
/// How a mat-vec multiply's matrix was loaded (both flags when unknown:
/// zdxc's matrices pass through local variables).
fn layoutFlags(c: anytype, f: *const module.Function, v0: module.Value) u8 {
var v = v0;
var flags: u8 = 0;
var steps: usize = 0;
while (steps < 64) : (steps += 1) {
if (v != .inst) return transposed | non_mul_optimal;
const inst = f.insts.items[v.inst];
if (inst.op != .call) return transposed | non_mul_optimal;
const call = inst.op.call;
const op = if (call.args.len > 0) c.constInt(call.args[0]) else null;
if (op == 324) {
v = call.args[1];
continue;
}
if (op == 325) {
const layout = c.constInt(call.args[4]) orelse return transposed | non_mul_optimal;
if (layout == 3) flags |= transposed else if (layout != 2) flags |= non_mul_optimal;
return flags;
}
return transposed | non_mul_optimal;
}
return transposed | non_mul_optimal;
}
fn lessShape(_: void, x: Shape, y: Shape) bool {
if (x.m != y.m) return x.m < y.m;
if (x.n != y.n) return x.n < y.n;
return x.k < y.k;
}
fn sortedShapes(a: Allocator, set: std.AutoArrayHashMapUnmanaged(Shape, void)) Allocator.Error![]Shape {
const out = try a.dupe(Shape, set.keys());
std.sort.insertion(Shape, out, {}, lessShape);
return out;
}
fn sortedKeys(comptime K: type, a: Allocator, keys: []const K) Allocator.Error![]K {
const out = try a.dupe(K, keys);
std.sort.insertion(K, out, {}, struct {
fn lt(_: void, x: K, y: K) bool {
return std.mem.order(u8, std.mem.asBytes(&x), std.mem.asBytes(&y)) == .lt;
}
}.lt);
return out;
}
const Writer = struct {
a: Allocator,
shapes: std.ArrayList(Shape) = .empty,
indices: std.ArrayList(u32) = .empty,
/// AddLinAlgShapes: shape table indexes, as a run in the semantic
/// index table (shared with an equal earlier run).
fn shapeRun(w: *Writer, shapes: []const Shape) Allocator.Error![2]u32 {
var idx: std.ArrayList(u32) = .empty;
for (shapes) |s| {
const k = for (w.shapes.items, 0..) |x, i| {
if (std.meta.eql(x, s)) break i;
} else blk: {
try w.shapes.append(w.a, s);
break :blk w.shapes.items.len - 1;
};
try idx.append(w.a, @intCast(k));
}
var off: usize = 0;
while (off + idx.items.len <= w.indices.items.len) : (off += 1) {
if (std.mem.eql(u32, w.indices.items[off..][0..idx.items.len], idx.items)) return .{ @intCast(off), @intCast(idx.items.len) };
}
const at: u32 = @intCast(w.indices.items.len);
try w.indices.appendSlice(w.a, idx.items);
return .{ at, @intCast(idx.items.len) };
}
};
fn put32(a: Allocator, out: *std.ArrayList(u8), v: u32) Allocator.Error!void {
var b: [4]u8 = undefined;
std.mem.writeInt(u32, &b, v, .little);
try out.appendSlice(a, &b);
}
fn serialize(a: Allocator, info: *Info) Allocator.Error!Tables {
var w: Writer = .{ .a = a };
var recs: [6]std.ArrayList(u8) = .{ .empty, .empty, .empty, .empty, .empty, .empty };
var counts: [6]u32 = .{ 0, 0, 0, 0, 0, 0 };
// (std::map order: keys sorted.)
for (try sortedKeys(Key2, a, info.constructions.keys())) |k| {
const run = try w.shapeRun(try sortedShapes(a, info.constructions.get(k).?));
try put32(a, &recs[0], run[0]);
try put32(a, &recs[0], run[1]);
try recs[0].appendSlice(a, &.{ k[0], 0, 0, 0 });
counts[0] += 1;
}
for (try sortedKeys(Key3, a, info.matvec.keys())) |k| {
try recs[1].appendSlice(a, &.{ k[0], k[1], k[2], info.matvec.get(k).? });
counts[1] += 1;
}
for (try sortedKeys(Key4, a, info.multiplies.keys())) |k| {
const run = try w.shapeRun(try sortedShapes(a, info.multiplies.get(k).?));
const t: usize = if (k[0] == 1) 2 else 3; // Wave, else ThreadGroup
try put32(a, &recs[t], run[0]);
try put32(a, &recs[t], run[1]);
try recs[t].appendSlice(a, &.{ k[1], k[2], k[3], 0 });
counts[t] += 1;
}
for (try sortedKeys(Key2, a, info.outer.keys())) |k| {
try recs[4].appendSlice(a, &.{ k[0], k[1], 0, 0 });
counts[4] += 1;
}
for (try sortedKeys(u8, a, info.accumulate.keys())) |k| {
try recs[5].appendSlice(a, &.{ k, info.accumulate.get(k).?, 0, 0 });
counts[5] += 1;
}
return .{
.shapes = w.shapes.items,
.records = .{ recs[0].items, recs[1].items, recs[2].items, recs[3].items, recs[4].items, recs[5].items },
.counts = counts,
.semantic_indices = w.indices.items,
};
}
/// The PSV0 LinAlg block: PSVLinAlgRuntimeInfo0, then each non-empty
/// table as its record size and records.
pub fn psvBlock(a: Allocator, t: Tables, out: *std.ArrayList(u8)) Allocator.Error!void {
try put32(a, out, 28); // sizeof(PSVLinAlgRuntimeInfo0)
try put32(a, out, @intCast(t.shapes.len));
for (t.counts) |n| try put32(a, out, n);
if (t.shapes.len > 0) {
try put32(a, out, 12);
for (t.shapes) |s| for ([_]u32{ s.m, s.n, s.k }) |v| try put32(a, out, v);
}
for (t.records, t.counts, t.sizes) |r, n, sz| if (n > 0) {
try put32(a, out, sz);
try out.appendSlice(a, r);
};
}
/// AddLinAlgShapes: the shape records' index array.
fn rdatShapes(a: Allocator, b: *rdat.Builder, set: std.AutoArrayHashMapUnmanaged(Shape, void)) Allocator.Error!u32 {
var idx: std.ArrayList(u32) = .empty;
for (try sortedShapes(a, set)) |s| {
var rec: [12]u8 = undefined;
for ([_]u32{ s.m, s.n, s.k }, 0..) |v, k| std.mem.writeInt(u32, rec[4 * k ..][0..4], v, .little);
try idx.append(a, try b.record(.shapes, &rec));
}
return b.array(idx.items);
}
/// A record with an index array reference, then four bytes.
fn refRecord(ref: u32, tail: [4]u8) [8]u8 {
var rec: [8]u8 = undefined;
std.mem.writeInt(u32, rec[0..4], ref, .little);
rec[4..8].* = tail;
return rec;
}
/// The function's RDAT ExtendedProperties (dxc's
/// AddLinAlgFunctionProperties): one property per non-empty kind, in
/// FunctionPropertyType order.
pub fn rdatProperties(a: Allocator, b: *rdat.Builder, info: *const Info) Allocator.Error!u32 {
var props: std.ArrayList(u32) = .empty;
var recs: std.ArrayList(u32) = .empty;
const flush = struct {
fn f(aa: Allocator, bb: *rdat.Builder, ps: *std.ArrayList(u32), rs: *std.ArrayList(u32), ty: u32) Allocator.Error!void {
if (rs.items.len == 0) return;
var arr: [4]u8 = undefined;
std.mem.writeInt(u32, &arr, try bb.array(rs.items), .little);
try ps.append(aa, try bb.record(.properties, &refRecord(ty, arr)));
rs.clearRetainingCapacity();
}
}.f;
for (try sortedKeys(Key2, a, info.constructions.keys())) |k| {
const shapes = try rdatShapes(a, b, info.constructions.get(k).?);
try recs.append(a, try b.record(.constructions, &refRecord(shapes, .{ k[0], 0, 0, 0 })));
}
try flush(a, b, &props, &recs, 1);
for (try sortedKeys(Key3, a, info.matvec.keys())) |k| {
try recs.append(a, try b.record(.thread_matvec, &.{ k[0], k[1], k[2], info.matvec.get(k).? }));
}
try flush(a, b, &props, &recs, 2);
const mul_keys = try sortedKeys(Key4, a, info.multiplies.keys());
for ([_]u8{ 1, 2 }, [_]rdat.Ext{ .wave_multiplies, .group_multiplies }, [_]u32{ 3, 4 }) |scope, t, ty| {
for (mul_keys) |k| if (k[0] == scope) {
const shapes = try rdatShapes(a, b, info.multiplies.get(k).?);
try recs.append(a, try b.record(t, &refRecord(shapes, .{ k[1], k[2], k[3], 0 })));
};
try flush(a, b, &props, &recs, ty);
}
for (try sortedKeys(Key2, a, info.outer.keys())) |k| {
try recs.append(a, try b.record(.outer_products, &.{ k[0], k[1], 0, 0 }));
}
try flush(a, b, &props, &recs, 5);
for (try sortedKeys(u8, a, info.accumulate.keys())) |k| {
try recs.append(a, try b.record(.accumulate_stores, &.{ k, info.accumulate.get(k).?, 0, 0 }));
}
try flush(a, b, &props, &recs, 6);
if (props.items.len == 0) return rdat.null_ref;
return b.array(props.items);
}

View File

@ -114,7 +114,7 @@ fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), na
if (ty == TypeTable.void_type) return out.append(a, 'X');
switch (t.get(ty)) {
.scalar => |s| try out.appendSlice(a, scalarCode(s)),
.@"enum" => |en| try className(a, 'W', try std.fmt.allocPrint(a, "4{s}", .{en.name}), out, names),
.@"enum" => |en| try qualifiedName(a, t, "W4", en.name, en.scopes, out, names),
.vector => |v| {
var args: std.ArrayList(u8) = .empty;
try args.appendSlice(a, scalarCode(v.elem));
@ -141,7 +141,7 @@ fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), na
for (dims.items) |d| try number(a, d, out);
try typeCode(a, t, et, out, names);
},
.@"struct" => |st| try className(a, 'U', st.name, out, names),
.@"struct" => |st| try qualifiedName(a, t, if (st.is_class) "V" else "U", try structName(a, t, st), st.scopes, out, names),
.resource => |r| {
if (r.elem == TypeTable.void_type or r.kind == .raytracing_acceleration_structure) return className(a, 'U', r.name, out, names);
// Template arguments have names of their own.
@ -166,6 +166,47 @@ fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), na
}
}
/// A struct's own name: `name`, or `?$name@<args>@` for a template
/// instance (its arguments with names of their own).
fn structName(a: Allocator, t: *TypeTable, st: *const types.StructInfo) Allocator.Error![]const u8 {
const base = st.base_name orelse return st.name;
var out: std.ArrayList(u8) = .empty;
var inner: Names = .{};
try inner.add(a, base);
try out.print(a, "?${s}@", .{base});
for (st.template_args) |arg| switch (arg) {
.type => |ty| try typeCode(a, t, ty, &out, &inner),
.value => |v| {
try out.appendSlice(a, "$0");
if (v < 0) try out.append(a, '?');
try number(a, @abs(v), &out);
},
};
try out.append(a, '@');
return out.items;
}
/// `<kind><name><scope>@...@`: the name and each enclosing scope's,
/// innermost first, each a back-reference when already spelled.
fn qualifiedName(a: Allocator, t: *TypeTable, kind: []const u8, name: []const u8, scopes: []const types.ScopeName, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {
try out.appendSlice(a, kind);
try namePart(a, name, out, names);
for (scopes) |sc| try namePart(a, switch (sc) {
.name => |n| n,
.strct => |st| try structName(a, t, st),
}, out, names);
try out.append(a, '@');
}
/// One part of a qualified name: `name@` (template instances end in `@`
/// themselves), or a back-reference digit.
fn namePart(a: Allocator, name: []const u8, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {
if (names.find(name)) |k| return out.append(a, '0' + @as(u8, @intCast(k)));
try out.appendSlice(a, name);
if (name[0] != '?') try out.append(a, '@');
try names.add(a, name);
}
/// `<kind><name>@@`, or `<kind><backref>@` for a name already spelled
/// (template instances `?$name@args@` end in `@` themselves).
fn className(a: Allocator, kind: u8, name: []const u8, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {

View File

@ -55,7 +55,7 @@ pub const Constant = struct {
pub const Linkage = enum(u32) { external = 0, internal = 3 };
/// Attribute group for function declarations (e.g. dx.op functions).
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind };
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind };
pub const Value = union(enum) {
/// Index into Module.globals (a pointer to the variable).
@ -276,6 +276,10 @@ const Encoder = struct {
m: *Module,
w: bitstream.Writer,
ops: std.ArrayList(u64) = .empty,
/// The function being written, and each of its instructions' value
/// ID offset (non-void instructions before it).
numbered: ?*const Function = null,
inst_ids: std.ArrayList(u32) = .empty,
fn gpa(e: *Encoder) Allocator {
return e.w.gpa;
@ -305,12 +309,9 @@ const Encoder = struct {
.arg => |a| e.moduleValueCount() + a,
.inst => |i| blk: {
const func = f.?;
std.debug.assert(e.numbered == func);
const nargs: u32 = @intCast(e.m.types.items[func.ty].function.params.len);
var n: u32 = 0;
for (func.insts.items[0..i]) |prev| {
if (e.m.types.items[prev.ty] != .void) n += 1;
}
break :blk e.moduleValueCount() + nargs + n;
break :blk e.moduleValueCount() + nargs + e.inst_ids.items[i];
},
};
}
@ -337,6 +338,7 @@ const Encoder = struct {
fn write(e: *Encoder) ![]u8 {
defer e.ops.deinit(e.gpa());
defer e.inst_ids.deinit(e.gpa());
const w = &e.w;
try w.emit('B', 8);
try w.emit('C', 8);
@ -382,11 +384,12 @@ const Encoder = struct {
}
fn writeAttributes(e: *Encoder) !void {
// Groups 1..4 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: noreturn = 17, nounwind = 18, readnone = 20, readonly = 21.
// Groups 1..5 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: noinline = 14, noreturn = 17, nounwind = 18,
// readnone = 20, readonly = 21.
const w = &e.w;
try w.enterBlock(block_paramattr_group, 3);
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 } };
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 } };
for (groups, 1..) |kinds, id| {
try e.push(id);
try e.push(0xFFFFFFFF);
@ -533,6 +536,13 @@ const Encoder = struct {
fn writeFunction(e: *Encoder, f: *const Function) !void {
const w = &e.w;
e.inst_ids.clearRetainingCapacity();
var n: u32 = 0;
for (f.insts.items) |inst| {
try e.inst_ids.append(e.gpa(), n);
if (e.m.types.items[inst.ty] != .void) n += 1;
}
e.numbered = f;
try w.enterBlock(block_function, 4);
try e.push(f.num_blocks);
try e.rec(1); // DECLAREBLOCKS
@ -613,14 +623,14 @@ const Encoder = struct {
.load => |l| {
try e.pushValueAndType(f, inst_id, l.ptr);
try e.push(inst.ty);
try e.push(@as(u64, std.math.log2_int(u32, l.@"align")) + 1);
try e.push(if (l.@"align" == 0) 0 else @as(u64, std.math.log2_int(u32, l.@"align")) + 1);
try e.push(0);
try e.rec(20);
},
.store => |s| {
try e.pushValueAndType(f, inst_id, s.ptr);
try e.pushValueAndType(f, inst_id, s.val);
try e.push(@as(u64, std.math.log2_int(u32, s.@"align")) + 1);
try e.push(if (s.@"align" == 0) 0 else @as(u64, std.math.log2_int(u32, s.@"align")) + 1);
try e.push(0);
try e.rec(44);
},

View File

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

View File

@ -2,6 +2,7 @@
//! only covers an empty compute shader; later milestones feed it from the IR.
const std = @import("std");
const linalg_info = @import("linalg_info.zig");
const Allocator = std.mem.Allocator;
const Module = @import("module.zig").Module;
const container = @import("container.zig");
@ -150,6 +151,8 @@ pub const PsvInfo = struct {
max_vertex_count: u16 = 0,
mesh_topology: u8 = 0,
uses_view_id: bool = false,
/// SM 6.10 linear algebra usage.
linalg: ?linalg_info.Tables = null,
};
pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 {
@ -194,6 +197,9 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// Semantic index table, with runs shared between elements.
var indices: std.ArrayList(u32) = .empty;
defer indices.deinit(gpa);
// (Linear algebra shape runs come first, as in dxc.)
const linalg: ?linalg_info.Tables = if (info.linalg) |t| (if (t.empty()) null else t) else null;
if (linalg) |t| try indices.appendSlice(gpa, t.semantic_indices);
var records: std.ArrayList(u8) = .empty;
defer records.deinit(gpa);
for ([_][]const signature.Element{ info.inputs, info.outputs, info.patch_constants }) |els| for (els) |e| {
@ -226,7 +232,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
try w(&buf, gpa, entry_off);
// PSVRuntimeInfo4
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
try w(&buf, gpa, 0); // Flags
try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
try w(&buf, gpa, @intCast(info.resources.len));
if (info.resources.len > 0) {
@ -264,6 +270,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// (domain).
if (info.kind == .hull and pc_vectors > 0 and in_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, pc_vectors) * 4);
if (info.kind == .domain and out_vectors[0] > 0 and pc_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(pc_vectors, out_vectors[0]) * 4);
if (linalg) |t| try linalg_info.psvBlock(gpa, t, &buf);
return buf.toOwnedSlice(gpa);
}

View File

@ -48,6 +48,9 @@ pub const TypeRef = struct {
/// Type attributes written on this reference, in order: `row_major`,
/// `column_major`, `unorm`, `snorm` (template arguments, typedefs).
attr_words: []const QualWord = &.{},
/// `#pragma pack_matrix` in effect where the type was written (true:
/// row_major): the orientation of a matrix declared without one.
pack_matrix: ?bool = null,
};
/// Storage classes, type qualifiers and parameter / interpolation
@ -285,7 +288,8 @@ pub const Decl = struct {
func: FuncDecl,
@"struct": StructDecl,
cbuffer: CBufferDecl,
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{}, attrs: []const Attribute = &.{} },
/// `alias`: written `using name = type;`.
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{}, attrs: []const Attribute = &.{}, alias: bool = false },
@"enum": EnumDecl,
namespace: struct { name: []const u8, decls: []const *Decl },
/// `using namespace N;`

View File

@ -31,6 +31,10 @@ pub const Parser = struct {
names: std.StringHashMapUnmanaged(std.ArrayList(NameKind)) = .empty,
/// Names declared in each open scope, to undo on exit.
scopes: std.ArrayList(std.ArrayList([]const u8)) = .empty,
/// Types declared in any struct (template ones included, whose scope
/// ends with the template): types as the last part of a qualified
/// name (`S<T>::Inner`).
member_types: std.StringHashMapUnmanaged(void) = .empty,
anon_count: u32 = 0,
/// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`.
@ -45,18 +49,55 @@ pub const Parser = struct {
/// The last parseName ended in `::template X`: X takes template
/// arguments whatever it names.
forced_template: bool = false,
/// `#pragma pack_matrix` lines: the position of the token after them,
/// and row_major.
pack_pragmas: []const PackPragma = &.{},
const PackPragma = struct { pos: usize, row_major: bool };
/// Collect every token from `pp` and set up a parser over them.
pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser {
var toks: std.ArrayList(Token) = .empty;
var packs: std.ArrayList(PackPragma) = .empty;
while (true) {
// Preprocessor diagnostics are ordered by the token being produced.
diags.position = toks.items.len;
const t = try pp.next();
// `#pragma pack_matrix` may come between any two tokens (as in
// dxc): it is kept aside, not in the token stream.
if (t.kind == .pragma) if (packMatrix(t.text)) |rm| {
try packs.append(arena, .{ .pos = toks.items.len, .row_major = rm });
continue;
};
try toks.append(arena, t);
if (t.kind == .eof) break;
}
return .{ .arena = arena, .diags = diags, .toks = toks.items };
return .{ .arena = arena, .diags = diags, .toks = toks.items, .pack_pragmas = packs.items };
}
/// `pack_matrix(row_major)` / `pack_matrix(column_major)`.
fn packMatrix(text: []const u8) ?bool {
var buf: [64]u8 = undefined;
var n: usize = 0;
for (text) |c| if (!std.ascii.isWhitespace(c)) {
if (n == buf.len) return null;
buf[n] = c;
n += 1;
};
const s = buf[0..n];
if (std.mem.eql(u8, s, "pack_matrix(row_major)")) return true;
if (std.mem.eql(u8, s, "pack_matrix(column_major)")) return false;
return null;
}
/// The `#pragma pack_matrix` in effect at token `pos`.
fn packMatrixAt(p: *const Parser, pos: usize) ?bool {
var r: ?bool = null;
for (p.pack_pragmas) |pp| {
if (pp.pos > pos) break;
r = pp.row_major;
}
return r;
}
pub fn parseTranslationUnit(p: *Parser) Allocator.Error!ast.TranslationUnit {
@ -281,6 +322,11 @@ pub const Parser = struct {
return isBuiltinType(name);
}
/// The last part of a qualified name: also a struct's member type.
fn isMemberTypeName(p: *const Parser, name: []const u8) bool {
return p.isTypeName(name) or p.member_types.contains(name);
}
fn isTemplateName(p: *const Parser, name: []const u8) bool {
if (p.lookupName(name)) |k| {
if (k == .template_type or k == .template_func) return true;
@ -306,6 +352,7 @@ pub const Parser = struct {
return p.skipTypeAttrs(p.skipParens(i + 1) orelse return null);
}
if (p.toks[i].kind == .colon_colon) i += 1;
var qualified = false;
while (true) {
const t = p.toks[i];
if (t.kind != .identifier or isReserved(t.text)) return null;
@ -316,9 +363,10 @@ pub const Parser = struct {
}
if (p.toks[after].kind == .colon_colon and p.toks[after + 1].kind == .identifier) {
i = after + 1;
qualified = true;
continue;
}
if (!p.isTypeName(t.text)) return null;
if (!(if (qualified) p.isMemberTypeName(t.text) else p.isTypeName(t.text))) return null;
return p.skipTypeAttrs(after);
}
}
@ -492,7 +540,9 @@ pub const Parser = struct {
if (w.isIdent("unorm")) norm = .unorm;
if (w.isIdent("snorm")) norm = .snorm;
}
const type_pos = p.pos;
const t = try p.parseTypeInner();
t.pack_matrix = p.packMatrixAt(type_pos);
if (norm != .none) t.norm = norm;
if (words.items.len > 0) t.attr_words = words.items;
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
@ -524,7 +574,7 @@ pub const Parser = struct {
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = try p.simpleName(start.loc, name), .unsigned_spec = !signed });
}
const name = try p.parseName();
if (!p.isTypeName(name.last())) {
if (!(if (name.parts.len > 1) p.isMemberTypeName(name.last()) else p.isTypeName(name.last()))) {
p.diags.position = p.pos;
_ = p.diags.report(.{ .severity = .@"error", .loc = start.loc, .len = @intCast(start.text.len) }, "unknown type name '{s}'", .{name.last()});
return error.Syntax;
@ -849,7 +899,10 @@ pub const Parser = struct {
// that `S::Inner` resolves; the name table is flat by last name.
var nested: std.ArrayList(struct { []const u8, NameKind }) = .empty;
for (p.scopes.items[p.scopes.items.len - 1].items) |n| {
if (p.lookupName(n)) |k| if (k == .type or k == .template_type) try nested.append(p.arena, .{ n, k });
if (p.lookupName(n)) |k| if (k == .type or k == .template_type) {
try nested.append(p.arena, .{ n, k });
if (k == .type) try p.member_types.put(p.arena, n, {});
};
}
p.popScope();
for (nested.items) |n| try p.declareName(n[0], n[1]);
@ -972,7 +1025,7 @@ pub const Parser = struct {
const dims = try p.parseArrayDims();
_ = try p.expect(.semi, "';'");
try p.declareNameOuter(name.text, if (template_params.len > 0) .template_type else .type, template_params.len > 0);
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .template_params = template_params, .attrs = attrs } } });
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .template_params = template_params, .attrs = attrs, .alias = true } } });
}
fn parseNamespace(p: *Parser) Error!*ast.Decl {

View File

@ -184,6 +184,9 @@ pub const Param = struct {
ty: TypeId,
/// out / inout: passed as a pointer to caller storage.
by_ref: bool,
/// `groupshared` parameters: a pointer to the caller's groupshared
/// variable (by_ref too).
groupshared: bool = false,
/// in, out, inout (library function annotations).
dir: enum { in, out, inout } = .in,
/// The HLSL type (before patches become arrays), for mangled names.
@ -202,6 +205,9 @@ pub const Function = struct {
/// Declaration order of the HLSL function (libraries define functions
/// in this order).
decl_order: u32 = std.math.maxInt(u32),
/// `[noinline]` (plain functions, not methods or template instances):
/// libraries keep it a function of its own.
no_inline: bool = false,
insts: std.ArrayList(Inst) = .empty,
blocks: std.ArrayList(Block) = .empty,
@ -303,6 +309,9 @@ pub const BindingDecl = struct {
/// [[vk::combinedImageSampler]]: `s` registers shift like `t` ones.
combined: bool = false,
/// Resources in the declaration (array elements).
/// A global struct of resources: its resources' globals (null:
/// unused) at offsets within the struct's bindings (`count` of them).
members: []const struct { global: ?u32, offset: u32 } = &.{},
count: u32 = 1,
};
@ -512,8 +521,15 @@ pub const Module = struct {
/// Descriptor declarations in declaration order.
binding_decls: std.ArrayList(BindingDecl) = .empty,
vk: VkOptions = .{},
/// A global struct holds resources (dxc's SPIR-V then numbers array
/// elements' bindings separately, as with -fspv-flatten-resource-arrays).
resource_structs: bool = false,
/// -enable-16bit-types: half and 16-bit integers are native types.
native_16bit: bool = false,
/// -Zpr: matrices that are structured buffer elements themselves
/// (not fields, which carry their own orientation) are row_major.
/// DXIL only: dxc's SPIR-V keeps those column_major.
row_major: bool = false,
/// Root signatures: version 1.0 or 1.1 (-force-rootsig-ver), and
/// -Qstrip_rootsignature.
rootsig_version: enum { v1_0, v1_1 } = .v1_1,

View File

@ -160,7 +160,9 @@ fn structAlign(t: *const TypeTable, info: *const types.StructInfo, rules: Rules)
.dx_legacy => return 16,
else => {
var al: u32 = if (rules == .vk_relaxed or rules == .gl_std140) 16 else 1;
for (info.fields.items) |f| al = @max(al, try alignOf(t, f.type, f.row_major, rules));
for (info.fields.items) |f| if (!isOpaque(t, f.type)) {
al = @max(al, try alignOf(t, f.type, f.row_major, rules));
};
return al;
},
}
@ -200,6 +202,11 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules
if (packed_end) |pe| off = @max(off, pe);
var end: u32 = off;
for (info.fields.items[first..], out[first..]) |f, *o| {
// (Resources in structs take no space in buffers.)
if (isOpaque(t, f.type)) {
o.* = off;
continue;
}
if (f.pack_offset) |po| {
o.* = po;
continue;
@ -250,9 +257,19 @@ pub fn componentOffset(a: Allocator, t: *const TypeTable, ty: TypeId, row_major:
}
}
/// Resources (and arrays of them): no data.
pub fn isOpaque(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource, .sampler => true,
.array => |a| isOpaque(t, a.elem),
else => false,
};
}
pub fn flatCount(t: *const TypeTable, ty: TypeId) Error!u32 {
return switch (t.get(ty)) {
.scalar, .@"enum" => 1,
.resource, .sampler => 0,
.vector => |v| v.len,
.matrix => |m| @as(u32, m.rows) * m.cols,
.array => |a| a.len * try flatCount(t, a.elem),

View File

@ -7,6 +7,7 @@ const std = @import("std");
const Allocator = std.mem.Allocator;
const ast = @import("../front/ast.zig");
const ir = @import("ir.zig");
const layout = @import("layout.zig");
const semamod = @import("../sema/sema.zig");
const types = @import("../sema/types.zig");
const Bitfield = types.Bitfield;
@ -91,6 +92,9 @@ const Lowerer = struct {
funcs: std.AutoHashMapUnmanaged(*const semamod.Function, u32) = .empty,
pending: std.ArrayList(*const semamod.Function) = .empty,
globals: std.AutoHashMapUnmanaged(*const Variable, u32) = .empty,
/// Resources inside global structs (`g.tex`): a global each, by
/// variable and member path.
leaf_globals: std.StringHashMapUnmanaged(u32) = .empty,
/// cbuffer globals by declaration (0: `$Globals`), and where each
/// member variable lives.
cbuffers: std.AutoHashMapUnmanaged(usize, u32) = .empty,
@ -230,6 +234,40 @@ const Lowerer = struct {
var globals_done = false;
for (l.s.global_order.items) |gd| switch (gd) {
.variable => |v| {
// A struct of resources: a binding per resource (used or
// not), the first taking the struct's register.
if (v.storage == .global_uniform and holdsResources(&l.s.types, v.type)) {
l.m.resource_structs = true;
if (l.s.opts.spirv) {
if (structHoldsBuffer(&l.s.types, v.type)) {
l.unsupported(v.loc, "global structures containing buffers are not supported", .{});
return error.Unsupported;
}
if (layout.flatCount(&l.s.types, v.type) catch 0 > 0) {
l.unsupported(v.loc, "global structures containing both resources and non-resources are not supported", .{});
return error.Unsupported;
}
}
var leaves: std.ArrayList(LeafPath) = .empty;
try l.resourceLeaves(v.type, &.{}, &leaves);
// One range for the whole struct (as dxc): each
// resource at its offset.
var bd: ir.BindingDecl = if (v.decl) |d| try l.bindingDecl(d.semantics, d.attrs, null) else .{ .global = null };
bd.global = null;
var members: std.ArrayList(@typeInfo(@FieldType(ir.BindingDecl, "members")).pointer.child) = .empty;
var offset: u32 = 0;
for (leaves.items) |leaf| {
try members.append(l.arena, .{ .global = l.leaf_globals.get(try l.leafName(v, leaf.path)), .offset = offset });
var n: u32 = 1;
var at = leaf.ty;
while (l.s.types.get(at) == .array) : (at = l.s.types.get(at).array.elem) n *= @max(1, l.s.types.get(at).array.len);
offset += n;
}
bd.count = @max(1, offset);
bd.members = members.items;
try l.m.binding_decls.append(l.arena, bd);
if (layout.flatCount(&l.s.types, v.type) catch 0 == 0) continue;
}
if (!isObject(&l.s.types, v.type)) {
if (v.storage != .global_uniform or globals_done or l.isPushConstantStruct(v) or l.isSpecConstant(v)) continue;
globals_done = true;
@ -355,14 +393,17 @@ const Lowerer = struct {
for (f.params, 0..) |p, k| {
if (l.s.types.get(p.type) == .stream) continue;
const sem = if (k < f.decl.params.len) semanticOf(f.decl.params[k].semantics) else null;
try params.append(l.arena, .{ .name = p.name, .ty = l.irType(p.type), .by_ref = p.dir != .in, .dir = switch (p.dir) {
try params.append(l.arena, .{ .name = p.name, .ty = l.irType(p.type), .by_ref = p.dir != .in or p.groupshared, .groupshared = p.groupshared, .dir = switch (p.dir) {
.in => .in,
.out => .out,
.inout => .inout,
}, .semantic = sem, .sema_ty = p.type });
}
const order: u32 = @intCast(std.mem.indexOfScalar(*semamod.Function, l.s.all_functions.items, @constCast(f)) orelse std.math.maxInt(u32));
const i = try l.m.addFunction(.{ .name = f.name, .params = params.items, .ret = f.ret, .entry = l.cur_entry, .ret_semantic = semanticOf(f.decl.ret_semantics), .decl_order = order });
const no_inline = !isMethod(f) and f.template_args.len == 0 and for (f.decl.attrs) |a| {
if (std.mem.eql(u8, a.name, "noinline")) break true;
} else false;
const i = try l.m.addFunction(.{ .name = f.name, .params = params.items, .ret = f.ret, .entry = l.cur_entry, .ret_semantic = semanticOf(f.decl.ret_semantics), .decl_order = order, .no_inline = no_inline });
try l.funcs.put(l.arena, f, i);
try l.pending.append(l.arena, f);
return i;
@ -404,14 +445,14 @@ const Lowerer = struct {
if (l.s.types.get(p.type) == .stream) continue;
const pty = l.irType(p.type);
const mq = if (i < f.decl.params.len) f.decl.params[i].quals else ast.Qualifiers{};
const space: ir.Space = if (mq.vertices or mq.indices or mq.primitives) .mesh else if (p.dir != .in) .function else .none;
const space: ir.Space = if (mq.vertices or mq.indices or mq.primitives) .mesh else if (p.groupshared) .groupshared else if (p.dir != .in) .function else .none;
const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = pty, .ptr = space });
ir_index += 1;
if (p.dir == .in and isSpirvPointer(&l.s.types, p.type)) {
if (i < f.param_vars.len) if (f.param_vars[i]) |v| try l.value_vars.put(l.arena, v, pv);
continue;
}
const storage = if (p.dir != .in) pv else blk: {
const storage = if (p.dir != .in or p.groupshared) pv else blk: {
const local = try l.b.add(.{ .op = .local_var, .ty = pty, .ptr = .function });
try l.b.store(local, pv);
break :blk local;
@ -670,10 +711,8 @@ const Lowerer = struct {
try l.vars.put(l.arena, variable, try l.b.add(.{ .op = .{ .global = gi }, .ty = glob.ty, .ptr = glob.space }));
return;
}
if (v.init == null and isObject(&l.s.types, variable.type) and !isRayQuery(&l.s.types, variable.type)) {
l.unsupported(d.loc, "uninitialized local resource '{s}' is not supported yet", .{variable.name});
return error.Unsupported;
}
// (A resource local is an alias of what is stored into it:
// reading it before that is reported by the backends.)
if (isSpirvPointer(&l.s.types, variable.type)) {
const init_e = v.init orelse {
l.unsupported(d.loc, "uninitialized inline SPIR-V pointer '{s}' is not supported", .{variable.name});
@ -854,7 +893,8 @@ const Lowerer = struct {
const t = l.types();
const ty = l.b.f.inst(v).ty;
switch (t.get(ty)) {
.scalar, .@"enum" => try out.append(l.arena, v),
// (Resources in structs are leaves of their own.)
.scalar, .@"enum", .resource, .sampler => try out.append(l.arena, v),
.vector, .matrix => for (0..t.componentCount(ty).?) |k| try out.append(l.arena, try l.component(v, @intCast(k))),
.array => |a| for (0..a.len) |i| try l.flatten(try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = a.elem }), out),
.@"struct" => |st| for (st.fields.items, 0..) |f, i| {
@ -874,6 +914,10 @@ const Lowerer = struct {
fn fromFlat(l: *Lowerer, ty: TypeId, comps: []const Ref, next: *usize) Error!Ref {
const t = l.types();
switch (t.get(ty)) {
.resource, .sampler => {
defer next.* += 1;
return comps[next.*];
},
.scalar, .@"enum" => {
defer next.* += 1;
return l.convert(comps[next.*], ty);
@ -940,9 +984,10 @@ const Lowerer = struct {
},
.variable => |v| {
if (l.value_vars.get(v)) |val| return val;
if (v.storage == .global_uniform and holdsResources(&l.s.types, v.type)) return l.uniformValue(v, &.{}, v.type);
if (l.isSpecConstant(v)) return l.specConstant(v);
// Integer `static const` scalars are constants.
if (v.storage == .constant and v.init != null and l.s.types.get(v.type) == .scalar and !l.s.types.get(v.type).scalar.isFloat()) {
if (v.storage == .constant and v.init != null and isIntConstantType(&l.s.types, v.type)) {
if (l.s.evalVarInt(v)) |val| return l.b.constInt(try l.concrete(e.ty), val);
}
return l.b.load(try l.lvalue(e));
@ -994,6 +1039,7 @@ const Lowerer = struct {
},
.member => |m| return l.member(e, m.base, m.name),
.index => |x| {
if (l.uniformPath(e)) |up| return l.uniformValue(up.v, up.path, e.ty);
const bt = t.get(x.base.ty);
if (bt == .descriptor_heap) {
const idx = try l.converted(x.index, try t.scalar(.uint));
@ -1180,7 +1226,7 @@ const Lowerer = struct {
try flattenList(l.arena, e, &flat);
var comps: std.ArrayList(Ref) = .empty;
for (flat.items) |x| try l.flatten(try l.rvalue(x), &comps);
const need = l.types().componentCount(ty) orelse return l.fail(e, "this initializer list");
const need = flatLength(l.types(), ty) orelse return l.fail(e, "this initializer list");
if (comps.items.len < need) return l.fail(e, "this initializer list");
var next: usize = 0;
return l.fromFlat(ty, comps.items, &next);
@ -1210,11 +1256,12 @@ const Lowerer = struct {
return l.b.add(.{ .op = .{ .construct = parts }, .ty = try l.concrete(e.ty) });
},
.@"struct" => |info| {
if (l.uniformPath(e)) |up| return l.uniformValue(up.v, up.path, e.ty);
const r = l.s.resolution(e) orelse return l.fail(e, "this member");
// A static member through an object.
if (r == .variable) {
const v = r.variable;
if (v.storage == .constant and v.init != null and l.s.types.get(v.type) == .scalar and !l.s.types.get(v.type).scalar.isFloat()) {
if (v.storage == .constant and v.init != null and isIntConstantType(&l.s.types, v.type)) {
if (l.s.evalVarInt(v)) |val| return l.b.constInt(try l.concrete(e.ty), val);
}
return l.b.load(try l.variableLvalue(e, v));
@ -1413,7 +1460,11 @@ const Lowerer = struct {
for (args, f.params, 0..) |a, p, i| {
if (l.s.types.get(p.type) == .stream) continue;
n_vals += 1;
if (p.dir == .in) {
if (p.groupshared) {
// The caller's groupshared variable itself.
vals[i] = try l.lvalue(a);
temps[i] = .none;
} else if (p.dir == .in) {
vals[i] = try l.converted(a, p.type);
} else {
// Copy-in / copy-out through a temporary.
@ -1429,7 +1480,7 @@ const Lowerer = struct {
if (isMethod(f)) try packed_vals.insert(l.arena, 0, object orelse (if (l.this_ptr != .none) l.this_ptr else return error.Unsupported));
const res = try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = packed_vals.items } }, .ty = ret_ty });
for (args, f.params, 0..) |a, p, i| {
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue;
if (p.dir == .in or p.groupshared or l.s.types.get(p.type) == .stream) continue;
const back = try l.b.load(temps[i]);
try l.storeTo(a, try l.convert(back, a.ty));
}
@ -1476,6 +1527,22 @@ const Lowerer = struct {
l.mesh_payload = args[3].ty;
return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = TypeTable.void_type });
}
// SM 6.10 matrices: results go straight to the `out` /
// `ref` argument's storage; groupshared arrays by reference.
if (std.mem.startsWith(u8, name, "__builtin_LinAlg_")) {
const vals = try l.arena.alloc(Ref, args.len);
for (args, 0..) |a, i| {
const q = if (i < spec.params.len) spec.params[i].qual else .in;
const pt = it.params[i];
vals[i] = if (q != .in or l.s.types.get(a.ty) == .array)
try l.lvalue(a)
else if (pt == TypeTable.error_type or l.s.types.get(pt) == .resource)
try l.rvalue(a)
else
try l.converted(a, try l.concrete(pt));
}
return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = ret_ty });
}
// `out` parameters go through temporaries copied back
// afterwards; `ref` ones (atomic destinations) pass the
// storage itself.
@ -1507,6 +1574,120 @@ const Lowerer = struct {
}
/// Pointer to the storage `e` designates.
/// `g.a.b`, rooted at a global uniform struct holding resources: the
/// variable and the member indices.
fn uniformPath(l: *Lowerer, e: *ast.Expr) ?struct { v: *const Variable, path: []const u32 } {
switch (e.kind) {
.name => {
const r = l.s.resolution(e) orelse return null;
if (r != .variable) return null;
const v = r.variable;
if (v.storage != .global_uniform or !holdsResources(&l.s.types, v.type)) return null;
return .{ .v = v, .path = &.{} };
},
.member => |m| {
if (l.s.types.get(m.base.ty) != .@"struct") return null;
const base = l.uniformPath(m.base) orelse return null;
const r = l.s.resolution(e) orelse return null;
if (r != .field) return null;
const path = std.mem.concat(l.arena, u32, &.{ base.path, &.{r.field} }) catch return null;
return .{ .v = base.v, .path = path };
},
// An element of an array of structs holding resources (at a
// constant index).
.index => |x| {
const bt = l.s.types.get(x.base.ty);
if (bt != .array or !holdsResources(&l.s.types, x.base.ty) or isResourceLike(&l.s.types, bt.array.elem)) return null;
const base = l.uniformPath(x.base) orelse return null;
const k = l.s.evalInt(x.index) orelse return null;
if (k < 0 or k >= bt.array.len) return null;
const path = std.mem.concat(l.arena, u32, &.{ base.path, &.{@intCast(k)} }) catch return null;
return .{ .v = base.v, .path = path };
},
else => return null,
}
}
const LeafPath = struct { path: []const u32, ty: TypeId };
/// The resources of a struct type, in member order.
fn resourceLeaves(l: *Lowerer, ty: TypeId, prefix: []const u32, out: *std.ArrayList(LeafPath)) Error!void {
const t = l.types();
if (isResourceLike(t, ty) or layout.isOpaque(t, ty)) return out.append(l.arena, .{ .path = prefix, .ty = ty });
if (t.get(ty) == .array) {
for (0..t.get(ty).array.len) |k| try l.resourceLeaves(t.get(ty).array.elem, try std.mem.concat(l.arena, u32, &.{ prefix, &.{@intCast(k)} }), out);
return;
}
if (t.get(ty) != .@"struct") return;
for (t.get(ty).@"struct".fields.items, 0..) |f, k| {
if (!layout.isOpaque(t, f.type) and !holdsResources(t, f.type)) continue;
try l.resourceLeaves(f.type, try std.mem.concat(l.arena, u32, &.{ prefix, &.{@intCast(k)} }), out);
}
}
/// `g.inner.tex`.
/// (Array elements by flattened index, as dxc: `g[5].tex`.)
fn leafName(l: *Lowerer, v: *const Variable, path: []const u32) Error![]const u8 {
var name: std.ArrayList(u8) = .empty;
try name.appendSlice(l.arena, v.name);
var cur = v.type;
var flat: ?u32 = null;
for (path) |k| switch (l.s.types.get(cur)) {
.array => |arr| {
flat = (flat orelse 0) * arr.len + k;
cur = arr.elem;
},
.@"struct" => |st| {
if (flat) |fl| try name.print(l.arena, "[{d}]", .{fl});
flat = null;
const f = st.fields.items[k];
try name.print(l.arena, ".{s}", .{f.name});
cur = f.type;
},
else => {},
};
if (flat) |fl| try name.print(l.arena, "[{d}]", .{fl});
return name.items;
}
/// The global of a resource inside a global struct, named by its path
/// (`g.tex`) and bound like any other unbound resource.
fn leafGlobal(l: *Lowerer, v: *const Variable, path: []const u32, ty: TypeId) Error!Ref {
const name = try l.leafName(v, path);
const gop = try l.leaf_globals.getOrPut(l.arena, name);
if (!gop.found_existing) {
try l.m.globals.append(l.arena, .{ .name = name, .ty = ty, .space = .resource });
gop.value_ptr.* = @intCast(l.m.globals.items.len - 1);
}
return l.b.add(.{ .op = .{ .global = gop.value_ptr.* }, .ty = ty, .ptr = .resource });
}
/// The value at `path` in a global struct holding resources: its
/// resources from their globals, its data from $Globals.
fn uniformValue(l: *Lowerer, v: *const Variable, path: []const u32, ty: TypeId) Error!Ref {
const t = l.types();
if (layout.isOpaque(t, ty)) return l.b.load(try l.leafGlobal(v, path, ty));
if (holdsResources(t, ty)) {
if (t.get(ty) == .array) {
const arr = t.get(ty).array;
const parts = try l.arena.alloc(Ref, arr.len);
for (parts, 0..) |*p, k| p.* = try l.uniformValue(v, try std.mem.concat(l.arena, u32, &.{ path, &.{@intCast(k)} }), arr.elem);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
}
const st = t.get(ty).@"struct";
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items, 0..) |*p, f, k| p.* = try l.uniformValue(v, try std.mem.concat(l.arena, u32, &.{ path, &.{@intCast(k)} }), f.type);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
}
const cm = try l.cbufferMember(v);
const glob = l.m.globals.items[cm.global];
const base = try l.b.add(.{ .op = .{ .global = cm.global }, .ty = glob.ty, .ptr = .cbuffer });
const idx = try l.arena.alloc(Ref, path.len + 1);
idx[0] = try l.b.constInt(try t.scalar(.uint), cm.field);
for (path, idx[1..]) |k, *x| x.* = try l.b.constInt(try t.scalar(.uint), k);
return l.b.load(try l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = idx } }, .ty = ty, .ptr = .cbuffer }));
}
/// Storage of a variable that is not a local (locals are in `vars`).
fn variableLvalue(l: *Lowerer, e: *ast.Expr, v: *const Variable) Error!Ref {
const t = l.types();
@ -1543,6 +1724,8 @@ const Lowerer = struct {
fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
const t = l.types();
// A resource inside a global struct: its own global.
if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty);
switch (e.kind) {
.this => {
if (l.this_ptr == .none) return l.fail(e, "this expression");
@ -1604,6 +1787,25 @@ const Lowerer = struct {
};
}
/// Whether `e` designates part of an RW structured buffer element or a
/// groupshared variable: memory other threads may write.
fn isSharedMemory(l: *Lowerer, e: *const ast.Expr) bool {
const t = l.types();
var x = e;
while (true) switch (x.kind) {
.member => |m| x = m.base,
.index => |ix| {
if (t.get(ix.base.ty) == .resource) return t.get(ix.base.ty).resource.kind == .rw_structured_buffer;
x = ix.base;
},
.name => {
const r = l.s.resolution(x) orelse return false;
return r == .variable and r.variable.storage == .groupshared;
},
else => return false,
};
}
/// Pointer to the storage field holding bitfield `bf` of the struct
/// `ptr` points to.
fn bitStorage(l: *Lowerer, ptr: Ref, bf: Bitfield) Error!Ref {
@ -1680,6 +1882,22 @@ const Lowerer = struct {
.member => |m| if (t.get(m.base.ty) == .matrix) {
const mt = t.get(m.base.ty).matrix;
const ks = matrixSwizzle(l.arena, m.name, mt.cols) orelse return error.Unsupported;
if (l.isSharedMemory(m.base)) {
// Other threads may write the other elements: store
// only the named ones (as dxc).
const base_ptr = try l.lvalue(m.base);
const space = l.b.f.inst(base_ptr).ptr;
const row_ty = try t.vector(mt.elem, mt.cols);
const ec = try t.scalar(mt.elem);
for (ks, 0..) |k, i| {
const part = if (ks.len == 1) value else try l.component(value, @intCast(i));
const r = try l.b.constInt(try t.scalar(.uint), k / mt.cols);
const c = try l.b.constInt(try t.scalar(.uint), k % mt.cols);
const row = try l.b.add(.{ .op = .{ .access = .{ .base = base_ptr, .indices = try l.arena.dupe(Ref, &.{r}) } }, .ty = row_ty, .ptr = space });
try l.b.store(try l.b.add(.{ .op = .{ .access = .{ .base = row, .indices = try l.arena.dupe(Ref, &.{c}) } }, .ty = ec, .ptr = space }), part);
}
return;
}
var whole = try l.rvalue(m.base);
const row_ty = try t.vector(mt.elem, mt.cols);
for (ks, 0..) |k, i| {
@ -1705,6 +1923,17 @@ const Lowerer = struct {
}
return;
}
if (l.isSharedMemory(m.base)) {
// Store only the named components (as dxc).
const base_ptr = try l.lvalue(m.base);
const ec = try t.scalar(t.component(m.base.ty).?);
for (comps, 0..) |c, i| {
const part = if (comps.len == 1) value else try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(i) } }, .ty = ec });
const idx = try l.b.constInt(try t.scalar(.uint), c);
try l.b.store(try l.b.add(.{ .op = .{ .access = .{ .base = base_ptr, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = ec, .ptr = l.b.f.inst(base_ptr).ptr }), part);
}
return;
}
var whole = try l.rvalue(m.base);
const ec = try t.scalar(t.component(m.base.ty).?);
for (comps, 0..) |c, i| {
@ -1759,10 +1988,16 @@ const Lowerer = struct {
return r;
}
/// A parameter's (or the return value's) interpolation and matrix
/// orientation.
fn paramAttrs(l: *Lowerer, q: ast.Qualifiers, ty: *const ast.TypeRef) SigAttrs {
return .{ .interp = semamod.interpOf(q), .row_major = l.s.sig_row_major.get(ty) orelse q.row_major };
}
/// A parameter's (or, with the function's attributes, the return
/// value's) signature modifiers.
fn sigAttrs(l: *Lowerer, q: ast.Qualifiers, attrs: []const ast.Attribute) SigAttrs {
var a = paramAttrs(q);
fn sigAttrs(l: *Lowerer, q: ast.Qualifiers, attrs: []const ast.Attribute, ty: *const ast.TypeRef) SigAttrs {
var a = l.paramAttrs(q, ty);
a.vk_location = l.s.vkAttrInt(attrs, "vk::location");
a.vk_index = l.s.vkAttrInt(attrs, "vk::index");
for (attrs) |at| if (std.mem.eql(u8, at.name, "vk::builtin") and at.args.len == 1 and at.args[0].kind == .string_lit) {
@ -2061,7 +2296,7 @@ const Lowerer = struct {
const points = try l.arena.alloc(Ref, patch.count);
for (points, 0..) |*v, k| {
var next = first;
v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), @intCast(k), register and k == 0, &next, null, pd.name_loc);
v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), @intCast(k), register and k == 0, &next, null, pd.name_loc);
}
try l.b.store(local, try l.b.add(.{ .op = .{ .construct = points }, .ty = l.irType(pty) }));
}
@ -2133,16 +2368,16 @@ const Lowerer = struct {
args[i] = try l.b.load(locals[i]);
continue;
}
if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name));
if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), pd.name_loc, pd.name));
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
}
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = pci, .args = args } }, .ty = pcf.ret });
l.patch_io = true;
defer l.patch_io = false;
if (pcf.ret != TypeTable.void_type) try l.entryOutput(entry, pcf.ret, semanticOf(pcf.decl.ret_semantics), paramAttrs(pcf.decl.quals), ret, pcf.loc, "return value");
if (pcf.ret != TypeTable.void_type) try l.entryOutput(entry, pcf.ret, semanticOf(pcf.decl.ret_semantics), l.paramAttrs(pcf.decl.quals, pcf.decl.ret), ret, pcf.loc, "return value");
for (pcf.decl.params, pcf.params, 0..) |pd, p, i| {
if (p.dir == .in) continue;
try l.entryOutput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), try l.b.load(locals[i]), pd.name_loc, pd.name);
try l.entryOutput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), try l.b.load(locals[i]), pd.name_loc, pd.name);
}
l.b.terminate(.{ .ret = .none });
entry.patch_wrapper = wrapper;
@ -2201,12 +2436,12 @@ const Lowerer = struct {
.vertices => {
entry.mesh.max_vertices = arr.len;
var next: u32 = @intCast(entry.outputs.items.len);
try l.streamOut(&entry.outputs, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs), null, &next, 0, null, pd.name_loc);
try l.streamOut(&entry.outputs, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs, pd.type), null, &next, 0, null, pd.name_loc);
},
.primitives => {
entry.mesh.max_primitives = arr.len;
var next: u32 = @intCast(entry.patch_constants.items.len);
try l.streamOut(&entry.patch_constants, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs), null, &next, 0, null, pd.name_loc);
try l.streamOut(&entry.patch_constants, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs, pd.type), null, &next, 0, null, pd.name_loc);
},
.indices => {
entry.mesh.max_primitives = arr.len;
@ -2236,7 +2471,7 @@ const Lowerer = struct {
// Everything else a domain shader reads is per patch.
l.patch_io = true;
defer l.patch_io = false;
try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name));
try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), pd.name_loc, pd.name));
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
continue;
}
@ -2249,7 +2484,7 @@ const Lowerer = struct {
const verts = try l.arena.alloc(Ref, arr.len);
for (verts, 0..) |*v, vx| {
var next = first;
v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), @intCast(vx), vx == 0, &next, null, pd.name_loc);
v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), @intCast(vx), vx == 0, &next, null, pd.name_loc);
}
try l.b.store(locals[i], try l.b.add(.{ .op = .{ .construct = verts }, .ty = p.type }));
args[i] = try l.b.load(locals[i]);
@ -2265,7 +2500,7 @@ const Lowerer = struct {
continue;
}
if (p.dir != .out) {
const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name);
const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), pd.name_loc, pd.name);
try l.b.store(locals[i], v);
}
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
@ -2274,7 +2509,7 @@ const Lowerer = struct {
for (f.params, 0..) |p, i| if (l.s.types.get(p.type) != .stream) try call_args.append(l.arena, args[i]);
std.debug.assert(call_args.items.len == n_args);
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = call_args.items } }, .ty = f.ret });
if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), l.sigAttrs(f.decl.quals, f.decl.attrs), ret, f.loc, "return value");
if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), l.sigAttrs(f.decl.quals, f.decl.attrs, f.decl.ret), ret, f.loc, "return value");
for (f.decl.params, f.params, 0..) |pd, p, i| {
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue;
if (l.b.f.inst(locals[i]).ptr == .mesh) continue;
@ -2283,7 +2518,7 @@ const Lowerer = struct {
try l.b.store(ray_srcs[i], v);
continue;
}
try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), v, pd.name_loc, pd.name);
try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), v, pd.name_loc, pd.name);
}
l.b.terminate(.{ .ret = .none });
entry.wrapper = wrapper;
@ -2314,6 +2549,67 @@ pub fn saturatingInt(f: f64) i64 {
/// Non-static member functions take their object as a hidden first
/// parameter.
/// (dxc's SPIR-V supports textures and samplers in global structs, not
/// buffers.)
fn structHoldsBuffer(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource => |r| switch (r.kind) {
.buffer, .rw_buffer, .byte_address_buffer, .rw_byte_address_buffer, .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer, .constant_buffer, .texture_buffer => true,
else => false,
},
.array => |a| structHoldsBuffer(t, a.elem),
.@"struct" => |st| for (st.fields.items) |f| {
if (structHoldsBuffer(t, f.type)) break true;
} else false,
else => false,
};
}
fn isResourceLike(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource, .sampler => true,
else => false,
};
}
/// A struct or array with a resource in it.
fn holdsResources(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.array => |a| isResourceLike(t, a.elem) or holdsResources(t, a.elem),
.@"struct" => |st| for (st.fields.items) |f| {
if (isResourceLike(t, f.type) or holdsResources(t, f.type)) break true;
} else false,
else => false,
};
}
/// Leaves of an initializer list for `ty` (components, and resources).
fn flatLength(t: *const TypeTable, ty: TypeId) ?u32 {
return switch (t.get(ty)) {
.resource, .sampler => 1,
.array => |a| if (flatLength(t, a.elem)) |n| n * a.len else null,
.@"struct" => |st| blk: {
var n: u32 = 0;
for (st.fields.items, 0..) |f, i| {
if (f.bits) {
n += @intCast(st.bitfieldsIn(@intCast(i)).len);
} else n += flatLength(t, f.type) orelse break :blk null;
}
break :blk n;
},
else => t.componentCount(ty),
};
}
/// Integer (and enum) `static const` values are folded to constants.
fn isIntConstantType(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.scalar => |sc| !sc.isFloat(),
.@"enum" => true,
else => false,
};
}
/// `vk::SpirvOpaqueType<OpTypePointer, ...>` (WorkgroupSpirvPointer).
fn isSpirvPointer(t: *const TypeTable, ty: TypeId) bool {
return t.get(ty) == .spirv and t.get(ty).spirv.opcode == 32;
@ -2414,9 +2710,6 @@ pub fn isObject(t: *TypeTable, ty: TypeId) bool {
};
}
fn paramAttrs(q: ast.Qualifiers) Lowerer.SigAttrs {
return .{ .interp = semamod.interpOf(q), .row_major = q.row_major };
}
fn semanticOf(sems: []const ast.Semantic) ?[]const u8 {
for (sems) |sem| if (sem.kind == .semantic) return sem.values[0];

View File

@ -179,7 +179,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
}
/// `op` with every operand passed through `ctx.map`.
fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
return switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant => op,
.load => |p| .{ .load = ctx.map(p) },

500
src/ir/split_resources.zig Normal file
View File

@ -0,0 +1,500 @@
//! Resources inside structs, taken apart for SPIR-V (dxc gets there by
//! legalization: inlining and scalar replacement). After this pass no
//! struct value or local carries a resource: each resource member of a
//! local is a resource local of its own, each struct value has its
//! resources alongside, function parameters holding resources gain a
//! resource parameter per member, and functions returning resources
//! return the parameter or global they come from. The SPIR-V emitter
//! leaves resource members out of struct types.
const std = @import("std");
const Allocator = std.mem.Allocator;
const ir = @import("ir.zig");
const types = @import("../sema/types.zig");
const opt = @import("opt.zig");
const diag = @import("../diag.zig");
const Ref = ir.Ref;
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
pub const Error = Allocator.Error || error{Unsupported};
fn isOpaque(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource => |r| !std.mem.eql(u8, r.name, "RayQuery"),
.sampler => true,
.array => |a| isOpaque(t, a.elem),
else => false,
};
}
/// A struct (or array of structs) with a resource in it.
pub fn holdsResources(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.array => |a| holdsResources(t, a.elem),
.@"struct" => |st| for (st.fields.items) |f| {
if (isOpaque(t, f.type) or holdsResources(t, f.type)) break true;
} else false,
else => false,
};
}
/// The resource members (resources, or arrays of them) of `ty`, in order.
fn leafTypes(a: Allocator, t: *const TypeTable, ty: TypeId, out: *std.ArrayList(TypeId)) Allocator.Error!void {
if (isOpaque(t, ty)) return out.append(a, ty);
switch (t.get(ty)) {
.array => |arr| for (0..arr.len) |_| try leafTypes(a, t, arr.elem, out),
.@"struct" => |st| for (st.fields.items) |f| try leafTypes(a, t, f.type, out),
else => {},
}
}
/// An out / inout parameter of a resource (or array of them).
fn isRefResource(t: *const TypeTable, prm: ir.Param) bool {
return prm.by_ref and !prm.groupshared and prm.dir != .in and isOpaque(t, prm.ty);
}
fn leafCount(t: *const TypeTable, ty: TypeId) u32 {
if (isOpaque(t, ty)) return 1;
return switch (t.get(ty)) {
.array => |arr| arr.len * leafCount(t, arr.elem),
.@"struct" => |st| blk: {
var n: u32 = 0;
for (st.fields.items) |f| n += leafCount(t, f.type);
break :blk n;
},
else => 0,
};
}
/// Member / element `k`'s place among `ty`'s leaves, and its type.
fn member(t: *const TypeTable, ty: TypeId, k: u32) struct { start: u32, ty: TypeId } {
switch (t.get(ty)) {
.array => |arr| return .{ .start = k * leafCount(t, arr.elem), .ty = arr.elem },
.@"struct" => |st| {
var s: u32 = 0;
for (st.fields.items[0..k]) |f| s += leafCount(t, f.type);
return .{ .start = s, .ty = st.fields.items[k].type };
},
else => return .{ .start = 0, .ty = ty },
}
}
/// Where a returned resource comes from.
const Source = union(enum) { param: u32, global: u32 };
const FuncInfo = struct {
done: bool = false,
/// Original parameter index -> index of its first leaf parameter.
leaf_params: []?u32 = &.{},
/// Original parameter index -> new index (null: an out / inout
/// resource, now a local of the callee).
param_map: []?u32 = &.{},
/// Out / inout resources: the parameter bringing an inout one's value
/// in, and where the value going out comes from.
ref_in: []?u32 = &.{},
ref_out: []?Source = &.{},
/// The returned resources' origins (functions returning resources).
ret: ?[]const Source = null,
/// The function returned only resources and now returns nothing.
ret_void: bool = false,
};
const Pass = struct {
a: Allocator,
m: *ir.Module,
t: *TypeTable,
diags: *diag.Diagnostics,
infos: []FuncInfo,
/// The current function's parameter index map.
cur_map: []?u32 = &.{},
fn fail(p: *Pass, comptime fmt: []const u8, args: anytype) Error {
p.diags.err(.none, "SPIR-V code generation: " ++ fmt ++ " is not supported yet", args);
return error.Unsupported;
}
/// Adds a leaf parameter per resource member of each parameter that
/// holds resources (by value or by reference).
fn signature(p: *Pass, fi: u32) Allocator.Error!void {
const f = p.m.functions.items[fi];
const info = &p.infos[fi];
const np_old = f.params.len;
info.leaf_params = try p.a.alloc(?u32, np_old);
info.param_map = try p.a.alloc(?u32, np_old);
info.ref_in = try p.a.alloc(?u32, np_old);
info.ref_out = try p.a.alloc(?Source, np_old);
@memset(info.leaf_params, null);
@memset(info.ref_in, null);
@memset(info.ref_out, null);
var params: std.ArrayList(ir.Param) = .empty;
// Out / inout resources leave the parameter list (a pointer to a
// resource cannot be passed).
for (f.params, 0..) |prm, k| {
if (isRefResource(p.t, prm)) {
info.param_map[k] = null;
continue;
}
info.param_map[k] = @intCast(params.items.len);
try params.append(p.a, prm);
}
for (f.params, 0..) |prm, k| {
if (isRefResource(p.t, prm)) {
if (prm.dir == .inout) {
info.ref_in[k] = @intCast(params.items.len);
try params.append(p.a, .{ .name = prm.name, .ty = prm.ty, .by_ref = false, .sema_ty = prm.ty });
}
continue;
}
if (!holdsResources(p.t, prm.ty)) continue;
info.leaf_params[k] = @intCast(params.items.len);
var leaves: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, prm.ty, &leaves);
for (leaves.items, 0..) |lt, n| try params.append(p.a, .{ .name = try std.fmt.allocPrint(p.a, "{s}.{d}", .{ prm.name, n }), .ty = lt, .by_ref = false, .sema_ty = lt });
}
f.params = params.items;
}
fn add(f: *ir.Function, a: Allocator, inst: ir.Inst) Allocator.Error!Ref {
try f.insts.append(a, inst);
return @enumFromInt(f.insts.items.len - 1);
}
fn leafParam(p: *Pass, f: *ir.Function, r: Ref, old: ir.Inst, ty: TypeId, pi: u32, first: u32, out: *std.ArrayList(Ref), leaves: *std.AutoHashMapUnmanaged(Ref, []const Ref), pleaves: *std.AutoHashMapUnmanaged(Ref, []const Ref)) Error!void {
f.insts.items[r.index()].op = .{ .param = p.cur_map[pi].? };
try out.append(p.a, r);
var lts: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, ty, &lts);
const vals = try p.a.alloc(Ref, lts.items.len);
for (vals, lts.items, 0..) |*v, lt, n| {
v.* = try add(f, p.a, .{ .op = .{ .param = first + @as(u32, @intCast(n)) }, .ty = lt });
try out.append(p.a, v.*);
}
if (old.ptr != .none) {
// By reference (`this`, inout): locals of its own, initialized
// from the leaf parameters.
const ptrs = try p.a.alloc(Ref, vals.len);
for (ptrs, vals, lts.items) |*pp, v, lt| {
pp.* = try add(f, p.a, .{ .op = .local_var, .ty = lt, .ptr = .function });
try out.append(p.a, pp.*);
try out.append(p.a, try add(f, p.a, .{ .op = .{ .store = .{ .ptr = pp.*, .value = v } }, .ty = TypeTable.void_type }));
}
try pleaves.put(p.a, r, ptrs);
} else try leaves.put(p.a, r, vals);
}
fn function(p: *Pass, fi: u32) Error!void {
const info = &p.infos[fi];
if (info.done) return;
info.done = true;
const f = p.m.functions.items[fi];
// Callees first: their returns may be resources.
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
p.cur_map = info.param_map;
var leaves: std.AutoHashMapUnmanaged(Ref, []const Ref) = .empty;
var pleaves: std.AutoHashMapUnmanaged(Ref, []const Ref) = .empty;
var repl: std.AutoHashMapUnmanaged(Ref, Ref) = .empty;
const Map = struct {
r: *std.AutoHashMapUnmanaged(Ref, Ref),
pub fn map(c: @This(), x: Ref) Ref {
return c.r.get(x) orelse x;
}
};
const mp: Map = .{ .r = &repl };
var rets: std.ArrayList([]const Ref) = .empty;
var ref_locals: std.AutoHashMapUnmanaged(u32, Ref) = .empty;
var ref_init: std.AutoHashMapUnmanaged(Ref, void) = .empty;
const n_old = f.insts.items.len;
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
for (f.blocks.items, 0..) |*blk, bi| {
var out: std.ArrayList(Ref) = .empty;
for (blk.insts.items) |r| {
const old = f.insts.items[r.index()];
const op = try opt.mapOp(p.a, old.op, mp);
f.insts.items[r.index()].op = op;
const ty = old.ty;
// Kept parameters move to their new index.
if (op == .param and op.param < info.param_map.len) if (info.param_map[op.param]) |np| if (info.leaf_params[op.param] == null) {
f.insts.items[r.index()].op = .{ .param = np };
};
switch (op) {
// An out / inout resource: a local of its own (an
// inout one starts as the value passed in).
.param => |pi| {
if (pi < info.leaf_params.len) if (info.leaf_params[pi]) |first| {
try p.leafParam(f, r, old, ty, pi, first, &out, &leaves, &pleaves);
continue;
};
if (!(pi < info.param_map.len and info.param_map[pi] == null)) {
try out.append(p.a, r);
continue;
}
f.insts.items[r.index()].op = .local_var;
f.insts.items[r.index()].ptr = .function;
try out.append(p.a, r);
try ref_locals.put(p.a, pi, r);
if (info.ref_in[pi]) |in| {
const v = try add(f, p.a, .{ .op = .{ .param = in }, .ty = ty });
try out.append(p.a, v);
const st = try add(f, p.a, .{ .op = .{ .store = .{ .ptr = r, .value = v } }, .ty = TypeTable.void_type });
try out.append(p.a, st);
try ref_init.put(p.a, st, {});
}
continue;
},
.local_var => if (holdsResources(p.t, ty)) {
try out.append(p.a, r);
var lts: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, ty, &lts);
const ptrs = try p.a.alloc(Ref, lts.items.len);
for (ptrs, lts.items) |*pp, lt| {
pp.* = try add(f, p.a, .{ .op = .local_var, .ty = lt, .ptr = .function });
try out.append(p.a, pp.*);
}
try pleaves.put(p.a, r, ptrs);
continue;
},
.access => |acc| if (pleaves.get(acc.base)) |base_leaves| {
var cur = f.insts.items[acc.base.index()].ty;
var start: u32 = 0;
for (acc.indices) |x| {
if (!holdsResources(p.t, cur)) break;
const xi = f.insts.items[x.index()];
if (xi.op != .constant) return p.fail("dynamically indexing an array of structs holding resources", .{});
const mb = member(p.t, cur, @intCast(xi.op.constant.int));
start += mb.start;
cur = mb.ty;
}
if (isOpaque(p.t, cur) and cur == ty) {
// A resource member: its own local.
try repl.put(p.a, r, base_leaves[start]);
continue;
}
try out.append(p.a, r);
if (holdsResources(p.t, ty)) try pleaves.put(p.a, r, base_leaves[start..][0..leafCount(p.t, ty)]);
continue;
},
.load => |ptr| if (pleaves.get(ptr)) |pl| {
try out.append(p.a, r);
const vals = try p.a.alloc(Ref, pl.len);
for (vals, pl) |*v, pp| {
v.* = try add(f, p.a, .{ .op = .{ .load = pp }, .ty = f.insts.items[pp.index()].ty });
try out.append(p.a, v.*);
}
try leaves.put(p.a, r, vals);
continue;
},
.store => |st| if (pleaves.get(st.ptr)) |pl| {
try out.append(p.a, r);
const vals = leaves.get(st.value) orelse return p.fail("storing this value holding resources", .{});
for (pl, vals) |pp, v| try out.append(p.a, try add(f, p.a, .{ .op = .{ .store = .{ .ptr = pp, .value = v } }, .ty = TypeTable.void_type }));
continue;
},
.construct => |parts| if (holdsResources(p.t, ty)) {
try out.append(p.a, r);
var vals: std.ArrayList(Ref) = .empty;
for (parts) |x| {
const xt = f.insts.items[x.index()].ty;
if (isOpaque(p.t, xt)) {
try vals.append(p.a, x);
} else if (holdsResources(p.t, xt)) {
try vals.appendSlice(p.a, leaves.get(x) orelse return p.fail("this value holding resources", .{}));
}
}
try leaves.put(p.a, r, vals.items);
continue;
},
.extract => |x| if (leaves.get(x.agg)) |vals| {
const mb = member(p.t, f.insts.items[x.agg.index()].ty, x.index);
if (isOpaque(p.t, ty)) {
try repl.put(p.a, r, vals[mb.start]);
continue;
}
try out.append(p.a, r);
if (holdsResources(p.t, ty)) try leaves.put(p.a, r, vals[mb.start..][0..leafCount(p.t, ty)]);
continue;
},
.insert => |x| if (holdsResources(p.t, ty)) {
try out.append(p.a, r);
const whole = leaves.get(x.agg) orelse return p.fail("this value holding resources", .{});
const vals = try p.a.dupe(Ref, whole);
const mb = member(p.t, ty, x.index);
const vt = f.insts.items[x.value.index()].ty;
if (isOpaque(p.t, vt)) {
vals[mb.start] = x.value;
} else if (holdsResources(p.t, vt)) {
const part = leaves.get(x.value) orelse return p.fail("this value holding resources", .{});
@memcpy(vals[mb.start..][0..part.len], part);
}
try leaves.put(p.a, r, vals);
continue;
},
.select => |x| if (holdsResources(p.t, ty) or isOpaque(p.t, ty)) {
_ = x;
return p.fail("selecting between values holding resources", .{});
},
.call => |c| {
const ci = &p.infos[c.func];
var args: std.ArrayList(Ref) = .empty;
for (c.args, 0..) |arg, k| if (k >= ci.param_map.len or ci.param_map[k] != null) try args.append(p.a, arg);
for (c.args, 0..) |arg, k| {
if (k < ci.ref_in.len) if (ci.ref_in[k] != null) {
// An inout resource's value goes in.
const v = try add(f, p.a, .{ .op = .{ .load = arg }, .ty = f.insts.items[arg.index()].ty });
try out.append(p.a, v);
try args.append(p.a, v);
continue;
};
if (k >= ci.leaf_params.len or ci.leaf_params[k] == null) continue;
if (leaves.get(arg)) |vals| {
try args.appendSlice(p.a, vals);
} else if (pleaves.get(arg)) |pl| {
for (pl) |pp| {
const v = try add(f, p.a, .{ .op = .{ .load = pp }, .ty = f.insts.items[pp.index()].ty });
try out.append(p.a, v);
try args.append(p.a, v);
}
} else return p.fail("passing this value holding resources to a function", .{});
}
f.insts.items[r.index()].op = .{ .call = .{ .func = c.func, .args = args.items } };
if (ci.ret_void) f.insts.items[r.index()].ty = TypeTable.void_type;
try out.append(p.a, r);
// Out / inout resources come back: the argument's
// storage gets the parameter or global they are.
for (c.args, 0..) |arg, k| {
if (k >= ci.ref_out.len) continue;
const src = ci.ref_out[k] orelse continue;
const at = f.insts.items[arg.index()].ty;
const v = switch (src) {
.param => |pi| args.items[pi],
.global => |g| blk: {
const gp = try add(f, p.a, .{ .op = .{ .global = g }, .ty = at, .ptr = .resource });
try out.append(p.a, gp);
const l = try add(f, p.a, .{ .op = .{ .load = gp }, .ty = at });
try out.append(p.a, l);
break :blk l;
},
};
try out.append(p.a, try add(f, p.a, .{ .op = .{ .store = .{ .ptr = arg, .value = v } }, .ty = TypeTable.void_type }));
}
// What the callee returns: its arguments or
// globals.
if (ci.ret) |srcs| {
const vals = try p.a.alloc(Ref, srcs.len);
var lts: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, ty, &lts);
for (vals, srcs, lts.items) |*v, src, lt| v.* = switch (src) {
.param => |pi| args.items[pi],
.global => |g| blk: {
const gp = try add(f, p.a, .{ .op = .{ .global = g }, .ty = lt, .ptr = .resource });
try out.append(p.a, gp);
const l = try add(f, p.a, .{ .op = .{ .load = gp }, .ty = lt });
try out.append(p.a, l);
break :blk l;
},
};
if (isOpaque(p.t, ty)) try repl.put(p.a, r, vals[0]) else try leaves.put(p.a, r, vals);
}
continue;
},
else => {},
}
try out.append(p.a, r);
}
blk.insts = out;
// The terminator's operand too.
switch (blk.term) {
.ret => |v| if (v != .none) {
const mv = mp.map(v);
blk.term = .{ .ret = mv };
if (ret_holds) {
if (isOpaque(p.t, f.ret)) {
try rets.append(p.a, try p.a.dupe(Ref, &.{mv}));
blk.term = .{ .ret = .none };
} else try rets.append(p.a, leaves.get(mv) orelse return p.fail("returning this value holding resources", .{}));
}
},
.cond_br => |cb| blk.term = .{ .cond_br = .{ .cond = mp.map(cb.cond), .then = cb.then, .@"else" = cb.@"else" } },
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
else => {},
}
_ = bi;
}
_ = n_old;
// What each out / inout resource holds when the function returns:
// every store into it (other than the incoming value) the same
// parameter or global.
var it = ref_locals.iterator();
while (it.next()) |kv| {
var src: ?Source = if (info.ref_in[kv.key_ptr.*]) |in| .{ .param = in } else null;
var seen = false;
for (f.insts.items, 0..) |inst, ii| {
if (inst.op != .store or inst.op.store.ptr != kv.value_ptr.*) continue;
if (ref_init.contains(@enumFromInt(ii))) continue;
const here = p.trace(f, inst.op.store.value) orelse return p.fail("passing out a resource that is not a parameter or global", .{});
if (seen and !std.meta.eql(src.?, here)) return p.fail("passing out different resources from one function", .{});
src = here;
seen = true;
}
info.ref_out[kv.key_ptr.*] = src;
}
if (ret_holds) {
var srcs: ?[]Source = null;
for (rets.items) |vals| {
const here = try p.a.alloc(Source, vals.len);
for (here, vals) |*s, v| s.* = p.trace(f, v) orelse return p.fail("returning a resource that is not a parameter or global", .{});
if (srcs) |prev| {
for (prev, here) |x, y| if (!std.meta.eql(x, y)) return p.fail("returning different resources from one function", .{});
} else srcs = here;
}
info.ret = srcs orelse return p.fail("a function returning resources with no return", .{});
if (isOpaque(p.t, f.ret)) {
info.ret_void = true;
f.ret = TypeTable.void_type;
}
}
}
/// The parameter or global a resource value comes from.
fn trace(p: *Pass, f: *const ir.Function, v0: Ref) ?Source {
var v = v0;
var steps: u32 = 0;
while (steps < 64) : (steps += 1) {
const inst = f.insts.items[v.index()];
switch (inst.op) {
.load => |x| v = x,
.param => |pi| return .{ .param = pi },
.global => |g| return .{ .global = g },
// A resource local: what is stored into it.
.local_var => v = for (f.insts.items) |i| {
if (i.op == .store and i.op.store.ptr == v) break i.op.store.value;
} else return null,
else => return null,
}
}
_ = p;
return null;
}
};
/// Splits every function's resource-holding aggregates (SPIR-V only).
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
var any = false;
for (m.functions.items) |f| {
for (f.params) |prm| if (holdsResources(m.types, prm.ty) or isRefResource(m.types, prm)) {
any = true;
};
if (holdsResources(m.types, f.ret) or isOpaque(m.types, f.ret)) any = true;
for (f.insts.items) |inst| if (holdsResources(m.types, inst.ty)) {
any = true;
};
}
if (!any) return;
var p: Pass = .{ .a = a, .m = m, .t = m.types, .diags = diags, .infos = try a.alloc(FuncInfo, m.functions.items.len) };
@memset(p.infos, .{});
for (0..m.functions.items.len) |fi| try p.signature(@intCast(fi));
for (0..m.functions.items.len) |fi| try p.function(@intCast(fi));
}

156
src/job.zig Normal file
View File

@ -0,0 +1,156 @@
//! `--job=<job.json>`: compile every shader a job file lists in one
//! process, on several threads. Starting a process costs more than
//! compiling most shaders, so a build with many shaders is much faster
//! this way than with one zdxc run per shader.
//!
//! The job file:
//!
//! {
//! "threads": 8,
//! "args": ["-HV", "2021"],
//! "jobs": [
//! { "args": ["-T", "cs_6_0", "a.hlsl", "-Fo", "a.dxo"] },
//! { "args": ["-T", "ps_6_0", "-E", "PS", "b.hlsl", "-Fo", "b.dxo"] }
//! ]
//! }
//!
//! Each job is a dxc command line. The top-level `args`, then any other
//! options given next to `--job`, come before every job's own. `threads`
//! defaults to the number of CPUs. Paths are relative to the current
//! directory, as on the command line. Each job's output and diagnostics
//! are printed in job order; the exit code is 0 when every job succeeds,
//! else 1 if any job failed on its command line or I/O, else 5.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
/// Compiles one job: `args` is a full command line (argv[0] first). It
/// writes to `stdout` / `stderr` and returns the exit code.
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8;
const JobFile = struct {
threads: ?u32 = null,
args: []const []const u8 = &.{},
jobs: []const struct { args: []const []const u8 },
};
/// The index of `--job=<file>` in `argv`, if any.
pub fn find(argv: []const [:0]const u8) ?usize {
for (argv[1..], 1..) |a, i| if (std.mem.startsWith(u8, a, "--job=")) return i;
return null;
}
/// Runs the job file `argv[at]` names; the other arguments apply to every
/// job. Returns the process exit code.
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const path = argv[at]["--job=".len..];
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 30)) catch |e| {
try stderr.print("zdxc: error: cannot read job file '{s}': {s}\n", .{ path, @errorName(e) });
return 1;
};
var scanner = std.json.Scanner.initCompleteInput(arena, text);
var diag: std.json.Diagnostics = .{};
scanner.enableDiagnostics(&diag);
const file = std.json.parseFromTokenSourceLeaky(JobFile, arena, &scanner, .{}) catch |e| {
try stderr.print("zdxc: error: {s}:{d}:{d}: invalid job file: {s}\n", .{ path, diag.getLine(), diag.getColumn(), @errorName(e) });
return 1;
};
// argv[0], the file's common args, the command line's, then the job's.
var common: std.ArrayList([:0]const u8) = .empty;
try common.append(arena, argv[0]);
for (file.args) |a| try common.append(arena, try arena.dupeSentinel(u8, a, 0));
for (argv[1..], 1..) |a, i| if (i != at) try common.append(arena, a);
const jobs = try arena.alloc([]const [:0]const u8, file.jobs.len);
for (jobs, file.jobs) |*j, fj| {
const full = try arena.alloc([:0]const u8, common.items.len + fj.args.len);
@memcpy(full[0..common.items.len], common.items);
for (full[common.items.len..], fj.args) |*d, a| d.* = try arena.dupeSentinel(u8, a, 0);
j.* = full;
}
var b: Batch = .{ .io = io, .jobs = jobs, .results = try arena.alloc(Result, jobs.len), .compile = compile, .stdout = stdout, .stderr = stderr };
@memset(b.results, .{});
const cpus: u32 = @intCast(std.Thread.getCpuCount() catch 1);
const nthreads = @max(1, @min(file.threads orelse cpus, jobs.len));
// The calling thread is one of the workers.
const threads = try arena.alloc(std.Thread, nthreads - 1);
var spawned: usize = 0;
for (threads) |*t| {
t.* = std.Thread.spawn(.{}, Batch.work, .{&b}) catch break;
spawned += 1;
}
b.work();
for (threads[0..spawned]) |t| t.join();
var failed: usize = 0;
var code: u8 = 0;
for (b.results) |r| if (r.code != 0) {
failed += 1;
if (code != 1) code = r.code;
};
if (failed > 0) try stderr.print("zdxc: {d} of {d} jobs failed\n", .{ failed, jobs.len });
return code;
}
const Result = struct {
done: bool = false,
code: u8 = 0,
out: []u8 = &.{},
err: []u8 = &.{},
};
const Batch = struct {
io: Io,
jobs: []const []const [:0]const u8,
results: []Result,
compile: CompileFn,
stdout: *Io.Writer,
stderr: *Io.Writer,
next: std.atomic.Value(usize) = .init(0),
/// Guards `results` and the writers; jobs are printed in order.
mutex: Io.Mutex = .init,
printed: usize = 0,
fn work(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
while (true) {
const i = b.next.fetchAdd(1, .monotonic);
if (i >= b.jobs.len) return;
_ = arena.reset(.retain_capacity);
const a = arena.allocator();
var out: Io.Writer.Allocating = .init(a);
var err: Io.Writer.Allocating = .init(a);
const code = b.compile(b.io, a, b.jobs[i], &out.writer, &err.writer);
// The arena is reused for the next job: keep the output.
b.finish(i, .{
.done = true,
.code = code,
.out = gpa.dupe(u8, out.written()) catch &.{},
.err = gpa.dupe(u8, err.written()) catch &.{},
});
}
}
/// Records job `i` and prints every finished job not yet printed, in
/// order.
fn finish(b: *Batch, i: usize, r: Result) void {
b.mutex.lockUncancelable(b.io);
defer b.mutex.unlock(b.io);
b.results[i] = r;
while (b.printed < b.results.len and b.results[b.printed].done) : (b.printed += 1) {
const p = &b.results[b.printed];
b.stdout.writeAll(p.out) catch {};
b.stderr.writeAll(p.err) catch {};
std.heap.smp_allocator.free(p.out);
std.heap.smp_allocator.free(p.err);
p.out = &.{};
p.err = &.{};
}
b.stdout.flush() catch {};
b.stderr.flush() catch {};
}
};

View File

@ -6,6 +6,7 @@ const container = zdxc.dxil.container;
const front = zdxc.front;
const options = zdxc.options;
const job = @import("job.zig");
const Options = struct {
profile: ?[]const u8 = null,
@ -18,6 +19,8 @@ const Options = struct {
preprocess: bool = false,
pp_output: ?[]const u8 = null,
enable_16bit: bool = false,
row_major: bool = false,
col_major: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
rootsig_ver: ?[]const u8 = null,
strip_rootsig: bool = false,
@ -43,6 +46,8 @@ const Options = struct {
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
/// Accepted options with no effect yet, reported once each.
ignored: std.ArrayList([]const u8) = .empty,
/// `--job=<file>` (handled before run; here only inside a job file).
job: ?[]const u8 = null,
};
const Cli = struct {
@ -60,15 +65,22 @@ pub fn main(init: std.process.Init) !u8 {
const arena = init.arena.allocator();
const io = init.io;
var stderr_buf: [1024]u8 = undefined;
var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buf);
// Streaming, not positional: `2>> log` must append.
var stderr_writer: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buf);
var stdout_buf: [4096]u8 = undefined;
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
var stdout_writer: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf);
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
defer stderr_writer.interface.flush() catch {};
const args = try init.minimal.args.toSlice(arena);
if (job.find(args)) |at| {
const code = try job.run(io, arena, args, at, compileJob, &stdout_writer.interface, &stderr_writer.interface);
try stdout_writer.interface.flush();
return code;
}
// Exit codes follow dxc: 1 for command-line and I/O errors, 5 when the
// compilation reports errors.
run(cli, arena, try init.minimal.args.toSlice(arena), &stdout_writer.interface) catch |err| switch (err) {
run(cli, arena, args, &stdout_writer.interface) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => return err,
@ -77,6 +89,20 @@ pub fn main(init: std.process.Init) !u8 {
return 0;
}
/// One job of a `--job` file: `run`, with its exit code.
fn compileJob(io: Io, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
const cli: Cli = .{ .io = io, .stderr = stderr };
run(cli, arena, args, stdout) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
return 1;
},
};
return 0;
}
/// Parse a dxc-style command line. Returns null when the command is
/// complete (`-help`, `--version`).
fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer) !?Options {
@ -103,6 +129,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
},
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.job => opts.job = a.value(),
.fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false,
},
@ -132,6 +159,8 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
.spirv => opts.spirv = true,
.fspv_target_env_EQ => opts.target_env = v,
.enable_16bit_types => opts.enable_16bit = true,
.Zpr => opts.row_major = true,
.Zpc => opts.col_major = true,
.force_rootsig_ver, .force_rootsig_ver_ => opts.rootsig_ver = v,
.Qstrip_rootsignature => opts.strip_rootsig = true,
.rootsig_define => opts.rootsig_define = v,
@ -226,6 +255,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
},
}
}
if (opts.row_major and opts.col_major) return cli.fail("Cannot specify /Zpr and /Zpc together, use /? to get usage information", .{});
// Like dxc, the last input wins (dxc reads getLastArgValue(OPT_INPUT)).
if (parsed.inputs.len > 0) opts.input = parsed.inputs[parsed.inputs.len - 1];
@ -239,6 +269,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
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.job != null) return cli.fail("--job cannot be used inside a job file", .{});
if (opts.check_hash) {
const path = opts.input orelse return cli.fail("no input file", .{});
@ -308,7 +339,8 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
if (try pp.enterMainFile(input)) {
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
} else {
@ -324,6 +356,7 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
.sm_minor = if (profile) |p| p.minor else 10,
.library = is_lib,
.root = opts.entry,
.row_major = opts.row_major,
});
try sema.checkUnit(tu);
if (!opts.sema and !diags.hasErrors() and profile != null) {
@ -344,6 +377,7 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
};
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.row_major = opts.row_major;
mm.vk = opts.vk;
mm.strip_rootsig = opts.strip_rootsig;
if (opts.rootsig_ver) |rv| {
@ -357,6 +391,8 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
const color = opts.color orelse (Io.File.stderr().supportsAnsiEscapeCodes(cli.io) catch false);
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color });
try cli.stderr.flush();
// An unreadable input is an I/O error, as in dxc.
if (!opened) return error.Fatal;
if (diags.hasErrors()) return error.CompileFailed;
if (opts.preprocess) {
if (opts.pp_output) |path| {
@ -373,6 +409,14 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
return;
}
if (opts.spirv) {
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return cli.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });

View File

@ -29,11 +29,12 @@ pub const Extra = enum {
zdxc_ast,
zdxc_sema,
zdxc_ir,
job,
fcolor_diagnostics,
fno_color_diagnostics,
};
const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const u8 }{
const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const u8, kind: Kind = .flag, meta: []const u8 = "" }{
.{ .id = .zdxc_empty, .spelling = "zdxc-empty", .help = "Emit an empty shader for -T instead of compiling the input (development)" },
.{ .id = .zdxc_check_hash, .spelling = "zdxc-check-hash", .help = "Verify the container hash of the input (development)" },
.{ .id = .zdxc_lex, .spelling = "zdxc-lex", .help = "Print the input's tokens, one per line (development)" },
@ -41,6 +42,7 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const
.{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" },
.{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" },
.{ .id = .zdxc_ir, .spelling = "zdxc-ir", .help = "Print the lowered IR instead of compiling (development)" },
.{ .id = .job, .spelling = "-job=", .kind = .joined, .meta = "<job.json>", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" },
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },
};
@ -133,7 +135,7 @@ fn parseOne(arena: Allocator, argv: []const []const u8, index: *usize, failure:
}
for (extra_options) |o| {
if (prefixFits(str, "-", o.spelling) and n < cands.len) {
cands[n] = .{ .which = .{ .extra = o.id }, .kind = .flag, .count = 0, .prefix_len = 1, .spelling_len = o.spelling.len };
cands[n] = .{ .which = .{ .extra = o.id }, .kind = o.kind, .count = 0, .prefix_len = 1, .spelling_len = o.spelling.len };
n += 1;
}
}
@ -221,7 +223,7 @@ const not_yet = "not supported by zdxc yet";
pub fn support(id: Id) Support {
return switch (id) {
// Core compilation.
.target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ => .implemented,
.target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ, .Zpr, .Zpc => .implemented,
.Frs, .Qstrip_rootsignature, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define => .implemented,
.auto_binding_space, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_auto_shift_bindings, .fvk_stage_io_order_EQ, .fspv_flatten_resource_arrays, .fspv_use_legacy_buffer_matrix_order, .fspv_preserve_interface, .fspv_use_vulkan_memory_model, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_unknown_image_format, .fspv_extension_EQ, .fspv_reflect => .implemented,
// (Output is the same with or without the unoptimized-IR switch.)
@ -237,7 +239,7 @@ pub fn support(id: Id) Support {
.VD, .validator_version => .implemented,
// Accepted for build-script compatibility; no effect yet.
.Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .exports, .export_shaders_only, .default_linkage, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_preserve_bindings, .Oconfig => .ignored,
.Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .exports, .export_shaders_only, .default_linkage, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_preserve_bindings, .Oconfig => .ignored,
// Dropped by design (see the zdxc plan).
._SLASH_Zi, .Zs, .Fd, .Qembed_debug, .Qsource_in_debug_module, .Qpdb_in_private, .fspv_debug_EQ => .{ .unsupported = dropped_debug },
@ -287,7 +289,7 @@ pub fn printHelp(w: *std.Io.Writer, show_hidden: bool) !void {
}
}
try w.writeAll("\nzdxc options:\n");
for (extra_options) |o| try printOption(w, o.spelling, .flag, "", o.help, false);
for (extra_options) |o| try printOption(w, o.spelling, o.kind, o.meta, o.help, false);
}
fn printOption(w: *std.Io.Writer, spelling: []const u8, kind: Kind, meta: []const u8, help: []const u8, ignored: bool) !void {

View File

@ -33,6 +33,7 @@ pub const ir = struct {
pub const layout = @import("ir/layout.zig");
pub const texture = @import("ir/texture.zig");
pub const opt = @import("ir/opt.zig");
pub const split_resources = @import("ir/split_resources.zig");
};
pub const sema = struct {

View File

@ -120,20 +120,20 @@ const Layout = struct { rows: u8, cols: u8, kind: TypeTable.Shape };
/// Symbolic dimension bindings (`r`, `c`, `r2`, `c2`, ...).
const Bindings = struct {
names: [8][]const u8 = undefined,
values: [8]u8 = undefined,
values: [8]u16 = undefined,
n: usize = 0,
/// The widest shape of the arguments declared `<>`: all such types of
/// an intrinsic share their dimensions (dxc's r / c), scalars
/// splatting to the widest.
any_shape: ?TypeTable.Shape = null,
fn get(b: *const Bindings, name: []const u8) ?u8 {
fn get(b: *const Bindings, name: []const u8) ?u16 {
for (b.names[0..b.n], b.values[0..b.n]) |k, v| if (std.mem.eql(u8, k, name)) return v;
return null;
}
/// Bind or check; false on conflict.
fn bind(b: *Bindings, name: []const u8, v: u8) bool {
fn bind(b: *Bindings, name: []const u8, v: u16) bool {
if (b.get(name)) |old| return old == v;
if (b.n == b.names.len) return false;
b.names[b.n] = name;
@ -291,18 +291,19 @@ fn layoutType(sema: anytype, ls: *const table.Spec, comp: Scalar, group: usize,
const arg_shape: ?TypeTable.Shape = if (group > 0 and group - 1 < args.len) t.shape(args[group - 1].ty) else null;
if (ls.dims.len == 1) {
const len = dimValue(ls.dims[0], bindings, if (arg_shape) |sh| (if (sh.kind == .vector) sh.cols else if (sh.kind == .scalar) 1 else sh.cols) else null) orelse return null;
if (len < 1 or len > 4) return null;
// (Long vectors, SM 6.9: only arguments can make them.)
if (len < 1 or len > 1024) return null;
return try t.vector(comp, len);
}
const rows = dimValue(ls.dims[0], bindings, if (arg_shape) |sh| sh.rows else null) orelse return null;
const cols = dimValue(ls.dims[1], bindings, if (arg_shape) |sh| sh.cols else null) orelse return null;
if (rows < 1 or rows > 4 or cols < 1 or cols > 4) return null;
return try t.matrix(comp, rows, cols);
return try t.matrix(comp, @intCast(rows), @intCast(cols));
}
/// A layout dimension: a number, or a symbol bound from the argument.
fn dimValue(dim: []const u8, b: *Bindings, from_arg: ?u8) ?u8 {
if (std.fmt.parseInt(u8, dim, 10)) |v| return v else |_| {}
fn dimValue(dim: []const u8, b: *Bindings, from_arg: ?u16) ?u16 {
if (std.fmt.parseInt(u16, dim, 10)) |v| return v else |_| {}
if (b.get(dim)) |v| return v;
const v = from_arg orelse return null;
if (!b.bind(dim, v)) return null;

View File

@ -31,11 +31,15 @@ pub const Options = struct {
/// translation-unit checks; otherwise `root` (the entry point name).
library: bool = true,
root: ?[]const u8 = null,
/// `-Zpr`: matrices without an orientation (or `#pragma pack_matrix`)
/// are row_major.
row_major: bool = false,
};
/// Matrix orientation and float normalization written on a type: sugar
/// that does not change type identity.
pub const TypeAttrs = struct { orientation: ?[]const u8 = null, norm: ?[]const u8 = null };
/// that does not change type identity. `pack` is the `#pragma
/// pack_matrix` in effect where the type was written (true: row_major).
pub const TypeAttrs = struct { orientation: ?[]const u8 = null, norm: ?[]const u8 = null, pack: ?bool = null };
pub const Storage = enum { global_uniform, global_static, groupshared, cbuffer, local, local_static, param, constant };
@ -112,7 +116,7 @@ pub const Function = struct {
};
/// A bound template argument.
pub const Bound = union(enum) { type: TypeId, value: i64 };
pub const Bound = types.TemplateArg;
pub const FuncSet = struct {
funcs: std.ArrayList(*Function) = .empty,
@ -139,6 +143,8 @@ pub const Scope = struct {
syms: std.StringHashMapUnmanaged(Symbol) = .empty,
kind: enum { global, namespace, function, block, @"struct" } = .block,
name: []const u8 = "",
/// The struct of a struct scope.
strct: ?*const types.StructInfo = null,
};
/// Per-struct data kept by Sema (methods, nested scope).
@ -182,6 +188,9 @@ pub const Sema = struct {
all_functions: std.ArrayList(*Function) = .empty,
/// Type attributes carried by typedef names (clang's attributed-type
/// sugar: `typedef row_major float4x4 rm;`). Keyed by name.
/// Function parameters' and return types' matrix orientation (for
/// entry point signatures), keyed by the type as written.
sig_row_major: std.AutoHashMapUnmanaged(*const ast.TypeRef, bool) = .empty,
typedef_attrs: std.StringHashMapUnmanaged(TypeAttrs) = .empty,
/// Type attributes of the last resolveType result.
last_attrs: TypeAttrs = .{},
@ -293,6 +302,10 @@ pub const Sema = struct {
/// Adds a template (or a specialization) to the name's set here.
fn addTemplate(s: *Sema, name: []const u8, d: *const ast.Decl, spec: bool) !void {
try s.template_scopes.put(s.arena, d, s.scope);
// dxc rejects `typedef` members even in templates never used.
if (d.kind == .@"struct" and s.instance_depth == 0) if (d.kind.@"struct".members) |ms| for (ms) |m| {
if (m.kind == .typedef and !m.kind.typedef.alias and m.kind.typedef.template_params.len == 0) s.err(m.loc, "nested typedefs are not supported in HLSL", .{});
};
const set = blk: {
if (s.scope.syms.get(name)) |sym| switch (sym) {
.template => |t| break :blk t,
@ -567,7 +580,7 @@ pub const Sema = struct {
// Register the type before checking members, so the struct
// may name itself.
const info = try s.arena.create(types.StructInfo);
info.* = .{ .name = name.items };
info.* = .{ .name = name.items, .base_name = st.name, .template_args = b.args, .scopes = try s.scopeNames(b.scope), .is_class = st.keyword == .class };
const ty = try s.types.intern(.{ .@"struct" = info });
try b.scope.syms.put(s.arena, name.items, .{ .type = ty });
// The injected class name: `S` alone is this instance.
@ -1047,6 +1060,7 @@ pub const Sema = struct {
}
};
for (t.attr_words) |w| s.applyTypeAttr(w, base, &attrs);
if (s.types.get(base) == .matrix) attrs.pack = t.pack_matrix;
var ty = base;
// Array dimensions on template arguments (`float[3]`).
var i = t.array_dims.len;
@ -1058,6 +1072,24 @@ pub const Sema = struct {
return ty;
}
/// Written orientation, else `#pragma pack_matrix`'s, else `-Zpr`'s.
pub fn isRowMajor(s: *const Sema, a: TypeAttrs) bool {
if (a.orientation) |o| return eql(o, "row_major");
return a.pack orelse s.opts.row_major;
}
/// A parameter's or return value's orientation in a signature: as
/// written on it or by `#pragma pack_matrix`. A typedef's orientation
/// is lost there in dxc (and blocks the pragma), leaving `-Zpr`'s.
fn sigRowMajor(s: *const Sema, words: []const ast.QualWord, type_attrs: TypeAttrs) bool {
for (words) |w| {
if (eql(w.word, "row_major")) return true;
if (eql(w.word, "column_major")) return false;
}
if (type_attrs.orientation != null) return s.opts.row_major;
return type_attrs.pack orelse s.opts.row_major;
}
/// Applies a type attribute (dxc's handleHLSLTypeAttr checks).
fn applyTypeAttr(s: *Sema, w: ast.QualWord, ty: TypeId, a: *TypeAttrs) void {
if (ty == TypeTable.error_type) return;
@ -1109,7 +1141,6 @@ pub const Sema = struct {
s.err(templateArgLoc(args[1]), "invalid value, valid range is between 1 and {d} inclusive", .{max});
return TypeTable.error_type;
}
if (len > 4) return TypeTable.error_type; // long vectors: not modelled
return s.types.vector(comp, @intCast(len));
}
if (std.mem.eql(u8, n, "matrix")) {
@ -1151,8 +1182,11 @@ pub const Sema = struct {
return TypeTable.error_type;
}
var elem: TypeId = TypeTable.void_type;
var row_major = false;
if (args.len > 0) {
elem = try s.typeArg(args[0]) orelse TypeTable.error_type;
const structured = kind == .structured_buffer or kind == .rw_structured_buffer or kind == .append_structured_buffer or kind == .consume_structured_buffer;
if (structured and s.types.get(elem) == .matrix) row_major = s.isRowMajor(if (args[0] == .type) s.last_attrs else .{});
} else if (isTextureOrTypedBuffer(kind)) {
elem = try s.types.vector(.float, 4); // Texture2D == Texture2D<float4>
}
@ -1169,16 +1203,19 @@ pub const Sema = struct {
},
}
}
return s.types.intern(.{ .resource = .{ .kind = kind, .elem = elem, .name = n } });
if ((kind == .constant_buffer or kind == .texture_buffer) and args.len > 0) s.checkLongVectors(elem, templateArgLoc(args[0]), "ConstantBuffers or TextureBuffers");
return s.types.intern(.{ .resource = .{ .kind = kind, .elem = elem, .name = n, .row_major = row_major } });
}
const streams = [_]struct { []const u8, @FieldType(@FieldType(types.Type, "stream"), "kind") }{ .{ "PointStream", .point }, .{ "LineStream", .line }, .{ "TriangleStream", .triangle } };
for (streams) |st| if (std.mem.eql(u8, n, st[0])) {
const elem = if (args.len > 0) try s.typeArg(args[0]) orelse TypeTable.error_type else TypeTable.error_type;
s.checkLongVectors(elem, t.loc, "geometry streams");
return s.types.intern(.{ .stream = .{ .kind = st[1], .elem = elem } });
};
if (std.mem.eql(u8, n, "InputPatch") or std.mem.eql(u8, n, "OutputPatch")) {
const elem = if (args.len > 0) try s.typeArg(args[0]) orelse TypeTable.error_type else TypeTable.error_type;
const count: u32 = if (args.len > 1) @intCast(@max(0, s.constArg(args[1]) orelse 0)) else 0;
s.checkLongVectors(elem, t.loc, "tessellation patches");
return s.types.intern(.{ .patch = .{ .output = n[0] == 'O', .elem = elem, .count = count } });
}
}
@ -1210,6 +1247,17 @@ pub const Sema = struct {
};
return s.types.intern(.{ .resource = .{ .kind = vn[1], .elem = elem, .name = n } });
};
// An SM 6.10 matrix handle: its attributes are its type.
if (eql(n, "__builtin_LinAlgMatrix")) {
for (t.attrs) |a| if (eql(a.name, "__LinAlgMatrix_Attributes") and a.args.len == 5) {
var v: [5]u32 = undefined;
for (a.args, &v) |x, *o| o.* = @intCast(s.evalInt(x) orelse {
s.err(x.loc, "expression is not an integral constant expression", .{});
return TypeTable.error_type;
});
return s.types.intern(.{ .linalg = .{ .comp = v[0], .m = v[1], .n = v[2], .use = v[3], .scope = v[4] } });
};
}
// vk::SpirvType<opcode, size, alignment, operands...> and
// vk::SpirvOpaqueType<opcode, operands...>.
if (s.opts.spirv and (eql(n, "SpirvType") or eql(n, "SpirvOpaqueType"))) return s.inlineSpirvType(t, eql(n, "SpirvType"));
@ -1332,6 +1380,23 @@ pub const Sema = struct {
return .{ .type = ty };
}
/// SM 6.9 long vectors (over 4 elements) are not allowed in `context`.
fn checkLongVectors(s: *Sema, ty: TypeId, loc: Loc, comptime context: []const u8) void {
if (s.hasLongVector(ty, 0)) s.err(loc, "vectors of over 4 elements in " ++ context ++ " are not supported", .{});
}
fn hasLongVector(s: *Sema, ty: TypeId, depth: u32) bool {
if (depth > 32) return false;
return switch (s.types.get(ty)) {
.vector => |v| v.len > 4,
.array => |a| s.hasLongVector(a.elem, depth + 1),
.@"struct" => |st| for (st.fields.items) |f| {
if (s.hasLongVector(f.type, depth + 1)) break true;
} else false,
else => false,
};
}
/// The string argument of attribute `name` (`[[vk::builtin("X")]]`).
pub fn vkAttrString(attrs: []const ast.Attribute, name: []const u8) ?[]const u8 {
for (attrs) |a| if (std.mem.eql(u8, a.name, name) and a.args.len == 1 and a.args[0].kind == .string_lit) {
@ -1514,6 +1579,19 @@ pub const Sema = struct {
pub fn checkUnit(s: *Sema, tu: ast.TranslationUnit) Allocator.Error!void {
for (tu.decls) |d| try s.decl(d, .global);
// Entry points take and return no long vectors (SM 6.9).
for (s.all_functions.items) |f| {
if (f.owner != null) continue;
const entry = if (s.opts.library) for (f.decl.attrs) |a| {
if (eql(a.name, "shader")) break true;
} else false else if (s.opts.entry) |en| eql(f.name, en) else false;
if (!entry) continue;
for (f.params, f.decl.params) |p, pd| switch (s.types.get(p.type)) {
.patch, .stream => {},
else => s.checkLongVectors(p.type, pd.name_loc, "entry function parameters"),
};
s.checkLongVectors(f.ret, f.decl.name.loc, "entry function return type");
}
if (s.opts.entry) |entry| {
const found = if (s.global.syms.get(entry)) |sym| sym == .functions else false;
if (!found) _ = s.diags.report(.{ .severity = .@"error", .loc = .none }, "missing entry point definition", .{});
@ -1603,13 +1681,18 @@ pub const Sema = struct {
},
.typedef => |td| {
if (td.template_params.len > 0) return s.declareTemplate(td.name, d);
if (ctx == .member and s.instance_depth == 0) {
// (Alias declarations are allowed; template members are
// reported at the template's definition.)
if (ctx == .member and !td.alias and s.instance_depth == 0) {
s.err(d.loc, "nested typedefs are not supported in HLSL", .{});
return;
}
var base = try s.resolveType(td.type);
if (s.types.get(base) == .spirv and td.attrs.len > 0) base = try s.spirvTypeWithAttrs(base, td.attrs);
const attrs = s.checkModifiers(.typedef, td.qual_words, d.loc, base, s.last_attrs);
var attrs = s.checkModifiers(.typedef, td.qual_words, d.loc, base, s.last_attrs);
if (attrs.orientation == null) if (attrs.pack) |rm| {
attrs.orientation = if (rm) "row_major" else "column_major";
};
const ty = try s.applyArrayDims(base, td.array_dims);
try s.declare(td.name, .{ .type = ty }, d.loc);
if (attrs.orientation != null or attrs.norm != null) try s.typedef_attrs.put(s.arena, td.name, attrs);
@ -1659,6 +1742,18 @@ pub const Sema = struct {
}
}
/// The namespaces and structs enclosing `scope`, innermost first.
fn scopeNames(s: *Sema, scope: *const Scope) Allocator.Error![]const types.ScopeName {
var out: std.ArrayList(types.ScopeName) = .empty;
var sc: ?*const Scope = scope;
while (sc) |x| : (sc = x.parent) switch (x.kind) {
.namespace => try out.append(s.arena, .{ .name = x.name }),
.@"struct" => if (x.strct) |st| try out.append(s.arena, .{ .strct = st }),
else => {},
};
return out.items;
}
fn enumDecl(s: *Sema, d: *const ast.Decl, e: ast.EnumDecl) Allocator.Error!void {
const info = try s.arena.create(types.EnumInfo);
var underlying: Scalar = .int;
@ -1666,7 +1761,7 @@ pub const Sema = struct {
const ut = try s.resolveType(u);
underlying = s.types.component(ut) orelse .int;
}
info.* = .{ .name = e.name orelse "<anonymous enum>", .underlying = underlying, .scoped = e.scoped };
info.* = .{ .name = e.name orelse "<anonymous enum>", .underlying = underlying, .scoped = e.scoped, .scopes = try s.scopeNames(s.scope) };
const ty = try s.types.intern(.{ .@"enum" = info });
if (e.name) |n| try s.declare(n, .{ .type = ty }, d.loc);
const sc = try s.arena.create(Scope);
@ -1708,13 +1803,13 @@ pub const Sema = struct {
return;
} else {
info = try s.arena.create(types.StructInfo);
info.* = .{ .name = name };
info.* = .{ .name = name, .scopes = try s.scopeNames(s.scope), .is_class = st.keyword == .class };
ty = try s.types.intern(.{ .@"struct" = info });
try s.declare(name, .{ .type = ty }, d.loc);
}
const members = st.members orelse return;
const sc = try s.arena.create(Scope);
sc.* = .{ .parent = s.scope, .kind = .@"struct", .name = name };
sc.* = .{ .parent = s.scope, .kind = .@"struct", .name = name, .strct = info };
const ss = try s.arena.create(StructSema);
ss.* = .{ .scope = sc, .decl = d };
info.sema = ss;
@ -1789,7 +1884,7 @@ pub const Sema = struct {
if (s.opts.spirv) if (s.vkAttrInt(v.attrs, "vk::offset")) |vo| if (vo % 16 != 0 and s.types.get(ft) == .@"struct") {
s.warn(v.name_loc, null, "The offset provided in the attribute should be 16-byte aligned.", .{});
};
try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals), .vk_location = s.vkAttrInt(v.attrs, "vk::location"), .vk_index = s.vkAttrInt(v.attrs, "vk::index"), .vk_offset = if (s.opts.spirv) s.vkAttrInt(v.attrs, "vk::offset") else null, .vk_builtin = vkAttrString(v.attrs, "vk::builtin"), .decorations = if (s.opts.spirv) try s.memberDecorations(v.attrs) else &.{} });
try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = s.isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals), .vk_location = s.vkAttrInt(v.attrs, "vk::location"), .vk_index = s.vkAttrInt(v.attrs, "vk::index"), .vk_offset = if (s.opts.spirv) s.vkAttrInt(v.attrs, "vk::offset") else null, .vk_builtin = vkAttrString(v.attrs, "vk::builtin"), .decorations = if (s.opts.spirv) try s.memberDecorations(v.attrs) else &.{} });
},
.func => {},
else => try s.decl(m, .member),
@ -2188,12 +2283,18 @@ pub const Sema = struct {
.init = v.init,
.init_scope = s.scope,
.decl = v,
.row_major = isRowMajor(decl_attrs),
.row_major = s.isRowMajor(decl_attrs),
};
try s.declare(v.name, .{ .variable = variable }, v.name_loc);
try s.decl_vars.put(s.arena, v, variable);
if (ctx == .cbuffer) variable.block = s.current_block;
if (storage == .global_uniform) try s.uniform_globals.append(s.arena, variable);
if (ctx == .cbuffer) {
variable.block = s.current_block;
s.checkLongVectors(ty, v.name_loc, "cbuffers or tbuffers");
}
if (storage == .global_uniform) {
try s.uniform_globals.append(s.arena, variable);
s.checkLongVectors(ty, v.name_loc, "cbuffers or tbuffers");
}
if (storage == .global_uniform or (storage == .global_static and !q.static and ctx == .global)) try s.global_order.append(s.arena, .{ .variable = variable });
if (storage == .global_static or storage == .constant or storage == .local_static) try s.static_globals.append(s.arena, variable);
// Unsized arrays take their size from the initializer.
@ -2266,11 +2367,15 @@ pub const Sema = struct {
// `auto` return types are deduced in HLSL 202x; unconstrained here.
const ret = if (f.ret.name.isSimple("auto")) TypeTable.error_type else try s.applyArrayDims(try s.resolveType(f.ret), f.ret_dims);
const params = try s.arena.alloc(Param, f.params.len);
_ = s.checkModifiers(if (owner != null) .method else .function, f.qual_words, if (f.qual_words.len > 0) f.qual_words[0].loc else f.ret.loc, ret, s.last_attrs);
const ret_type_attrs = s.last_attrs;
_ = s.checkModifiers(if (owner != null) .method else .function, f.qual_words, if (f.qual_words.len > 0) f.qual_words[0].loc else f.ret.loc, ret, ret_type_attrs);
try s.sig_row_major.put(s.arena, f.ret, s.sigRowMajor(f.qual_words, ret_type_attrs));
s.checkFunctionAttrs(f.attrs);
for (f.params, params) |p, *out| {
const pbase = try s.resolveType(p.type);
_ = s.checkModifiers(.parameter, p.qual_words, if (p.qual_words.len > 0) p.qual_words[0].loc else p.type.loc, pbase, s.last_attrs);
const ptype_attrs = s.last_attrs;
_ = s.checkModifiers(.parameter, p.qual_words, if (p.qual_words.len > 0) p.qual_words[0].loc else p.type.loc, pbase, ptype_attrs);
try s.sig_row_major.put(s.arena, p.type, s.sigRowMajor(p.qual_words, ptype_attrs));
try s.checkArrayDims(p.name_loc, pbase, p.array_dims);
const pt = try s.applyArrayDims(pbase, p.array_dims);
s.checkSemantics(.parameter, p.semantics, pt, false);
@ -3180,8 +3285,12 @@ pub const Sema = struct {
switch (s.types.get(b.ty)) {
.scalar, .vector => {
const comp = s.types.component(b.ty).?;
const len: u8 = if (s.types.get(b.ty) == .vector) s.types.get(b.ty).vector.len else 1;
const sw = parseSwizzle(name, len) orelse {
const len: u16 = if (s.types.get(b.ty) == .vector) s.types.get(b.ty).vector.len else 1;
if (len > 4) {
s.err(name_loc, "invalid swizzle '{s}' on vector of over 4 elements.", .{name});
return err_typed;
}
const sw = parseSwizzle(name, @intCast(len)) orelse {
s.err(name_loc, "invalid format for vector swizzle '{s}'", .{name});
return err_typed;
};
@ -4055,10 +4164,6 @@ pub fn interpOf(q: ast.Qualifiers) types.Interp {
return .{ .nointerpolation = q.nointerpolation, .linear = q.linear, .centroid = q.centroid, .sample = q.sample, .noperspective = q.noperspective };
}
fn isRowMajor(a: TypeAttrs) bool {
return if (a.orientation) |o| eql(o, "row_major") else false;
}
fn eql(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
@ -4271,3 +4376,19 @@ test "recursion is reported from exported functions" {
"1: error: recursive functions are not allowed: function 'entry' calls recursive function 'recurse'",
});
}
test "nested types and typedefs" {
// `typedef` members are errors, templates included (even unused);
// alias declarations are not, and nested types of template instances
// resolve.
try expectDiags(
\\struct A { typedef float F; float x; };
\\template <typename T> struct B { typedef T F; T x; };
\\struct C { using F = float; F x; };
\\template <typename T> struct D { struct In { T t; }; using E = T; };
\\void f() { C::F c = 1; D<float>::In i; i.t = c; D<int>::E e = 2; }
, .{}, &.{
"1: error: nested typedefs are not supported in HLSL",
"2: error: nested typedefs are not supported in HLSL",
});
}

View File

@ -377,8 +377,22 @@ pub const Interp = packed struct(u8) {
};
/// A struct's layout-relevant information. Methods live in Sema.
/// A template argument: a type or an integral value.
pub const TemplateArg = union(enum) { type: TypeId, value: i64 };
/// A scope enclosing a declaration (for mangled names): a namespace or a
/// struct.
pub const ScopeName = union(enum) { name: []const u8, strct: *const StructInfo };
pub const StructInfo = struct {
name: []const u8,
/// For mangled names: the name without template arguments, the
/// arguments of a template instance, the enclosing scopes (innermost
/// first) and whether it was declared `class`.
base_name: ?[]const u8 = null,
template_args: []const TemplateArg = &.{},
scopes: []const ScopeName = &.{},
is_class: bool = false,
fields: std.ArrayList(Field) = .empty,
/// Direct base structs (HLSL 2021 single inheritance, in practice).
bases: std.ArrayList(*StructInfo) = .empty,
@ -438,6 +452,8 @@ pub const EnumInfo = struct {
name: []const u8,
underlying: Scalar,
scoped: bool,
/// Enclosing scopes, innermost first (mangled names).
scopes: []const ScopeName = &.{},
};
pub const Type = union(enum) {
@ -445,7 +461,7 @@ pub const Type = union(enum) {
/// The type of an ill-formed expression: suppresses follow-on errors.
@"error",
scalar: Scalar,
vector: struct { elem: Scalar, len: u8 },
vector: struct { elem: Scalar, len: u16 },
matrix: struct { elem: Scalar, rows: u8, cols: u8 },
/// `len == 0` means unsized (`float a[]`).
array: struct { elem: TypeId, len: u32 },
@ -453,7 +469,9 @@ pub const Type = union(enum) {
@"enum": *EnumInfo,
/// `elem` is the template argument (or the void type when absent).
/// `flags`: RayQuery's constant ray flags (template arguments).
resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8, flags: u32 = 0, flags2: u32 = 0 },
/// `row_major`: a structured buffer's matrix elements are (as written,
/// by `#pragma pack_matrix` or -Zpr; dxc's SPIR-V honors it).
resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8, flags: u32 = 0, flags2: u32 = 0, row_major: bool = false },
sampler: struct { comparison: bool },
string,
/// PointStream / LineStream / TriangleStream<T>.
@ -467,8 +485,13 @@ pub const Type = union(enum) {
/// `tex.mips` / `tex.sample` and their slices (`tex.mips[level]`).
texture_view: struct { texture: TypeId, kind: enum { mips, mips_slice, sample, sample_slice } },
spirv: *const SpirvTypeInfo,
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
/// scope)]]` (SM 6.10): an opaque matrix handle.
linalg: LinAlgMatrix,
};
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
/// Interns types. Ids 0 and 1 are `error` and `void`.
pub const TypeTable = struct {
gpa: Allocator,
@ -506,7 +529,7 @@ pub const TypeTable = struct {
.array => |a| .{ .tag = 4, .a = a.elem, .b = a.len },
.@"struct" => |s| .{ .tag = 5, .a = @intFromPtr(s), .b = 0 },
.@"enum" => |e| .{ .tag = 6, .a = @intFromPtr(e), .b = 0 },
.resource => |r| .{ .tag = 7, .a = (@as(u64, @backingInt(r.kind)) << 32) | r.elem, .b = std.hash.Wyhash.hash(r.flags | (@as(u64, r.flags2) << 32), r.name) },
.resource => |r| .{ .tag = 7, .a = (@as(u64, @intFromBool(r.row_major)) << 48) | (@as(u64, @backingInt(r.kind)) << 32) | r.elem, .b = std.hash.Wyhash.hash(r.flags | (@as(u64, r.flags2) << 32), r.name) },
.sampler => |s| .{ .tag = 8, .a = @intFromBool(s.comparison), .b = 0 },
.string => .{ .tag = 9, .a = 0, .b = 0 },
.stream => |s| .{ .tag = 10, .a = @backingInt(s.kind), .b = s.elem },
@ -514,6 +537,7 @@ pub const TypeTable = struct {
.descriptor_heap => |h| .{ .tag = 12, .a = @intFromBool(h.sampler), .b = 0 },
.dynamic_resource => .{ .tag = 13, .a = 0, .b = 0 },
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
.linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
};
}
@ -532,7 +556,7 @@ pub const TypeTable = struct {
}
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
pub fn vector(t: *TypeTable, s: Scalar, len: u8) !TypeId {
pub fn vector(t: *TypeTable, s: Scalar, len: u16) !TypeId {
return t.intern(.{ .vector = .{ .elem = s, .len = len } });
}
@ -557,7 +581,7 @@ pub const TypeTable = struct {
pub const Shape = struct {
rows: u8,
cols: u8,
cols: u16,
kind: enum { scalar, vector, matrix },
pub fn count(sh: Shape) u32 {
@ -644,7 +668,7 @@ pub const TypeTable = struct {
return switch (sh.kind) {
.scalar => t.scalar(s),
.vector => t.vector(s, sh.cols),
.matrix => t.matrix(s, sh.rows, sh.cols),
.matrix => t.matrix(s, sh.rows, @intCast(sh.cols)),
};
}
@ -703,6 +727,7 @@ pub const TypeTable = struct {
.sample_slice => "sample_slice_type",
} }),
.spirv => |x| if (x.size == 0) "SpirvOpaqueType" else "SpirvType",
.linalg => "__builtin_LinAlgMatrix",
};
}
};

View File

@ -140,6 +140,9 @@ const Emitter = struct {
/// spellings are one type).
spirv_types: std.StringHashMapUnmanaged(Id) = .empty,
/// Explicitly laid out variants of arrays and structs (buffers).
/// Arrays with an ArrayStride by element type, length (0: runtime
/// array) and stride: one type per layout, as in dxc.
strided_arrays: std.AutoHashMapUnmanaged([3]u32, Id) = .empty,
layout_types: std.AutoHashMapUnmanaged(LayoutKey, Id) = .empty,
/// Per instruction (current function): the buffer layout its pointer
/// result points into, if any.
@ -350,6 +353,7 @@ const Emitter = struct {
.vector => |v| blk: {
// vector<T, 1> is a plain T (SPIR-V has no 1-vectors).
if (v.len == 1) break :blk try e.scalarType(v.elem);
if (v.len > 4) return e.unsupported("vectors of over 4 elements are not supported in SPIR-V (Vulkan has no long vectors)", .{});
if (storageScalar(v.elem) != v.elem) break :blk try e.typeId(try e.t.vector(storageScalar(v.elem), v.len));
const elem = try e.scalarType(v.elem);
const id = e.b.newId();
@ -377,15 +381,15 @@ const Emitter = struct {
break :blk id;
},
.@"struct" => |st| blk: {
const members = try e.arena.alloc(u32, st.fields.items.len);
for (st.fields.items, members) |fld, *mid| mid.* = try e.typeId(fld.type);
var members: std.ArrayList(u32) = .empty;
for (st.fields.items) |fld| if (!layout.isOpaque(e.t, fld.type)) try members.append(e.arena, try e.typeId(fld.type));
const id = e.b.newId();
var ops: std.ArrayList(u32) = .empty;
try ops.append(e.arena, id);
try ops.appendSlice(e.arena, members);
try ops.appendSlice(e.arena, members.items);
try e.b.emit(.types_globals, .type_struct, ops.items);
try e.b.emitWithString(.debug_names, .name, &.{id}, try std.fmt.allocPrint(e.arena, "struct.{s}", .{st.name}), &.{});
for (st.fields.items, 0..) |fld, k| try e.b.emitWithString(.debug_names, .member_name, &.{ id, @intCast(k) }, fld.name, &.{});
for (st.fields.items, 0..) |fld, k| if (!layout.isOpaque(e.t, fld.type)) try e.b.emitWithString(.debug_names, .member_name, &.{ id, dataIndex(e.t, st, @intCast(k)) }, fld.name, &.{});
try e.memberDecorations(id, st, false);
break :blk id;
},
@ -478,34 +482,44 @@ const Emitter = struct {
}
const key: LayoutKey = .{ ty, rules, row_major };
if (e.layout_types.get(key)) |id| return id;
const id = e.b.newId();
switch (e.t.get(ty)) {
.matrix => |m| {
// Row-major integer matrix: an array of its rows.
const row_ty = try e.layoutTypeId(try e.t.vector(m.elem, m.cols), rules, false);
try e.b.emit(.types_globals, .type_array, &.{ id, row_ty, try e.constUint(m.rows) });
try e.b.emit(.annotations, .decorate, &.{ id, 6, layout.matrixStride(e.t, ty, true, rules) }); // ArrayStride
const id = switch (e.t.get(ty)) {
// Row-major integer matrix: an array of its rows.
.matrix => |m| try e.stridedArray(try e.layoutTypeId(try e.t.vector(m.elem, m.cols), rules, false), m.rows, layout.matrixStride(e.t, ty, true, rules)),
.array => |a| try e.stridedArray(try e.layoutTypeId(a.elem, rules, row_major), a.len, layout.arrayStride(e.t, a.elem, row_major, rules) catch return e.unsupported("buffer member type", .{})),
.@"struct" => |st| blk: {
const id = e.b.newId();
try e.layoutStruct(id, st, rules, st.name);
break :blk id;
},
.array => |a| {
const elem = try e.layoutTypeId(a.elem, rules, row_major);
try e.b.emit(.types_globals, .type_array, &.{ id, elem, try e.constUint(a.len) });
const stride = layout.arrayStride(e.t, a.elem, row_major, rules) catch return e.unsupported("buffer member type", .{});
try e.b.emit(.annotations, .decorate, &.{ id, 6, stride }); // ArrayStride
},
.@"struct" => |st| try e.layoutStruct(id, st, rules, st.name),
else => return e.unsupported("buffer members of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
}
};
try e.layout_types.put(e.arena, key, id);
return id;
}
/// `elem[len]` (a runtime array for `len` 0) with an ArrayStride.
fn stridedArray(e: *Emitter, elem: Id, len: u32, stride: u32) Error!Id {
const len_id = if (len == 0) 0 else try e.constUint(len);
const gop = try e.strided_arrays.getOrPut(e.arena, .{ elem, len_id, stride });
if (gop.found_existing) return gop.value_ptr.*;
const id = e.b.newId();
if (len == 0) {
try e.b.emit(.types_globals, .type_runtime_array, &.{ id, elem });
} else try e.b.emit(.types_globals, .type_array, &.{ id, elem, len_id });
try e.b.emit(.annotations, .decorate, &.{ id, 6, stride }); // ArrayStride
gop.value_ptr.* = id;
return id;
}
/// Emits struct `id` with `st`'s fields laid out by `rules`.
fn layoutStruct(e: *Emitter, id: Id, st: *const types.StructInfo, rules: layout.Rules, name: []const u8) Error!void {
{
{
var ops: std.ArrayList(u32) = .empty;
try ops.append(e.arena, id);
for (st.fields.items) |fld| try ops.append(e.arena, try e.layoutTypeId(fld.type, rules, fld.row_major));
// (Resources in structs are not members of the SPIR-V
// struct: they are their own variables.)
for (st.fields.items) |fld| if (!layout.isOpaque(e.t, fld.type)) try ops.append(e.arena, try e.layoutTypeId(fld.type, rules, fld.row_major));
try e.b.emit(.types_globals, .type_struct, ops.items);
const offs = layout.fieldOffsets(e.arena, e.t, st, rules) catch return e.unsupported("buffer member type '{s}'", .{st.name});
// An explicit [[vk::offset]] still has to respect the rules.
@ -518,7 +532,8 @@ const Emitter = struct {
if (o % need != 0) return e.unsupported("[[vk::offset({d})]] on '{s}' is not aligned to {d} bytes for this buffer layout", .{ o, fld.name, need });
};
for (st.fields.items, offs, 0..) |fld, o, k| {
const mk: u32 = @intCast(k);
if (layout.isOpaque(e.t, fld.type)) continue;
const mk: u32 = dataIndex(e.t, st, @intCast(k));
try e.b.emit(.annotations, .member_decorate, &.{ id, mk, 35, o }); // Offset
// Float matrices (possibly in arrays): HLSL rows are
// SPIR-V columns, so column_major is RowMajor.
@ -539,7 +554,9 @@ const Emitter = struct {
/// Members' inline SPIR-V decorations (not Offset in buffer layouts,
/// which place members themselves).
fn memberDecorations(e: *Emitter, id: Id, st: *const types.StructInfo, laid_out: bool) Error!void {
for (st.fields.items, 0..) |fld, k| for (fld.decorations) |d| {
for (st.fields.items, 0..) |fld, kk| for (fld.decorations) |d| {
if (layout.isOpaque(e.t, fld.type)) continue;
const k = dataIndex(e.t, st, @intCast(kk));
if (laid_out and d.decoration == 35) continue;
try e.requireNeed(op_caps.need(&op_caps.decorations, d.decoration));
if (d.strings.len > 0) {
@ -902,6 +919,12 @@ const Emitter = struct {
try e.emitFunction(m.functions.items[v.fi], v.id, v.bindings);
}
// An acceleration structure only declared (dxc's optimizer drops
// it): its type needs ray queries or ray tracing.
if (e.accel_type != 0 and !e.capabilities.contains(.ray_tracing_khr) and !e.capabilities.contains(.ray_query_khr)) {
try e.cap(.ray_query_khr);
try e.extension("SPV_KHR_ray_query");
}
// The Vulkan memory model, when asked for or needed (as dxc).
const vulkan_mm = e.vk.vulkan_memory_model or e.capabilities.contains(.vulkan_memory_model);
if (vulkan_mm) {
@ -1133,7 +1156,7 @@ const Emitter = struct {
}
switch (g.space) {
.resource => {
if (e.vk.flatten_arrays and e.t.get(g.ty) == .array and e.constantlyIndexed(@intCast(gi))) {
if ((e.vk.flatten_arrays or e.m.resource_structs) and e.t.get(g.ty) == .array and e.constantlyIndexed(@intCast(gi))) {
// One variable per element, on consecutive bindings.
var et = g.ty;
var n: u32 = 1;
@ -1293,6 +1316,7 @@ const Emitter = struct {
try vars.append(e.arena, .{ .bd = bd, .counter = false });
if (bd.acs) try vars.append(e.arena, .{ .bd = bd, .counter = true });
if (bd.global) |g| try declared.put(e.arena, g, {});
for (bd.members) |mb| if (mb.global) |g| try declared.put(e.arena, g, {});
}
// Resources with no declaration of their own (none in practice),
// and counters of RW structured buffers, in the order first used.
@ -1314,6 +1338,10 @@ const Emitter = struct {
}
const record = struct {
fn f(em: *Emitter, v: Var, slot: Slot) void {
// A struct of resources: each at its offset.
for (v.bd.members) |mb| if (mb.global) |g| {
em.slots[g] = .{ .set = slot.set, .binding = slot.binding + mb.offset };
};
const g = v.bd.global orelse return;
if (v.counter) em.counter_slots[g] = slot else em.slots[g] = slot;
}
@ -1353,7 +1381,7 @@ const Emitter = struct {
record(e, v, .{ .set = set, .binding = b });
} else if (v.bd.vk_binding) |b| {
const set = v.bd.vk_set orelse default_set;
try e.useBindings(set, b, v.n(e.vk.flatten_arrays));
try e.useBindings(set, b, v.n((e.vk.flatten_arrays or e.m.resource_structs)));
record(e, v, .{ .set = set, .binding = b });
}
}
@ -1363,7 +1391,7 @@ const Emitter = struct {
const set = if (v.bd.reg.space_given) v.bd.reg.space else default_set;
const class: u8 = if (v.bd.reg.class == 's' and v.bd.combined) 't' else v.bd.reg.class;
const b = v.bd.reg.index + e.vk.shift(class, set);
try e.useBindings(set, b, v.n(e.vk.flatten_arrays));
try e.useBindings(set, b, v.n((e.vk.flatten_arrays or e.m.resource_structs)));
record(e, v, .{ .set = set, .binding = b });
}
// The rest, in order.
@ -1380,7 +1408,7 @@ const Emitter = struct {
}
const set = if (v.bd.space_only and v.bd.reg.space_given) v.bd.reg.space else default_set;
const shift = if (e.vk.auto_shift) e.vk.shift(e.implicitClass(v.bd), set) else 0;
record(e, v, .{ .set = set, .binding = try e.nextBindings(set, shift, v.n(e.vk.flatten_arrays)) });
record(e, v, .{ .set = set, .binding = try e.nextBindings(set, shift, v.n((e.vk.flatten_arrays or e.m.resource_structs))) });
}
}
}
@ -1942,7 +1970,7 @@ const Emitter = struct {
try e.cap(.variable_pointers);
if (e.spv_minor < 3) try e.extension("SPV_KHR_variable_pointers");
}
try params.append(e.arena, if (p.by_ref) try e.pointerType(.function, t) else t);
try params.append(e.arena, if (p.by_ref) try e.pointerType(if (p.groupshared) .workgroup else .function, t) else t);
}
const fn_ty = try e.functionType(ret, params.items);
try e.b.emit(.functions, .function, &.{ ret, fn_id, 0, fn_ty });
@ -2185,7 +2213,7 @@ const Emitter = struct {
}
e.ptr_layouts[ri] = switch (e.m.globals.items[g].space) {
.cbuffer => if (e.m.globals.items[g].tbuffer) .{ .rules = e.tbRules(), .row_major = false, .buffer = true } else .{ .rules = e.cbRules(), .row_major = false },
.resource => .{ .rules = e.sbRules(), .row_major = false, .buffer = true },
.resource => .{ .rules = e.sbRules(), .row_major = bufferRowMajor(e.t, e.m.globals.items[g].ty), .buffer = true },
else => null,
};
},
@ -2201,7 +2229,8 @@ const Emitter = struct {
return;
}
// Resources stay as their variables (accessed by chains).
if (i.ptr == .none and (e.t.get(i.ty) == .resource or e.t.get(i.ty) == .sampler)) {
if (i.ptr == .none and (e.t.get(i.ty) == .resource or e.t.get(i.ty) == .sampler or (e.t.get(i.ty) == .array and isResourceType(e.t, i.ty)))) {
if (e.val(p) == 0 and f.inst(p).op == .local_var) return e.unsupported("a resource local read before it is assigned", .{});
e.vals[ri] = e.val(p);
return;
}
@ -2224,6 +2253,12 @@ const Emitter = struct {
e.vals[s.ptr.index()] = e.val(s.value);
return;
}
// A resource written back to the global it is (an inout
// argument): nothing to do.
if (target.op != .local_var and isResourceType(e.t, target.ty) and target.ptr == .resource) {
if (e.val(s.value) == e.val(s.ptr)) return;
return e.unsupported("assigning another resource to a global resource", .{});
}
if (target.op == .local_var and isResourceType(e.t, target.ty)) {
const old = e.vals[s.ptr.index()];
if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{});
@ -2298,7 +2333,7 @@ const Emitter = struct {
.cbuffer, .resource => .uniform,
else => return e.unsupported("access into this storage is not supported yet", .{}),
};
var pl = if (shader_record) PtrLayout{ .rules = e.sbRules(), .row_major = false } else if (into_cb) PtrLayout{ .rules = e.cbRules(), .row_major = false } else if (into_tb) PtrLayout{ .rules = e.tbRules(), .row_major = false, .buffer = true } else if (into_buffer) PtrLayout{ .rules = e.sbRules(), .row_major = false, .buffer = true } else e.ptr_layouts[a.base.index()];
var pl = if (shader_record) PtrLayout{ .rules = e.sbRules(), .row_major = false } else if (into_cb) PtrLayout{ .rules = e.cbRules(), .row_major = false } else if (into_tb) PtrLayout{ .rules = e.tbRules(), .row_major = false, .buffer = true } else if (into_buffer) PtrLayout{ .rules = e.sbRules(), .row_major = bufferRowMajor(e.t, f.inst(a.base).ty), .buffer = true } else e.ptr_layouts[a.base.index()];
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ 0, 0, e.val(a.base) });
var cur = f.inst(a.base).ty;
@ -2324,8 +2359,16 @@ const Emitter = struct {
.@"struct" => |st| blk: {
const k = f.inst(x);
if (k.op != .constant) break :blk cur;
const fld = st.fields.items[@intCast(k.op.constant.int)];
const fi: u32 = @intCast(k.op.constant.int);
const fld = st.fields.items[fi];
if (pl) |*p| p.row_major = fld.row_major;
// (Resource members are not in the SPIR-V
// struct: later members move up.)
if (dataIndex(e.t, st, fi) != fi) {
try ops.append(e.arena, try e.constUint(dataIndex(e.t, st, fi)));
cur = fld.type;
continue;
}
break :blk fld.type;
},
else => cur,
@ -2448,16 +2491,28 @@ const Emitter = struct {
e.vals[ri] = e.val(x.agg);
return;
}
e.vals[ri] = try e.op1(.composite_extract, i.ty, &.{ e.val(x.agg), x.index });
e.vals[ri] = try e.op1(.composite_extract, i.ty, &.{ e.val(x.agg), memberIndex(e.t, at, x.index) });
},
.insert => |x| {
if (e.isScalarLike(i.ty) or (e.t.get(i.ty) == .matrix and e.t.get(i.ty).matrix.rows == 1)) {
e.vals[ri] = e.val(x.value);
return;
}
e.vals[ri] = try e.op1(.composite_insert, i.ty, &.{ e.val(x.value), e.val(x.agg), x.index });
e.vals[ri] = try e.op1(.composite_insert, i.ty, &.{ e.val(x.value), e.val(x.agg), memberIndex(e.t, i.ty, x.index) });
},
.construct => |xs| {
// Struct values leave their resources out (split off).
if (e.t.get(i.ty) == .@"struct" and xs.len == e.t.get(i.ty).@"struct".fields.items.len) {
const st = e.t.get(i.ty).@"struct";
var any = false;
for (st.fields.items) |fld| any = any or layout.isOpaque(e.t, fld.type);
if (any) {
var parts: std.ArrayList(u32) = .empty;
for (xs, st.fields.items) |x, fld| if (!layout.isOpaque(e.t, fld.type)) try parts.append(e.arena, e.val(x));
e.vals[ri] = try e.op1(.composite_construct, i.ty, parts.items);
return;
}
}
if (xs.len == 1 and e.isScalarLike(i.ty)) {
e.vals[ri] = e.val(xs[0]);
return;
@ -2908,6 +2963,15 @@ const Emitter = struct {
}
/// The laid-out element type of a structured / byte-address buffer.
/// A structured buffer type's matrix elements are row_major.
fn bufferRowMajor(t: *TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource => |r| r.row_major,
.array => |a| bufferRowMajor(t, a.elem),
else => false,
};
}
fn bufferElemType(e: *Emitter, ty: TypeId) Error!?Id {
const r = switch (e.t.get(ty)) {
.resource => |r| r,
@ -2918,7 +2982,7 @@ const Emitter = struct {
.structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer => r.elem,
else => return null,
};
return try e.layoutTypeId(elem_ty, e.sbRules(), false);
return try e.layoutTypeId(elem_ty, e.sbRules(), r.row_major);
}
/// The BufferBlock struct of a buffer type (one per HLSL type, so
@ -2928,18 +2992,16 @@ const Emitter = struct {
const r = e.t.get(ty).resource;
const elem_ty = if (r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer) try e.t.scalar(.uint) else r.elem;
const elem = (try e.bufferElemType(ty)).?;
const stride = layout.arrayStride(e.t, elem_ty, false, e.sbRules()) catch return e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, elem_ty)});
const rt = e.b.newId();
try e.b.emit(.types_globals, .type_runtime_array, &.{ rt, elem });
try e.b.emit(.annotations, .decorate, &.{ rt, 6, stride }); // ArrayStride
const stride = layout.arrayStride(e.t, elem_ty, r.row_major, e.sbRules()) catch return e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, elem_ty)});
const rt = try e.stridedArray(elem, 0, stride);
const st = e.b.newId();
try e.b.emit(.types_globals, .type_struct, &.{ st, rt });
try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 35, 0 }); // Offset 0
if (e.isTrueMatrix(elem_ty) and storageScalar(e.t.get(elem_ty).matrix.elem).isFloat()) {
// Buffers of (column-major) matrices: HLSL rows are SPIR-V
// columns.
try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 7, layout.matrixStride(e.t, elem_ty, false, e.sbRules()) }); // MatrixStride
try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 4 }); // RowMajor
// Buffers of matrices: HLSL rows are SPIR-V columns, so
// column_major is RowMajor.
try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 7, layout.matrixStride(e.t, elem_ty, r.row_major, e.sbRules()) }); // MatrixStride
try e.b.emit(.annotations, .member_decorate, &.{ st, 0, if (r.row_major) 5 else 4 }); // ColMajor / RowMajor
}
if (!r.kind.isWritable() and r.kind != .consume_structured_buffer) try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 24 }); // NonWritable
try e.b.emit(.annotations, .decorate, &.{ st, e.bufferBlockDecoration() });
@ -3024,6 +3086,8 @@ const Emitter = struct {
},
.call => |c| for (c.args) |x| if (x.index() == k) return false,
.store => |st| if (st.value.index() == k) return false,
// (Read whole: passed on to a function.)
.load => |p| if (p.index() == k) return false,
else => {},
};
}
@ -4692,6 +4756,20 @@ fn isRayQuery(t: *TypeTable, ty: TypeId) bool {
/// Resources and samplers (not RayQuery objects, which are function
/// storage passed by pointer).
/// A composite member index in SPIR-V (struct resource members dropped).
fn memberIndex(t: *const TypeTable, ty: TypeId, k: u32) u32 {
return if (t.get(ty) == .@"struct") dataIndex(t, t.get(ty).@"struct", k) else k;
}
/// Member `k`'s index in the SPIR-V struct (resource members dropped).
fn dataIndex(t: *const TypeTable, st: *const types.StructInfo, k: u32) u32 {
var n: u32 = 0;
for (st.fields.items[0..k]) |f| {
if (!layout.isOpaque(t, f.type)) n += 1;
}
return n;
}
fn isResourceType(t: *TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource => !isRayQuery(t, ty),

Binary file not shown.

View File

@ -1,13 +0,0 @@
// PROFILE: as_6_5
// Amplification shader: a groupshared payload (struct-typed, accessed
// through GEPs) sent with DispatchMesh.
// ZCHECK: call void @dx.op.dispatchMesh.struct.Payload(i32 173
struct Payload { uint base; float scale[2]; uint ids[8]; };
groupshared Payload pl;
[numthreads(8,1,1)]
void main(uint tid : SV_GroupIndex) {
pl.ids[tid] = tid * 2;
if (tid == 0) { pl.base = 7; pl.scale[0] = 1; pl.scale[1] = 2; }
GroupMemoryBarrierWithGroupSync();
DispatchMesh(2, 1, 1, pl);
}

View File

@ -1,23 +0,0 @@
// PROFILE: cs_6_0
// Atomics on groupshared memory, buffers and texels; byte-address buffers.
// ZCHECK: atomicrmw add i32 addrspace(3)*
// ZCHECK: cmpxchg i32 addrspace(3)*
// ZCHECK: @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle {{.*}}, i32 8,
// ZCHECK: @dx.op.atomicCompareExchange.i32(i32 79,
groupshared uint cnt;
groupshared int mx[4];
RWStructuredBuffer<uint> sb : register(u0);
RWBuffer<uint> tb : register(u1);
RWTexture2D<int> tex : register(u2);
RWByteAddressBuffer rb : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint old, o2; int o3;
InterlockedAdd(cnt, 1, old);
InterlockedMax(mx[i & 3], (int)i);
InterlockedCompareExchange(cnt, 5, 6, o2);
InterlockedOr(sb[i], 2);
InterlockedMin(tb[i], i, o2);
InterlockedExchange(tex[uint2(i, 1)], 3, o3);
InterlockedCompareStore(sb[0], 1, 2);
sb[1] = old + o2 + o3;
}

View File

@ -1,10 +0,0 @@
// PROFILE: cs_6_0
// Memory barriers (device, group, all; with and without group sync).
// ZCHECK: call void @dx.op.barrier(i32 80, i32 10)
// ZCHECK: call void @dx.op.barrier(i32 80, i32 2)
RWStructuredBuffer<uint4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
AllMemoryBarrier(); AllMemoryBarrierWithGroupSync(); DeviceMemoryBarrier(); DeviceMemoryBarrierWithGroupSync(); GroupMemoryBarrier();
o[0] = uint4(firstbitlow(i), firstbithigh(i), firstbithigh((int)i), f32tof16(asfloat(i)));
o[1].x = asuint(f16tof32(i));
}

View File

@ -1,28 +0,0 @@
// PROFILE: cs_6_2
// Bitfields: DXIL packs same-size bitfields into one i32 (a, b, c share a
// word even though c is signed); reads mask/shift, writes read-modify-write.
// ZCHECK: and i32 {{.*}}, -249
// ZCHECK: or i32 {{.*}}, 56
// ZCHECK: ashr i32
struct Base { uint lo : 4; uint hi : 4; };
struct P : Base {
uint a : 3; uint b : 5; int c : 4;
uint d;
uint e : 30; uint f : 4;
uint sum() { return a + b + lo + hi; }
void bump() { b += 1; hi++; }
};
cbuffer CB { P cp; };
RWStructuredBuffer<P> sb : register(u0);
RWStructuredBuffer<int> o : register(u1);
[numthreads(1,1,1)] void main() {
P p = sb[0];
p.b = 7;
p.c = -3;
p.bump();
sb[1] = p;
P q = {1, 2, 3, 4, -5, 6, 7, 8};
sb[2] = q;
sb[3].f |= 2;
o[0] = p.a + p.c + cp.e + cp.f + p.sum() + q.c;
}

View File

@ -1,11 +0,0 @@
// PROFILE: cs_6_0
// Structured buffers of matrices: whole loads and stores, rows (constant
// and dynamic) and row components.
StructuredBuffer<float4x3> m : register(t0);
RWStructuredBuffer<float2x3> r : register(u1);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
o[i] = float4(m[i][1], 1) + r[i][0].x + float4(m[0][i % 4], m[1][2].y);
r[i] = r[i] * 2;
o[i + 1] = mul(float4(1, 2, 3, 4), m[i]).xyzz;
}

View File

@ -1,16 +0,0 @@
// PROFILE: cs_6_0
// Byte-address buffer loads, stores, atomics and sizes.
RWByteAddressBuffer rb : register(u0);
ByteAddressBuffer ro : register(t0);
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 v = ro.Load4(i * 16) + rb.Load2(4).xyxy;
rb.Store3(i * 12, v.xyz);
uint old; rb.InterlockedAdd(0, 1, old);
rb.InterlockedCompareStore(8, 1, 2);
uint n = 0;
rb.Store(20, n + old);
uint w; rb.GetDimensions(w); rb.Store(16, w);
}

View File

@ -1,20 +0,0 @@
// PROFILE: cs_6_2
// FLAGS: -enable-16bit-types
// Templated byte-address Load/Store of structs, matrices (by row in
// DXIL), 16- and 64-bit components (two words before SM 6.3); locals with
// components of several sizes in struct-typed memory.
// ZCHECK: call double @dx.op.makeDouble.f64(i32 101
// ZCHECK: rawBufferLoad.f16
struct S { float a; double b; uint16_t c; int2 d; };
RWByteAddressBuffer buf : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
S s = buf.Load<S>(i * 32);
float3x2 m = buf.Load<float3x2>(64);
half4 h = buf.Load<half4>(128);
S arr[2] = buf.Load<S[2]>(256);
s.a += m[1][0] + h.y + arr[1].d.x;
buf.Store<S>(i * 32 + 512, s);
buf.Store<float3x2>(96, m);
buf.Store<half4>(136, h);
buf.Store<double>(160, s.b);
}

View File

@ -1,60 +0,0 @@
#!/bin/sh
# DXIL output checks beyond validation: for each test/dxil/*.hlsl, zdxc's
# signature tables (ISG1/OSG1 and PSV0, minus the "Used" column) must match
# dxc's, and every `// ZCHECK: text` line must appear in zdxc's disassembly
# (`{{.*}}` matches anything).
#
# Usage: test/dxil/check.sh <path-to-zdxc>
set -u
ZDXC=$1
DXC_BUILD=${DXC_BUILD:-../build}
DXC=$DXC_BUILD/bin/dxc
DXV=$DXC_BUILD/bin/dxv
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0
fail=0
# Signature table rows, cut before the "Used" column.
sigtables() {
awk '/^; (Input|Output|Patch Constant) signature:/ { on = 1; seen = 0; next }
on && /^; (-|Name|shader hash)/ { next }
on && /^;$/ { if (seen) on = 0; next }
on { print substr($0, 1, 63); seen = 1 }' "$1" | sed 's/ *$//'
}
for f in test/dxil/*.hlsl; do
profile=$(sed -n 's|^// PROFILE: *||p' "$f")
flags=$(sed -n 's|^// FLAGS: *||p' "$f")
name=$(basename "$f" .hlsl)
if ! "$ZDXC" -T "$profile" $flags "$f" -Fo "$TMP/z.dxo" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue
fi
if ! "$DXV" "$TMP/z.dxo" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: dxv rejected the output"; head -3 "$TMP/log"; continue
fi
"$DXC" -dumpbin "$TMP/z.dxo" > "$TMP/z.ll" 2>&1
rm -f "$TMP/d.ll"
if ! "$DXC" -T "$profile" $flags "$f" -Fc "$TMP/d.ll" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: dxc rejects this test"; head -3 "$TMP/log"; continue
fi
ok=1
sigtables "$TMP/z.ll" > "$TMP/z.sig"
sigtables "$TMP/d.ll" > "$TMP/d.sig"
if ! diff "$TMP/d.sig" "$TMP/z.sig" > "$TMP/diff"; then
ok=0; echo "FAIL $name: signatures differ from dxc (< dxc, > zdxc)"; head -10 "$TMP/diff"
fi
# Runtime data (libraries) and root signatures must match dxc byte for byte.
"$DXC" -T "$profile" $flags "$f" -Fo "$TMP/d.dxo" > /dev/null 2>&1
if ! python3 test/dxil/compare_parts.py "$TMP/d.dxo" "$TMP/z.dxo" > "$TMP/rdat" 2>&1; then
ok=0; echo "FAIL $name: RDAT / RTS0 differ from dxc"; head -10 "$TMP/rdat"
fi
sed -n 's|^// ZCHECK: *||p' "$f" > "$TMP/checks"
while IFS= read -r pat; do
re=$(printf '%s\n' "$pat" | sed -e 's/[][\.*^$()+?|{}]/\\&/g' -e 's/\\{\\{\\\.\\\*\\}\\}/.*/g')
grep -Eq -- "$re" "$TMP/z.ll" || { ok=0; echo "FAIL $name: missing '$pat'"; }
done < "$TMP/checks"
if [ $ok = 1 ]; then pass=$((pass + 1)); else fail=$((fail + 1)); fi
done
echo "dxil checks: $pass passed, $fail failed"
[ "$fail" -eq 0 ]

View File

@ -1,23 +0,0 @@
"""Exits non-zero if two DXIL containers' RDAT or RTS0 parts differ (or
only one has one). Usage: compare_parts.py <expected.dxo> <actual.dxo>"""
import struct
import sys
def part(path, fourcc):
data = open(path, 'rb').read()
count = struct.unpack_from('<I', data, 28)[0]
for off in struct.unpack_from('<%dI' % count, data, 32):
if data[off:off + 4] == fourcc:
size = struct.unpack_from('<I', data, off + 4)[0]
return data[off + 8:off + 8 + size]
return None
status = 0
for fourcc in (b'RDAT', b'RTS0'):
a, b = part(sys.argv[1], fourcc), part(sys.argv[2], fourcc)
if a != b:
print('%s: expected %s bytes, got %s' % (fourcc.decode(), None if a is None else len(a), None if b is None else len(b)))
status = 1
sys.exit(status)

View File

@ -1,6 +0,0 @@
// PROFILE: cs_6_6
// Implicit-LOD sampling and derivatives in a compute shader (SM 6.6).
Texture2D<float4> t : register(t0);
SamplerState s : register(s0);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(8,8,1)] void main(uint2 id : SV_DispatchThreadID) { float2 uv = id / 64.0; o[id.x] = t.Sample(s, uv) + ddx(uv).x + t.CalculateLevelOfDetail(s, uv); }

View File

@ -1,12 +0,0 @@
// PROFILE: cs_6_0
// ConstantBuffer<T>: members (bitfields too), arrays, whole-struct reads,
// passing elements of resource arrays to (nested) functions.
// ZCHECK: cbufferLoadLegacy
struct S { float4 a; float b; uint lo : 8; uint hi : 8; };
ConstantBuffer<S> cbs[4] : register(b0);
Texture2D<float4> texs[2] : register(t0);
SamplerState smp : register(s0);
RWStructuredBuffer<float4> o : register(u0);
float4 inner(ConstantBuffer<S> c, Texture2D<float4> t) { return c.a * t.SampleLevel(smp, float2(0,0), 0) + c.hi; }
float4 outer(ConstantBuffer<S> c, Texture2D<float4> t) { return inner(c, t) + c.lo; }
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) { S s = cbs[2]; o[0] = outer(cbs[3], texs[1]) + outer(cbs[0], texs[0]) + cbs[i].a + s.b + s.lo; }

View File

@ -1,8 +0,0 @@
// PROFILE: cs_6_0
// Counters and Append/Consume buffers.
// ZCHECK: @dx.op.bufferUpdateCounter(i32 70, {{.*}}, i8 1)
// ZCHECK: @dx.op.bufferUpdateCounter(i32 70, {{.*}}, i8 -1)
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(1,1,1)] void main() { uint n = c.IncrementCounter(); ap.Append(co.Consume() + n); }

View File

@ -1,14 +0,0 @@
// PROFILE: cs_6_6
// Descriptor heaps (SM 6.6): resources and samplers taken from the heaps.
// ZCHECK: call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218
// ZCHECK: createHandleFromHeap(i32 218, i32 {{.*}}, i1 false, i1 true)
struct S { float4 a; float b; };
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
ConstantBuffer<S> c = ResourceDescriptorHeap[i];
Texture2D<float4> t = ResourceDescriptorHeap[i + 1];
SamplerState s = SamplerDescriptorHeap[0];
RWStructuredBuffer<float4> b = ResourceDescriptorHeap[NonUniformResourceIndex(i + 2)];
o[0] = c.a + t.SampleLevel(s, float2(0,0), 0);
b[i] = c.b;
}

View File

@ -1,22 +0,0 @@
// PROFILE: ds_6_0
// Domain shader: control points, patch constants, the domain location.
// ZCHECK: call float @dx.op.domainLocation.f32(i32 105, i8 1)
// ZCHECK: call float @dx.op.loadPatchConstant.f32(i32 104
struct HSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
struct PC {
float edges[4] : SV_TessFactor;
float inside[2] : SV_InsideTessFactor;
float3 extra : EXTRA;
uint id : PATCHID;
};
struct DSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : PATCHID; };
[domain("quad")]
DSOut main(PC pc, float2 uv : SV_DomainLocation, const OutputPatch<HSOut, 4> patch, uint prim : SV_PrimitiveID) {
DSOut o;
float4 a = lerp(patch[0].pos, patch[1].pos, uv.x);
float4 b = lerp(patch[3].pos, patch[2].pos, uv.x);
o.pos = lerp(a, b, uv.y) + float4(pc.extra, pc.inside[1]);
o.uv = patch[0].uv * pc.edges[3];
o.id = pc.id + prim;
return o;
}

View File

@ -1,6 +0,0 @@
// PROFILE: ps_6_0
// Gather with four offsets: four gathers (DXIL), ConstOffsets (SPIR-V).
// ZCHECK: textureGather.f32(i32 73, {{.*}}, i32 -1, i32 0, i32 1)
Texture2D<float4> t : register(t0);
SamplerState s : register(s0);
float4 main(float2 uv : UV) : SV_Target { return t.GatherGreen(s, uv, int2(1,0), int2(0,1), int2(-1,0), int2(0,-1)); }

View File

@ -1,13 +0,0 @@
// PROFILE: gs_6_0
// Geometry shader: per-vertex inputs, shadow SV_PrimitiveID, streams.
// ZCHECK: @dx.op.emitStream(i32 97, i8 0)
// ZCHECK: @dx.op.cutStream(i32 98, i8 0)
// ZCHECK: @dx.op.gsInstanceID.i32(i32 100)
// ZCHECK: !{i32 3, i32 6, i32 1, i32 5, i32 2}
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
struct GSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; uint layer : SV_RenderTargetArrayIndex; };
[maxvertexcount(6)] [instance(2)]
void main(triangle VSOut input[3], uint pid : SV_PrimitiveID, uint iid : SV_GSInstanceID, inout TriangleStream<GSOut> stream) {
for (int k = 0; k < 3; k++) { GSOut o; o.pos = input[k].pos; o.uv = input[k].uv + pid; o.layer = iid; stream.Append(o); }
stream.RestartStrip();
}

View File

@ -1,6 +0,0 @@
// PROFILE: cs_6_0
// Groupshared memory: address-space-3 globals, and the PSV byte count.
// ZCHECK: @g = external addrspace(3) global [64 x float], align 4
groupshared float g[64];
RWStructuredBuffer<float> o : register(u0);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) { g[i] = i; GroupMemoryBarrierWithGroupSync(); o[i] = g[63 - i]; }

View File

@ -1,36 +0,0 @@
// PROFILE: hs_6_0
// Hull shader: control points in and out, a patch constant function
// reading the input patch and the output control points.
// ZCHECK: call i32 @dx.op.outputControlPointID.i32(i32 107)
// ZCHECK: call void @dx.op.storePatchConstant.f32(i32 106
// ZCHECK: call float @dx.op.loadOutputControlPoint.f32(i32 103
struct VSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
struct HSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
struct PC {
float edges[4] : SV_TessFactor;
float inside[2] : SV_InsideTessFactor;
float3 extra : EXTRA;
uint id : PATCHID;
};
cbuffer CB { float tess; };
PC patchConst(InputPatch<VSOut, 4> ip, const OutputPatch<HSOut, 4> op, uint pid : SV_PrimitiveID) {
PC o;
[unroll] for (int i = 0; i < 4; i++) o.edges[i] = tess + i;
o.inside[0] = ip[0].pos.x;
o.inside[1] = op[3].uv.y;
o.extra = ip[1].pos.xyz + op[2].pos.xyz;
o.id = pid;
return o;
}
[domain("quad")]
[partitioning("fractional_even")]
[outputtopology("triangle_ccw")]
[outputcontrolpoints(4)]
[patchconstantfunc("patchConst")]
[maxtessfactor(32.0)]
HSOut main(InputPatch<VSOut, 4> ip, uint id : SV_OutputControlPointID) {
HSOut o;
o.pos = ip[id].pos * 2;
o.uv = ip[id].uv;
return o;
}

View File

@ -1,12 +0,0 @@
// PROFILE: hs_6_0
// Isoline hull shader: line tess factors (density, detail); the main
// function declares the input patch but does not read it.
struct CP { float3 p : P; };
struct PC { float f[2] : SV_TessFactor; };
PC pcf(InputPatch<CP, 2> ip) { PC o; o.f[0] = ip[0].p.x; o.f[1] = ip[1].p.y; return o; }
[domain("isoline")]
[partitioning("integer")]
[outputtopology("line")]
[outputcontrolpoints(2)]
[patchconstantfunc("pcf")]
CP main(InputPatch<CP, 2> ip, uint id : SV_OutputControlPointID) { CP c; c.p = float3(id, 0, 1); return c; }

View File

@ -1,18 +0,0 @@
// PROFILE: ps_6_6
// Intrinsics: firstbit*, f32tof16/f16tof32, and/or/select, isnan & co.,
// fmod, integer dot, any/all, fine derivatives, clip, IsHelperLane.
// ZCHECK: unaryBits.i32(i32 34
// ZCHECK: legacyF32ToF16
// ZCHECK: isHelperLane
RWStructuredBuffer<uint4> o : register(u0);
float4 main(float4 p : SV_Position, uint i : U) : SV_Target {
DeviceMemoryBarrier();
o[0] = uint4(firstbitlow(i), firstbithigh(i), firstbithigh((int)i), f32tof16(p.x));
int3 a = int3(1, 2, i), b = int3(3, i, 5);
bool3 m = and(a > 1, b < 4);
bool3 n = or(m, isnan(p.xyz));
float3 s = select(n, p.xyz, float3(1, 2, 3));
float r = fmod(p.x, 3) + f16tof32(i) + dot(a, b) + any(isinf(p)) + all(isfinite(p)) + isnormal(p.w) + ddx_fine(p.x) + ddy_fine(p.y);
clip(p.xy - 1);
return float4(s, r) + IsHelperLane();
}

View File

@ -1,21 +0,0 @@
// PROFILE: lib_6_6
// Graphics shaders in a library: entries with their signatures (no usage
// masks), stage state, and the patch constant function defined under its
// mangled name in declaration order. RDAT is checked against dxc's.
// ZCHECK: define void @"\01?pcf@@YA?AUPC@@V?$InputPatch@UCP@@$02@@@Z"()
// ZCHECK: define void @hs()
// ZCHECK: !{i32 8, i32 2, i32 1, !{{.*}}, i32 5, !{{.*}}}
struct CP { float4 p : POSITION; };
struct PC { float e[3] : SV_TessFactor; float i : SV_InsideTessFactor; };
PC pcf(InputPatch<CP, 3> ip) { PC o; o.e[0] = o.e[1] = o.e[2] = 2; o.i = 2; return o; }
[shader("hull")] [domain("tri")] [partitioning("integer")] [outputtopology("triangle_cw")] [outputcontrolpoints(3)] [patchconstantfunc("pcf")]
CP hs(InputPatch<CP, 3> ip, uint id : SV_OutputControlPointID) { return ip[id]; }
[shader("domain")] [domain("tri")]
float4 ds(PC pc, float3 uvw : SV_DomainLocation, const OutputPatch<CP, 3> op) : SV_Position { return op[0].p * uvw.x + op[1].p * uvw.y + op[2].p * uvw.z; }
struct GO { float4 p : SV_Position; };
[shader("geometry")] [maxvertexcount(3)]
void gs(triangle float4 v[3] : SV_Position, inout TriangleStream<GO> s) { for (int k = 0; k < 3; k++) { GO o; o.p = v[k]; s.Append(o); } }
Texture2D t; SamplerState s;
struct V { float4 p : SV_Position; float2 uv : TEXCOORD; };
[shader("vertex")] V vs(float3 p : POSITION, float2 uv : TEXCOORD) { V o; o.p = float4(p, 1); o.uv = uv; return o; }
[shader("pixel")] float4 ps(V i) : SV_Target { return t.Sample(s, i.uv); }

View File

@ -1,12 +0,0 @@
// PROFILE: ps_6_0
// Math intrinsics lowered to arithmetic, as dxc does.
// ZCHECK: @dx.op.unary.f32(i32 17,
// ZCHECK: @dx.op.isSpecialFloat.f32(i32 8,
// ZCHECK: @dx.op.unary.f32(i32 22,
float4 main(float3 a : A, float3 b : B, float2 c : C, float4x4 m : M, float3x3 m3 : N) : SV_Target {
float3 r = cross(a, b) + reflect(a, b) + refract(a, b, c.x) + faceforward(a, b, a);
float s = atan2(c.x, c.y) + fmod(c.x, c.y) + distance(a, b) + determinant(m) + determinant(m3);
s += smoothstep(0, 1, c.x) + step(0.5, c.y) + degrees(c.x) + radians(c.y) + ldexp(c.x, c.y);
int sg = sign(c.x) + sign((int)c.y);
return float4(r, s + sg + (isnan(c.x) ? 1 : 0) + (isinf(c.y) ? 2 : 0) + (isfinite(a.x) ? 4 : 0));
}

View File

@ -1,27 +0,0 @@
// PROFILE: ms_6_5
// Mesh shader: vertex and primitive outputs written per element, indices,
// partial (swizzled) output writes, the payload.
// ZCHECK: call void @dx.op.setMeshOutputCounts(i32 168
// ZCHECK: call void @dx.op.emitIndices(i32 169
// ZCHECK: call void @dx.op.storePrimitiveOutput.i32(i32 172
// ZCHECK: getMeshPayload
struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float c[2] : COLOR; };
struct P { nointerpolation uint id : PRIMID; bool cull : SV_CullPrimitive; };
struct Payload { uint base; float scale[3]; };
[numthreads(4,1,1)]
[outputtopology("triangle")]
void main(out indices uint3 tris[2], out vertices V verts[4], out primitives P prims[2], in payload Payload pl, uint tid : SV_GroupIndex) {
SetMeshOutputCounts(4, 2);
verts[tid].pos = float4(tid, 0, 0, 1) * pl.scale[tid % 3];
verts[tid].uv.y = 1;
verts[tid].uv.x = 0;
verts[tid].c[1] = 2;
verts[tid].c[0] = 3;
if (tid < 2) {
tris[tid] = uint3(0, tid + 1, tid + 2);
P p;
p.id = pl.base + tid;
p.cull = tid == 1;
prims[tid] = p;
}
}

View File

@ -1,16 +0,0 @@
// PROFILE: cs_6_0
// Operator overloading: binary operators, [] and () (dxc's subset).
struct V2 {
float x, y;
V2 operator+(V2 o) { V2 r; r.x = x + o.x; r.y = y + o.y; return r; }
V2 operator*(float k) { V2 r; r.x = x * k; r.y = y * k; return r; }
bool operator==(V2 o) { return x == o.x && y == o.y; }
float operator[](uint i) { return i == 0 ? x : y; }
float operator()(float a, float b) { return x * a + y * b; }
};
RWStructuredBuffer<float> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_DispatchThreadID) {
V2 a; a.x = 1; a.y = 2; V2 b = a * 3.0;
V2 c = a + b; c = c + a;
o[i] = c[1] + c(1, 2) + (a == a ? 1 : 0);
}

View File

@ -1,12 +0,0 @@
// PROFILE: ps_6_0
// Intrinsics with out parameters.
// ZCHECK: @dx.op.splitDouble.f64(i32 102
// ZCHECK: @dx.op.unary.f32(i32 29,
double d;
float4 main(float4 x : X) : SV_Target {
float4 s, c; sincos(x, s, c);
float3 ip; float3 fr = modf(x.xyz, ip);
float e; float m = frexp(x.w, e);
uint lo, hi; asuint(d, lo, hi);
return s + c + float4(fr + ip, m * e) + lo + hi;
}

View File

@ -1,39 +0,0 @@
// PROFILE: cs_6_5
// FLAGS: -E main
// RayQuery: allocated once in the prologue, its type flags as the
// allocation's constant flags; state reads by row / column / component.
// ZCHECK: call i32 @dx.op.allocateRayQuery(i32 178, i32 1)
// ZCHECK: @dx.op.rayQuery_TraceRayInline(i32 179
// ZCHECK: @dx.op.rayQuery_Proceed.i1(i32 180
// ZCHECK: @dx.op.rayQuery_StateScalar.i32(i32 185
// ZCHECK: @dx.op.rayQuery_StateVector.f32(i32 194, i32 {{.*}}, i8 1)
// ZCHECK: @dx.op.rayQuery_StateMatrix.f32(i32 188, i32 {{.*}}, i32 0, i8 3)
// ZCHECK: @dx.op.rayQuery_Abort(i32 181
// ZCHECK: i32 16, i32 0, !{{.*}}
RaytracingAccelerationStructure scene : register(t0);
RWStructuredBuffer<float4> output : register(u0);
void start(RayQuery<RAY_FLAG_FORCE_OPAQUE> q, RayDesc ray) {
q.TraceRayInline(scene, RAY_FLAG_NONE, 0xFF, ray);
}
[numthreads(8, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
RayDesc ray = { float3(id), 0.0, float3(0, 0, 1), 100.0 };
RayQuery<RAY_FLAG_FORCE_OPAQUE> q;
start(q, ray);
while (q.Proceed()) {
if (q.CandidateType() == CANDIDATE_NON_OPAQUE_TRIANGLE)
q.CommitNonOpaqueTriangleHit();
else
q.CommitProceduralPrimitiveHit(q.RayTMin());
}
float4 r = 0;
if (q.CommittedStatus() == COMMITTED_TRIANGLE_HIT) {
r.xy = q.CommittedTriangleBarycentrics();
r.z = q.CommittedRayT() + q.CommittedInstanceIndex();
r.w = q.CommittedObjectToWorld4x3()[3][0];
}
q.Abort();
output[id.x] = r;
}

View File

@ -1,66 +0,0 @@
// PROFILE: lib_6_5
// Ray tracing shaders in a library: mangled entry functions taking their
// payload / attributes by pointer, resources as globals with handles from
// createHandleForLib, and RDAT matching dxc's.
// ZCHECK: define void @"\01?chit@@YAXUPayload@@UBuiltInTriangleIntersectionAttributes@@@Z"(%struct.Payload*
// ZCHECK: @dx.op.createHandleForLib.struct.RaytracingAccelerationStructure(i32 160
// ZCHECK: call void @dx.op.traceRay.struct.Payload(i32 157
// ZCHECK: call void @dx.op.callShader.struct.CallData(i32 159
// ZCHECK: call i1 @dx.op.reportHit.struct.Attr(i32 158
// ZCHECK: call void @dx.op.ignoreHit(i32 155)
// ZCHECK: call float @dx.op.objectToWorld.f32(i32 151, i32 0, i8 3)
// ZCHECK: !{i32 8, i32 10, i32 6, i32 20, i32 7, i32 8, i32 5, !{{.*}}}
struct Payload { float4 color; uint depth; };
struct Attr { float2 bary; };
struct CallData { float3 v; };
RaytracingAccelerationStructure scene : register(t0);
RWTexture2D<float4> output : register(u0);
[shader("raygeneration")]
void rgen() {
uint2 id = DispatchRaysIndex().xy;
float2 uv = (float2(id) + 0.5) / float2(DispatchRaysDimensions().xy);
RayDesc ray;
ray.Origin = float3(uv, 0);
ray.Direction = float3(0, 0, 1);
ray.TMin = 0.001;
ray.TMax = 1000;
Payload p = { float4(0, 0, 0, 0), 0 };
TraceRay(scene, RAY_FLAG_FORCE_OPAQUE, 0xFF, 0, 1, 0, ray, p);
CallData c = { p.color.rgb };
CallShader(0, c);
output[id] = float4(c.v, 1);
}
[shader("closesthit")]
void chit(inout Payload p, in BuiltInTriangleIntersectionAttributes a) {
float3x4 m = ObjectToWorld3x4();
p.color = float4(a.barycentrics, RayTCurrent(), m[0][3]) + WorldRayDirection().xyzz;
p.depth = InstanceID() + PrimitiveIndex() + HitKind() + GeometryIndex();
}
[shader("miss")]
void miss(inout Payload p) {
p.color = float4(WorldRayOrigin(), RayTMin());
}
[shader("anyhit")]
void ahit(inout Payload p, in Attr a) {
if (a.bary.x > 0.5)
IgnoreHit();
if (RayFlags() & RAY_FLAG_CULL_BACK_FACING_TRIANGLES)
AcceptHitAndEndSearch();
p.depth += 1;
}
[shader("intersection")]
void isect() {
Attr a = { ObjectRayOrigin().xy };
ReportHit(RayTCurrent() * 0.5, 0, a);
}
[shader("callable")]
void call(inout CallData c) {
c.v *= 2;
}

View File

@ -1,14 +0,0 @@
// PROFILE: ps_6_0
// Resource arrays are register ranges; elements get handles where used.
// ZCHECK: createHandle(i32 57, i8 0, i32 0, i32 3, i1 false)
// ZCHECK: createHandle(i32 57, i8 0, i32 0, i32 {{.*}}, i1 true)
// ZCHECK: ]* undef, !"", i32 0, i32 1, i32 4, i32 2, i32 0,
// ZCHECK: [2 x %struct.SamplerState]* undef
Texture2D ts[4] : register(t1);
SamplerState ss[2] : register(s0);
RWStructuredBuffer<float> bufs[3] : register(u0);
float4 main(float2 uv : UV, uint i : I) : SV_Target {
float4 c = ts[2].Sample(ss[1], uv) + ts[NonUniformResourceIndex(i)].Sample(ss[0], uv);
bufs[1][0] = c.x;
return c + bufs[i][3];
}

View File

@ -1,10 +0,0 @@
// PROFILE: ps_6_0
// Resources passed to functions and held in locals (inlined to handles).
// ZCHECK: @dx.op.sample.f32(i32 60
Texture2D<float4> t0 : register(t0);
Texture2D<float4> t1 : register(t1);
SamplerState s : register(s0);
StructuredBuffer<float> b0 : register(t2);
float4 tap(Texture2D<float4> t, SamplerState ss, float2 uv) { return t.Sample(ss, uv); }
float rd(StructuredBuffer<float> b, uint i) { return b[i]; }
float4 main(float2 uv : UV) : SV_Target { Texture2D<float4> loc = t1; return tap(t0, s, uv) + tap(loc, s, uv * 2) + rd(b0, 3); }

View File

@ -1,10 +0,0 @@
// PROFILE: ps_6_0
// Root signatures from the RootSignature attribute (a macro of
// concatenated strings): an RTS0 part matching dxc's (version 1.1).
// ZCHECK: define void @main()
#define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \
"CBV(b0), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0)"
cbuffer C : register(b0) { float4 k; };
Texture2D t : register(t0); SamplerState s : register(s0);
[RootSignature(RS)]
float4 main(float2 uv : TEXCOORD) : SV_Target { return t.Sample(s, uv) * k; }

View File

@ -1,15 +0,0 @@
// PROFILE: ps_6_6
// Rasterizer-ordered views and globallycoherent UAVs: resource metadata,
// annotateHandle properties and the ROVs shader flag.
// ZCHECK: Raster Ordered UAVs
// ZCHECK: ResourceProperties { i32 20491, i32 0 }
// ZCHECK: ResourceProperties { i32 12290, i32 1033 }
// ZCHECK: i32 2, i1 false, i1 false, i1 true,
// ZCHECK: i32 11, i1 true, i1 false, i1 false,
globallycoherent RWByteAddressBuffer buffer1 : register(u0);
RasterizerOrderedTexture2D<float4> rov : register(u1);
float4 main(float4 p : SV_Position) : SV_Target {
rov[uint2(p.xy)] += buffer1.Load(0);
return rov[uint2(p.xy)];
}

View File

@ -1,2 +0,0 @@
// PROFILE: vs_6_0
float4 main() : SV_Position { return 1; }

View File

@ -1,5 +0,0 @@
// PROFILE: vs_6_0
// Return value first, then parameters; inout packs its output side; clip
// distances and matrices span rows.
struct O { float4 a : A; float2 b[2] : B; };
float4 main(in float3 x : X, out float y : Y, inout float2 z : Z, float4x2 m : M, row_major float2x3 rm : RM, out O o, uint iid : SV_InstanceID, out float4 p : SV_Position, out float cd[2] : SV_ClipDistance) : R { y = x.x; z += 1; o.a = m[0].xyxy+rm[0].xyzx; o.b[0] = 1; o.b[1] = iid; p = 1; cd[0]=1; cd[1]=2; return 2; }

View File

@ -1,5 +0,0 @@
// PROFILE: ps_6_0
// ZCHECK: call void @dx.op.discard(i32 82, i1 true)
// ZCHECK: @dx.op.unary.f32(i32 83,
struct PSIn { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : TEXCOORD1; float3 n : NORMAL; };
float4 main(PSIn i, bool ff : SV_IsFrontFace) : SV_Target { if (i.uv.x < 0) discard; return float4(i.n * (ff ? 1 : -1), i.uv.y + i.id + ddx(i.uv.x)); }

View File

@ -1,4 +0,0 @@
// PROFILE: ps_6_0
// Interpolation modifiers, shadow (SV_SampleIndex) and unpacked outputs.
// ZCHECK: @dx.op.sampleIndex.i32(i32 90)
float4 main(float4 p : SV_Position, centroid float c : C, noperspective float2 np : NP, sample float s : S, uint pid : SV_PrimitiveID, uint si : SV_SampleIndex, out float d : SV_Depth, out float4 t1 : SV_Target1, out uint cov : SV_Coverage) : SV_Target0 { d = 0.5; t1 = 1; cov = 3; return c + np.x + pid + si + s+p.x; }

View File

@ -1,15 +0,0 @@
// PROFILE: ps_6_0
// SV_Target arrays split into one element per render target.
uint i;
float4 main(int4 a : A, out float4 o[2] : SV_TARGET, out float4 o2[2][2] : SV_TARGET2) : SV_TARGET7
{
o[0] = a+2;
o[1] = a+3;
o[i] = a+10;
o2[0][0] = a+5;
o2[0][1] = a+6;
o2[1][0] = a+7;
o2[1][1] = a+8;
o2[i][i] = a + 12;
return a + 16;
}

View File

@ -1,5 +0,0 @@
// PROFILE: vs_6_0
// bool and min16float elements.
// ZCHECK: @dx.op.loadInput.f16(
struct O { float4 p : SV_Position; bool b : B; min16float h : H; int2 i : I; };
O main(bool bi : BI, min16float2 hi : HI, float4 v : SV_Position) { O o; o.p = v; o.b = bi; o.h = hi.x; o.i = 3; return o; }

View File

@ -1,5 +0,0 @@
// PROFILE: vs_6_0
cbuffer C : register(b0) { float4x4 mvp; };
struct VSIn { float3 pos : POSITION; float2 uv : TEXCOORD0; float3 n : NORMAL; uint id : SV_VertexID; };
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : TEXCOORD1; float3 n : NORMAL; };
VSOut main(VSIn i) { VSOut o; o.pos = mul(mvp, float4(i.pos, 1)); o.uv = i.uv; o.id = i.id; o.n = i.n; return o; }

View File

@ -1,8 +0,0 @@
// PROFILE: vs_6_0
// Static globals are initialized on entry; float constants keep their value.
// ZCHECK: store float 3.000000e+00
// ZCHECK: store float 5.000000e+00
// ZCHECK: fadd float {{.*}}, 1.500000e+00
static const float2 offs[2] = { float2(1, 2), float2(3, 4) };
static float g = 5;
float4 main(uint id : SV_VertexID) : SV_Position { g += 1.5; return float4(offs[id], g, 1); }

View File

@ -1,5 +0,0 @@
// PROFILE: cs_6_0
// Static locals: private globals initialized on entry.
RWStructuredBuffer<int> o : register(u0);
int next() { static int counter = 10; counter += 1; return counter; }
[numthreads(1,1,1)] void main() { static const float k[3] = {1, 2, 3}; o[0] = next() + next() + (int)k[2]; }

View File

@ -1,16 +0,0 @@
// PROFILE: ps_6_0
// Status arguments (sparse feedback) and CheckAccessFullyMapped.
// ZCHECK: checkAccessFullyMapped.i32(i32 71
Texture2D<float4> t : register(t0);
Buffer<float4> b : register(t2);
SamplerState s : register(s0);
float4 main(float2 uv : UV) : SV_Target {
uint st0, st1, st6;
float4 a = t.Sample(s, uv, int2(1, 0), 0.5, st0);
if (!CheckAccessFullyMapped(st0)) a = 0;
float4 l = t.Load(int3(1, 2, 0), int2(0, 0), st1);
bool m = CheckAccessFullyMapped(st1);
float4 bb = b.Load(3, st6);
bool n = CheckAccessFullyMapped(st6);
return a + (m ? l : 1) + (n ? bb : 2);
}

View File

@ -1,14 +0,0 @@
// PROFILE: lib_6_5
// State object subobjects go to the RDAT subobject table (checked against
// dxc's RDAT).
// ZCHECK: define void @"\01?b@@YAXUP@@@Z"
StateObjectConfig soc = { STATE_OBJECT_FLAGS_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITONS };
SubobjectToExportsAssociation sea = { "rsc", "a;b;foo;c" };
SubobjectToExportsAssociation sea2 = { "rsc", ";" };
RaytracingShaderConfig rsc = { 128, 64 };
RaytracingPipelineConfig rpc = { 512 };
TriangleHitGroup trHitGt = { "a", "b" };
ProceduralPrimitiveHitGroup ppHitGt = { "a", "b", "c"};
RaytracingPipelineConfig1 rpc1 = { 32, RAYTRACING_PIPELINE_FLAG_SKIP_TRIANGLES };
struct P { float4 c; };
[shader("miss")] void b(inout P p) { p.c = 1; }

View File

@ -1,6 +0,0 @@
// PROFILE: ps_6_8
// Pixel system values: clip distances in, barycentrics, coverage in and
// out, ViewID, shading rate, stencil ref.
struct I { float4 pos : SV_Position; float2 c0 : SV_ClipDistance0; float c1 : SV_ClipDistance1; noperspective float3 b2 : SV_Barycentrics1; };
struct O { float4 c : SV_Target; uint cov : SV_Coverage; uint st : SV_StencilRef; };
O main(I i, float3 b : SV_Barycentrics, uint cov : SV_Coverage, uint v : SV_ViewID, uint sr : SV_ShadingRate) { O o; o.c = float4(b + i.b2, i.c0.y + i.c1 + v + sr); o.cov = cov; o.st = 1; return o; }

View File

@ -1,5 +0,0 @@
// PROFILE: vs_6_8
// Vertex system values: clip/cull distances, ViewID, start vertex and
// instance, viewport / render target index, shading rate.
struct O { float4 pos : SV_Position; float2 c0 : SV_ClipDistance0; float c1 : SV_ClipDistance1; float cu : SV_CullDistance; uint vp : SV_ViewportArrayIndex; uint rt : SV_RenderTargetArrayIndex; uint sr : SV_ShadingRate; };
O main(uint v : SV_ViewID, uint sv : SV_StartVertexLocation, uint si : SV_StartInstanceLocation) { O o = (O)0; o.pos = v + sv + si; o.c0 = 1; o.c1 = 2; return o; }

View File

@ -1,18 +0,0 @@
// PROFILE: cs_6_0
// switch: fallthrough, default, break, continue to the enclosing loop.
// ZCHECK: switch i32 {{.*}}, label
RWStructuredBuffer<int> o : register(u0);
[numthreads(4,1,1)] void main(uint i : SV_GroupIndex) {
int r = 0;
for (int k = 0; k < 3; k++) {
switch (i + k) {
case 0: r += 1; break;
case 1:
case 2: r += 2;
case 3: r += 3; break;
default: if (r > 4) continue; r -= 1;
}
}
switch (r) { case 7: o[1] = 7; }
o[i] = r;
}

View File

@ -1,9 +0,0 @@
// PROFILE: cs_6_0
// tbuffer blocks and TextureBuffer<S>: TBuffer SRVs read a register at a
// time (cbuffer layout).
// ZCHECK: call %dx.types.ResRet.i32 @dx.op.bufferLoad.i32(i32 68
struct S { float4 a; float b; float3 c; };
tbuffer TB : register(t0) { float4 x; float y; S s; };
TextureBuffer<S> tbs : register(t1);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main() { o[0] = x * y + s.a + tbs.a * tbs.b + float4(tbs.c, 1); }

View File

@ -1,23 +0,0 @@
// PROFILE: cs_6_0
// Templates (function, class, variable; deduction, defaults, specializations) and methods.
template<typename T> T square(T x) { return x * x; }
template<typename T, int N> vector<T, N> scale(vector<T, N> v, T k) { return v * k; }
template<typename T> struct Pair { T a; T b; T sum() { return a + b; } };
template<typename T, uint N = 4> struct Arr { T v[N]; T get(uint i) { return v[i]; } };
template<typename T> T first(Pair<T> p) { return p.a; }
RWStructuredBuffer<float> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_DispatchThreadID) {
Pair<float> p; p.a = 1; p.b = 2;
Arr<int> a; a.v[0] = 3; a.v[1] = 4; a.v[2] = 5; a.v[3] = 6;
o[i] = square(2.0f) + square(3) + scale(float3(1, 2, 3), 2.0f).z + p.sum() + a.get(2) + first(p) + square<uint>(2);
}
template <class, class> static const bool is_same_v = false;
template <class T> static const bool is_same_v<T, T> = true;
template<typename T> struct Box { T v; };
template<> struct Box<int> { int v; int extra; };
struct Base { float b; float twice() { return b * 2; } };
struct Derived : Base { float d; };
[numthreads(1,1,1)] void more(uint i : SV_DispatchThreadID) {
Box<int> bi; bi.extra = 2; Derived dv; dv.b = 3;
o[i] = is_same_v<int, int> + is_same_v<int, float> + bi.extra + dv.twice();
}

View File

@ -1,43 +0,0 @@
// PROFILE: cs_6_0
// More templates: `S<T>::member`, partial specialization through
// matrix<T, N, M>, the injected class name, member function templates,
// SFINAE (enable_if), out-of-line member definitions (plain, static and
// of class templates), alias template deduction, argument-dependent
// lookup.
// ZCHECK: @dx.op.bufferStore.f32
template <bool C, typename T> struct enable_if {};
template <typename T> struct enable_if<true, T> { using type = T; };
template <typename M> struct traits;
template <typename T, int N, int K> struct traits<matrix<T, N, K> > {
static const uint Count = N * K;
};
namespace ns {
template <typename T, int N> struct Vec {
T v[N];
Vec scaled(T k);
template <int L> Vec Shifted() { Vec r; r.v = v; r.v[0] += L; return r; }
template <int L> static Vec Make(T x) { Vec r; for (int i = 0; i < N; i++) r.v[i] = x * L; return r; }
};
template <typename T, int N> Vec<T, N> Vec<T, N>::scaled(T k) {
Vec r; for (int i = 0; i < N; i++) r.v[i] = v[i] * k; return r;
}
template <typename T> using Vec2 = Vec<T, 2>;
template <typename T> T head(Vec2<T> x) { return x.v[0]; }
}
struct S { float a; float get(float k); static float twice(float x); };
float S::get(float k) { return a * k; }
float S::twice(float x) { return x * 2; }
template <typename T> typename enable_if<(sizeof(T) == 4), T>::type pick(T x) { return x; }
template <typename T> typename enable_if<(sizeof(T) == 8), T>::type pick(T x) { return x * 2; }
RWStructuredBuffer<float> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_DispatchThreadID) {
S s; s.a = 3;
ns::Vec2<float> v = ns::Vec2<float>::Make<3>(2);
ns::Vec<float, 2> g = v.scaled(2).Shifted<1>();
o[i] = traits<float2x3>::Count + s.get(2) + S::twice(1) + head(v) + g.v[0] + pick(1.0f);
}

View File

@ -1,37 +0,0 @@
// PROFILE: ps_6_0
// Texture and sampler operations; argument layout as dxc emits it.
// ZCHECK: @dx.op.sample.f32(i32 60, %dx.types.Handle {{.*}}, float {{.*}}, float undef, float undef, i32 1, i32 2, i32 undef, float undef)
// ZCHECK: @dx.op.sampleLevel.f32(i32 62,
// ZCHECK: @dx.op.sampleBias.f32(i32 61,
// ZCHECK: @dx.op.sampleGrad.f32(i32 63,
// ZCHECK: @dx.op.sampleCmp.f32(i32 64,
// ZCHECK: @dx.op.sampleCmpLevelZero.f32(i32 65,
// ZCHECK: @dx.op.textureLoad.f32(i32 66, %dx.types.Handle {{.*}}, i32 0, i32 1, i32 2, i32 undef, i32 undef, i32 undef, i32 undef)
// ZCHECK: @dx.op.textureLoad.i32(i32 66,
// ZCHECK: @dx.op.bufferLoad.f32(i32 68,
// ZCHECK: @dx.op.textureGather.f32(i32 73, {{.*}}, i32 1, i32 1, i32 1)
// ZCHECK: @dx.op.textureGatherCmp.f32(i32 74,
// ZCHECK: @dx.op.getDimensions(i32 72, %dx.types.Handle {{.*}}, i32 1)
// ZCHECK: @dx.op.calculateLOD.f32(i32 81,
// ZCHECK: @dx.op.textureStore.f32(i32 67,
// ZCHECK: !{i32 1, %struct.SamplerComparisonState* undef, !"", i32 0, i32 1, i32 1, i32 1, null}
Texture2D<float4> t2 : register(t0);
Texture2DArray<float> t2a : register(t1);
TextureCube tc : register(t2);
Texture2DMS<float4> tms : register(t3);
Texture3D<uint2> t3 : register(t4);
Buffer<float4> buf : register(t5);
RWTexture2D<float4> rw : register(u0);
SamplerState s : register(s0);
SamplerComparisonState sc : register(s1);
float4 main(float2 uv : UV) : SV_Target {
float4 r = t2.Sample(s, uv) + t2.Sample(s, uv, int2(1, 2)) + t2.SampleLevel(s, uv, 2) + t2.SampleBias(s, uv, 0.5) + t2.SampleGrad(s, uv, uv, uv);
r.x += t2a.SampleCmp(sc, float3(uv, 1), 0.5) + t2a.SampleCmpLevelZero(sc, float3(uv, 1), 0.5);
r += tc.Sample(s, uv.xyx) + t2.Load(int3(1, 2, 0)) + tms.Load(int2(1, 1), 2) + t3[uint3(1,2,3)].x + buf[3] + buf.Load(2);
r += t2.Gather(s, uv) + t2.GatherGreen(s, uv, int2(1, 1)) + t2a.GatherCmp(sc, float3(uv, 0), 0.5);
uint w, h, l; t2.GetDimensions(1, w, h, l);
float fw, fh; rw.GetDimensions(fw, fh);
r.x += w + h + l + fw + fh + t2.CalculateLevelOfDetail(s, uv);
rw[uint2(1, 2)] = r; r += rw[uint2(3,4)];
return r;
}

View File

@ -1,26 +0,0 @@
// PROFILE: ps_6_0
// Loops unroll so texel offsets become constants (as dxc requires).
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 -1, i32 -2, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 0, i32 -2, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 1, i32 -2, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 -1, i32 0, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 1, i32 2, i32 undef, float undef)
// ZCHECK: @dx.op.sampleLevel.f32(i32 62, {{.*}}, i32 -1, i32 0, i32 undef, float 0.000000e+00)
// ZCHECK: @dx.op.sampleLevel.f32(i32 62, {{.*}}, i32 2, i32 0, i32 undef, float 0.000000e+00)
Texture2D t : register(t0);
SamplerState s : register(s0);
static const int R = 1;
float4 main(float2 uv : UV, uint n : N) : SV_Target {
float4 c = 0;
// Nested loops whose offsets need constants, with a static const bound.
for (int y = -R; y <= R; y++)
for (int x = -R; x <= R; x++)
c += t.Sample(s, uv, int2(x, y * 2));
// [unroll] with a step other than one and a shifted offset.
[unroll] for (uint i = 0; i < 6; i += 3) c += t.SampleLevel(s, uv, 0, int2(i - 1, 0));
// Kept as loops: [loop], a break, a run-time bound.
[loop] for (int j = 0; j < 4; j++) c.x += j;
for (int k = 0; k < 4; k++) { if (c.y > 2) break; c.y += k; }
for (uint m = 0; m < n; m++) c.z += m;
return c;
}

View File

@ -1,14 +0,0 @@
// PROFILE: cs_6_0
// Wave and quad intrinsics, as dxc emits them.
// ZCHECK: @dx.op.waveActiveOp.i32(i32 119, i32 {{.*}}, i8 2, i8 1)
// ZCHECK: @dx.op.waveAllOp(i32 135
// ZCHECK: @dx.op.quadOp.f32(i32 123
RWStructuredBuffer<uint4> o : register(u0);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 b = WaveActiveBallot(i > 3);
int s = WaveActiveSum((int)i) + WavePrefixProduct((int)i) + WaveActiveMax((int)i);
uint u = WaveActiveMin(i) + WaveActiveBitXor(i) + WaveReadLaneAt(i, 2) + WaveReadLaneFirst(i) + WaveActiveCountBits(i > 1) + WavePrefixCountBits(i < 9);
bool f = WaveIsFirstLane() && WaveActiveAnyTrue(i == 0) && WaveActiveAllTrue(i < 100) && WaveActiveAllEqual(i);
float q = QuadReadAcrossX((float)i) + QuadReadLaneAt((float)i, 1);
o[i] = b + s + u + f + WaveGetLaneIndex() + WaveGetLaneCount() + (uint)q;
}

View File

@ -1,42 +0,0 @@
#!/bin/sh
# Command-line oracle: every dxc invocation in the DXC test corpus (the
# arguments of each `RUN: %dxc ...` line) must be understood by zdxc's
# dxc-compatible parser. Allowed outcomes: accepted, or rejected as an
# unsupported dxc feature. "unknown argument" / "missing argument" fail.
#
# Usage: test/oracle/cli.sh <path-to-zdxc>
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
DXC_ROOT=${DXC_ROOT:-..}
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
grep -rh --include='*.hlsl' 'RUN: *%dxc ' "$DXC_ROOT/tools/clang/test" > "$TMP/runs" 2>/dev/null
total=0; ok=0; unsupported=0; bad=0
while IFS= read -r line; do
# Arguments between `%dxc` and the first pipe / redirect; drop the input.
# Tokens containing lit substitutions (%s, %t, %S/...) are dropped
# whole, as are redirections.
args=$(printf '%s' "$line" | sed -E 's/.*RUN: *%dxc //; s/[0-9]?>&[0-9]//g; s/[|<>].*$//' | tr ' ' '\n' | grep -v '%' | tr '\n' ' ')
total=$((total + 1))
# -zdxc-lex on an empty file: only the command line is exercised.
# shellcheck disable=SC2086
if out=$("$ZDXC" $args -zdxc-lex "$TMP/none.hlsl" 2>&1 < /dev/null); then
ok=$((ok + 1))
elif printf '%s' "$out" | grep -q "is not supported"; then
unsupported=$((unsupported + 1))
printf '%s\n' "$out" | grep -m1 "is not supported" | sed -E "s/.*error: '([^']*)'.*/\1/" >> "$TMP/unsupported"
elif printf '%s' "$out" | grep -qE "unknown argument|is missing|more than one input"; then
bad=$((bad + 1))
echo "BAD: $args -> $(printf '%s' "$out" | head -1)"
else
ok=$((ok + 1)) # other errors (e.g. invalid values) are not parser failures
fi
done < "$TMP/runs"
: > "$TMP/none.hlsl"
if [ -s "$TMP/unsupported" ]; then
echo "unsupported options seen (count):"
sort "$TMP/unsupported" | uniq -c | sort -rn | head -${SHOW:-15}
fi
echo "oracle cli: $total dxc command lines: $ok accepted, $unsupported unsupported-feature, $bad parse failures"
[ "$bad" -eq 0 ]

View File

@ -1,64 +0,0 @@
#!/bin/sh
# Codegen oracle: compiles every dxc-valid corpus file with zdxc and runs the
# validator on what it emits. Files zdxc cannot compile yet ("code
# generation: ... not supported yet") are counted as unsupported; any output
# the validator rejects is a bug.
#
# Usage: test/oracle/codegen.sh <path-to-zdxc> spirv|dxil
# (run test/oracle/parse.sh first to build the corpus list)
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
BACKEND=${2:-spirv}
DXC_BUILD=${DXC_BUILD:-../build}
SPIRV_VAL=$DXC_BUILD/oracle-spirv-tools/tools/spirv-val
DXV=$DXC_BUILD/bin/dxv
CACHE=zig-out/oracle/parse-valid.txt
[ -s "$CACHE" ] || { echo "run test/oracle/parse.sh first to build $CACHE"; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
valid=0; invalid=0; unsupported=0; other=0; crashed=0
: > "$TMP/invalid"; : > "$TMP/reasons"; : > "$TMP/valid"; : > "$TMP/crashed"
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
is_spirv=0
case "$flags" in *-spirv*) is_spirv=1 ;; esac
if [ "$BACKEND" = spirv ]; then
[ $is_spirv = 1 ] || flags="$flags -spirv"
else
[ $is_spirv = 1 ] && continue
fi
# shellcheck disable=SC2086
"$ZDXC" -fno-color-diagnostics -no-warnings $flags "$f" -Fo "$TMP/out" > "$TMP/log" 2>&1
rc=$?
if [ $rc -ge 128 ]; then
crashed=$((crashed + 1)); echo "$f" >> "$TMP/crashed"
elif [ $rc = 0 ]; then
if [ "$BACKEND" = spirv ]; then
env=$(printf '%s\n' "$flags" | sed -n 's/.*-fspv-target-env=\([a-z0-9.]*\).*/\1/p'); env=$(printf "%s" "$env" | sed -e "s/spirv1/spv1/" -e "s/universal1/spv1/")
"$SPIRV_VAL" --target-env "${env:-vulkan1.0}" --relax-block-layout "$TMP/out" > "$TMP/val" 2>&1
else
"$DXV" "$TMP/out" > "$TMP/val" 2>&1
fi
if [ $? = 0 ]; then
valid=$((valid + 1)); echo "$f" >> "$TMP/valid"
else
invalid=$((invalid + 1))
echo "$f: $(grep -m1 -i "error" "$TMP/val")" >> "$TMP/invalid"
fi
elif grep -q "code generation" "$TMP/log"; then
unsupported=$((unsupported + 1))
grep -m1 "code generation" "$TMP/log" | sed -E 's/^.*code generation: //' >> "$TMP/reasons"
else
other=$((other + 1))
echo "$f: $(grep -m1 "error" "$TMP/log")" >> "$TMP/other"
fi
done < "$CACHE"
echo "most common unsupported constructs:"
sed -E "s/'[^']*'/'X'/g" "$TMP/reasons" | sort | uniq -c | sort -rn | head -"${SHOW:-15}"
if [ "$invalid" -gt 0 ]; then echo "INVALID OUTPUT:"; head -20 "$TMP/invalid"; fi
[ -s "$TMP/other" ] && { echo "front-end errors:"; head -5 "$TMP/other"; }
cp "$TMP/valid" "zig-out/oracle/codegen-$BACKEND-valid.txt"
cp "$TMP/invalid" "zig-out/oracle/codegen-$BACKEND-invalid.txt"
[ -s "$TMP/crashed" ] && { echo "CRASHED:"; cat "$TMP/crashed"; }
echo "oracle codegen ($BACKEND): $valid valid, $invalid INVALID, $crashed CRASHED, $unsupported unsupported, $other other errors"
[ "$invalid" -eq 0 ] && [ "$crashed" -eq 0 ]

View File

@ -1,6 +0,0 @@
#!/bin/sh
# Print the file name if dxc compiles it with its RUN-line flags (-HV 2021).
flags=$(sh "$(dirname "$0")/run_flags.sh" "$1") || exit 0
# shellcheck disable=SC2086
"$DXC" -HV 2021 $flags "$1" -Fo /dev/null >/dev/null 2>&1 && echo "$1"
exit 0

View File

@ -1,50 +0,0 @@
#!/bin/sh
# M0.0 oracle checks: zdxc output must be accepted by DXC's validator (dxv)
# and spirv-val, and zdxc's container hash must match dxc-signed containers.
#
# Usage: test/oracle/m0.sh <path-to-zdxc>
# Oracles default to the DXC build next to this repo; override with
# DXC_BUILD=<dir> (needs bin/dxc, bin/dxv, oracle-spirv-tools/tools/spirv-val).
set -u
ZDXC=$1
DXC_BUILD=${DXC_BUILD:-../build}
DXC=$DXC_BUILD/bin/dxc
DXV=$DXC_BUILD/bin/dxv
SPIRV_VAL=$DXC_BUILD/oracle-spirv-tools/tools/spirv-val
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0
fail=0
ok() { pass=$((pass + 1)); }
bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
for tool in "$DXC" "$DXV" "$SPIRV_VAL"; do
[ -x "$tool" ] || { echo "missing oracle: $tool"; exit 1; }
done
# 1. Hash: re-verify dxc-signed containers with zdxc's DxilHash port.
printf '[numthreads(1,1,1)] void main() {}\n' > "$TMP/empty.hlsl"
printf 'RWStructuredBuffer<float> o : register(u0);\n[numthreads(64,1,1)] void main(uint i : SV_DispatchThreadID) { o[i] = sqrt((float)i) * 3.0; }\n' > "$TMP/sqrt.hlsl"
for src in empty sqrt; do
for t in cs_6_0 cs_6_6; do
"$DXC" -T $t -E main "$TMP/$src.hlsl" -Fo "$TMP/ref.dxo" >/dev/null 2>&1 || { bad "dxc failed on $src $t"; continue; }
if "$ZDXC" -zdxc-check-hash "$TMP/ref.dxo" >/dev/null; then ok; else bad "hash mismatch on dxc output ($src, $t)"; fi
done
done
# 2. DXIL: empty compute shader for every shader model must pass dxv.
for m in 0 1 2 3 4 5 6 7 8 9; do
out="$TMP/cs_6_$m.dxo"
if "$ZDXC" -zdxc-empty -T cs_6_$m -Fo "$out" \
&& "$DXV" "$out" >/dev/null 2>&1 \
&& "$ZDXC" -zdxc-check-hash "$out" >/dev/null; then ok; else bad "dxv rejected cs_6_$m"; fi
done
# 3. SPIR-V: empty compute shader must pass spirv-val.
if "$ZDXC" -zdxc-empty -spirv -T cs_6_0 -Fo "$TMP/cs.spv" \
&& "$SPIRV_VAL" --target-env vulkan1.0 "$TMP/cs.spv"; then ok; else bad "spirv-val rejected cs"; fi
echo "oracle m0: $pass passed, $fail failed"
[ "$fail" -eq 0 ]

View File

@ -1,50 +0,0 @@
#!/bin/sh
# Parser oracle: every corpus file that dxc compiles successfully (with the
# target and flags from its RUN line, under -HV 2021) must parse without
# syntax errors in zdxc. Prints the pass rate and the most common errors.
#
# Usage: test/oracle/parse.sh <path-to-zdxc>
# The list of dxc-valid files is cached in zig-out/oracle/parse-valid.txt;
# delete it to rebuild (takes a few minutes).
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
DXC_ROOT=${DXC_ROOT:-..}
DXC=$(cd "${DXC_BUILD:-$DXC_ROOT/build}" && pwd)/bin/dxc
CACHE=zig-out/oracle/parse-valid.txt
JOBS=${JOBS:-8}
mkdir -p zig-out/oracle
if [ ! -s "$CACHE" ]; then
echo "building list of dxc-valid corpus files (cached in $CACHE)..."
tmp=$(mktemp)
find "$DXC_ROOT/tools/clang/test/CodeGenHLSL" "$DXC_ROOT/tools/clang/test/CodeGenDXIL" "$DXC_ROOT/tools/clang/test/CodeGenSPIRV" -name '*.hlsl' | sort > "$tmp"
export DXC
xargs -P "$JOBS" -n 1 sh test/oracle/dxc_valid_one.sh < "$tmp" | sort > "$CACHE"
rm -f "$tmp"
fi
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0
fail=0
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
# shellcheck disable=SC2086
if "$ZDXC" -zdxc-parse $flags "$f" > "$TMP/out" 2>&1; then
pass=$((pass + 1))
else
fail=$((fail + 1))
echo "$f" >> "$TMP/failed"
grep -m1 -E 'error' "$TMP/out" | sed -E 's/^.*(error|fatal): //' >> "$TMP/errors"
fi
done < "$CACHE"
if [ "$fail" -gt 0 ]; then
echo "most common first errors:"
sed -E "s/'[^']*'/'X'/g" "$TMP/errors" | sort | uniq -c | sort -rn | head -${SHOW:-15}
echo "first failing files:"
head -${SHOW_FILES:-10} "$TMP/failed"
fi
echo "oracle parse: $pass passed, $fail failed (of $(wc -l < "$CACHE" | tr -d ' ') dxc-valid files)"
[ "$fail" -eq 0 ]

View File

@ -1,9 +0,0 @@
#!/bin/sh
# Print the first parse error of every dxc-valid corpus file that zdxc
# fails to parse (run test/oracle/parse.sh first to build the file list).
# Usage: test/oracle/parse_errors.sh <path-to-zdxc>
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
# shellcheck disable=SC2086
"$1" -zdxc-parse $flags "$f" 2>&1 | grep -m1 -E "error|fatal" | sed -E "s#^[^ ]*: (error|fatal): #$f: #"
done < zig-out/oracle/parse-valid.txt

View File

@ -1,57 +0,0 @@
#!/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 <path-to-zdxc> [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 ]

View File

@ -1,15 +0,0 @@
#!/bin/sh
# Print the dxc/zdxc flags taken from the first RUN line of an HLSL test:
# -T, -E, -D, -spirv, -fspv-target-env and -enable-16bit-types. Exits 1 if
# there is no -T.
run=$(grep -m1 'RUN:' "$1")
target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//')
[ -n "$target" ] || exit 1
entry=$(printf '%s' "$run" | grep -oE -- '-E *[A-Za-z_][A-Za-z0-9_]*' | head -1 | sed 's/-E */-E /')
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"
env=$(printf '%s' "$run" | grep -oE -- '-fspv-target-env=[a-z0-9.]+' | head -1)
[ -n "$env" ] && extra="$extra $env"
echo "-T $target $entry $extra $defs"

View File

@ -1,34 +0,0 @@
#!/bin/sh
# Sema oracle (no false errors): every corpus file that dxc compiles under
# -HV 2021 must pass zdxc's semantic analysis without errors. Files whose
# only errors are "not supported yet" (milestone 0.2 features) are counted
# separately.
#
# Usage: test/oracle/sema.sh <path-to-zdxc> (run test/oracle/parse.sh first)
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
CACHE=zig-out/oracle/parse-valid.txt
[ -s "$CACHE" ] || { echo "run test/oracle/parse.sh first to build $CACHE"; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0; later=0; fail=0
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
# shellcheck disable=SC2086
if "$ZDXC" -zdxc-sema -fno-color-diagnostics -no-warnings $flags "$f" > "$TMP/out" 2>&1; then
pass=$((pass + 1))
elif ! grep "error:" "$TMP/out" | grep -v "too many errors emitted" | grep -qv "not supported yet"; then
later=$((later + 1))
else
fail=$((fail + 1))
echo "$f" >> "$TMP/failed"
grep -m1 "error:" "$TMP/out" | sed -E 's/^.*error: //' >> "$TMP/errors"
fi
done < "$CACHE"
if [ "$fail" -gt 0 ]; then
echo "most common first errors:"
sed -E "s/'[^']*'/'X'/g; s/[0-9]+/N/g" "$TMP/errors" | sort | uniq -c | sort -rn | head -${SHOW:-25}
cp "$TMP/failed" zig-out/oracle/sema-failed.txt
fi
echo "oracle sema: $pass clean, $later need milestone 0.2 features, $fail false errors (of $(wc -l < "$CACHE" | tr -d ' ') dxc-valid files)"
[ "$fail" -eq 0 ]

View File

@ -1,7 +0,0 @@
#!/bin/sh
# First Sema error of each file listed in zig-out/oracle/sema-failed.txt.
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
# shellcheck disable=SC2086
"$1" -zdxc-sema -fno-color-diagnostics -no-warnings $flags "$f" 2>&1 | grep -m1 "error:" | sed -E "s#^[^ ]*: error: #$(basename "$f"): #"
done < zig-out/oracle/sema-failed.txt

View File

@ -1,75 +0,0 @@
#!/bin/sh
# Expected-diagnostics oracle: runs zdxc over dxc's SemaHLSL `-verify` tests
# (HLSL 2021 only) and compares the lines zdxc reports errors on with the
# lines the tests expect errors on.
#
# caught expected error lines zdxc also reports an error on
# missed expected error lines zdxc is silent on
# false lines zdxc reports an error on that expect none
#
# Files where zdxc reports a "not supported yet" (milestone 0.2) error are
# counted separately and left out of the line totals.
#
# Usage: test/oracle/verify.sh <path-to-zdxc> [corpus-dir]
# SHOW=N number of most common missed / false messages to print
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
CORPUS=${2:-../tools/clang/test/SemaHLSL}
HERE=$(cd "$(dirname "$0")" && pwd)
OUT=zig-out/oracle
mkdir -p "$OUT"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
: > "$TMP/missed"; : > "$TMP/false"; : > "$TMP/files"
files=0; exact=0; later=0; skipped=0; caught=0; missed=0; false=0
for f in $(grep -rl --include='*.hlsl' -e '-verify' "$CORPUS" | sort); do
run=$(grep -m1 'RUN:.*-verify' "$f" | sed -E 's#(^| )/([TED]) *#\1-\2 #g')
hv=$(printf '%s' "$run" | grep -oE -- '-HV *[0-9a-z]+' | sed 's/-HV *//')
target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_[0-9]+_[0-9]+' | head -1 | sed 's/-T *//')
if [ -n "$hv" ] && [ "$hv" != 2021 ] || [ -z "$target" ]; then
skipped=$((skipped + 1)); continue
fi
flags="-T $target"
flags="$flags $(printf '%s' "$run" | grep -oE -- '-E *[A-Za-z_][A-Za-z0-9_]*' | head -1 | sed 's/-E */-E /')"
flags="$flags $(printf '%s' "$run" | grep -oE -- '-D *[A-Za-z_][A-Za-z0-9_]*(=[^ ]*)?' | sed 's/-D */-D/' | tr '\n' ' ')"
flags="$flags $(printf '%s' "$run" | grep -oE -- ' -(spirv|enable-16bit-types|W[a-z0-9-]+)' | tr '\n' ' ')"
awk -f "$HERE/verify_expect.awk" "$f" > "$TMP/expect"
# shellcheck disable=SC2086
"$ZDXC" -zdxc-sema -fno-color-diagnostics -ferror-limit=0 $flags "$f" > "$TMP/out" 2>&1
files=$((files + 1))
if grep -q "error: .*not supported yet" "$TMP/out"; then
later=$((later + 1)); continue
fi
# Lines zdxc reports errors on, in this file only.
grep -F "$f:" "$TMP/out" | grep -E '^[^ ]+:[0-9]+:[0-9]+: (fatal )?error: ' |
sed -E "s#^[^ ]+:([0-9]+):[0-9]+: (fatal )?error: (.*)#\1 \3#" > "$TMP/got"
awk -v name="$(basename "$f")" -v missed="$TMP/missed" -v falsef="$TMP/false" '
FILENAME == ARGV[1] {
if ($1 == "error") { line = $2; $1 = ""; $2 = ""; sub(/^ +/, ""); if (!(line in want)) want[line] = $0 }
else warn[$2] = 1
next
}
{ line = $1; $1 = ""; sub(/^ +/, ""); if (!(line in got)) got[line] = $0 }
END {
c = m = x = 0
for (l in want) if (l in got) c++; else { m++; print name ":" l ": " want[l] >> missed }
for (l in got) if (!(l in want)) { x++; print name ":" l ": " got[l] (l in warn ? " [dxc: warning]" : "") >> falsef }
print c, m, x
}' "$TMP/expect" "$TMP/got" > "$TMP/counts"
read -r c m x < "$TMP/counts"
caught=$((caught + c)); missed=$((missed + m)); false=$((false + x))
[ "$m" -eq 0 ] && [ "$x" -eq 0 ] && exact=$((exact + 1))
echo "$m $x $f" >> "$TMP/files"
done
summarize() {
sed -E 's/^[^ ]+: //; s/'"'"'[^'"'"']*'"'"'/'"'"'X'"'"'/g; s/[0-9]+/N/g' "$1" | sort | uniq -c | sort -rn | head -"${SHOW:-15}"
}
echo "most common missed errors (expected by dxc, not reported):"; summarize "$TMP/missed"
echo "most common false errors (reported, not expected):"; summarize "$TMP/false"
cp "$TMP/missed" "$OUT/verify-missed.txt"
cp "$TMP/false" "$OUT/verify-false.txt"
sort -rn "$TMP/files" > "$OUT/verify-files.txt"
total=$((caught + missed))
pct=0; [ "$total" -gt 0 ] && pct=$((caught * 100 / total))
echo "oracle verify: $files files ($skipped other -HV skipped), $exact exact, $later need milestone 0.2"
echo " error lines: $caught/$total caught ($pct%), $missed missed, $false false"

View File

@ -1,25 +0,0 @@
# Print the diagnostics a clang `-verify` test expects in its own file, one
# per line: "<severity> <line> <message>". Handles `expected-error`,
# `expected-warning` (optionally `-re`), `@+N` / `@-N` / `@N` line offsets
# and repeat counts; markers aimed at other files (`@file:N`) and notes are
# skipped.
{
rest = $0
while (match(rest, /expected-(error|warning)(-re)?(@[^ {]*)?( +[0-9]+)? *\{\{/)) {
marker = substr(rest, RSTART, RLENGTH)
rest = substr(rest, RSTART + RLENGTH)
sev = (marker ~ /^expected-error/) ? "error" : "warning"
line = NR
if (match(marker, /@[^ {]*/)) {
off = substr(marker, RSTART + 1, RLENGTH - 1)
if (off ~ /^\+[0-9]+$/) line = NR + substr(off, 2)
else if (off ~ /^-[0-9]+$/) line = NR - substr(off, 2)
else if (off ~ /^[0-9]+$/) line = off + 0
else continue
}
msg = rest
end = index(msg, "}}")
if (end > 0) msg = substr(msg, 1, end - 1)
print sev, line, msg
}
}

View File

@ -1,16 +0,0 @@
// PROFILE: as_6_5
// ENV: vulkan1.3
// Amplification shader: the groupshared payload becomes TaskPayloadWorkgroupEXT
// storage, DispatchMesh OpEmitMeshTasksEXT.
// ZCHECK: OpEntryPoint TaskEXT
// ZCHECK: %pl = OpVariable {{.*}} TaskPayloadWorkgroupEXT
// ZCHECK: OpEmitMeshTasksEXT
struct Payload { uint base; float scale[2]; uint ids[8]; };
groupshared Payload pl;
[numthreads(8,1,1)]
void main(uint tid : SV_GroupIndex) {
pl.ids[tid] = tid * 2;
if (tid == 0) { pl.base = 7; pl.scale[0] = 1; pl.scale[1] = 2; }
GroupMemoryBarrierWithGroupSync();
DispatchMesh(2, 1, 1, pl);
}

View File

@ -1,22 +0,0 @@
// PROFILE: cs_6_0
// Atomics on groupshared memory, buffers and texels.
// ZCHECK: OpAtomicIAdd %uint {{.*}} %uint_2 %uint_0 %uint_1
// ZCHECK: OpImageTexelPointer
// ZCHECK: OpAtomicCompareExchange
groupshared uint cnt;
groupshared int mx[4];
RWStructuredBuffer<uint> sb : register(u0);
RWBuffer<uint> tb : register(u1);
RWTexture2D<int> tex : register(u2);
RWByteAddressBuffer rb : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint old, o2; int o3;
InterlockedAdd(cnt, 1, old);
InterlockedMax(mx[i & 3], (int)i);
InterlockedCompareExchange(cnt, 5, 6, o2);
InterlockedOr(sb[i], 2);
InterlockedMin(tb[i], i, o2);
InterlockedExchange(tex[uint2(i, 1)], 3, o3);
InterlockedCompareStore(sb[0], 1, 2);
sb[1] = old + o2 + o3;
}

View File

@ -1,8 +0,0 @@
// PROFILE: cs_6_0
// Memory barriers (device, group, all; with and without group sync).
RWStructuredBuffer<uint4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
AllMemoryBarrier(); AllMemoryBarrierWithGroupSync(); DeviceMemoryBarrier(); DeviceMemoryBarrierWithGroupSync(); GroupMemoryBarrier();
o[0] = uint4(firstbitlow(i), firstbithigh(i), firstbithigh((int)i), f32tof16(asfloat(i)));
o[1].x = asuint(f16tof32(i));
}

View File

@ -1,27 +0,0 @@
// PROFILE: cs_6_2
// Bitfields: SPIR-V starts a new storage word when the type changes (c is
// int, a and b uint), as dxc does.
// ZCHECK: OpTypeStruct %uint %uint %int %uint %uint %uint
// ZCHECK: OpShiftRightArithmetic %int
struct Base { uint lo : 4; uint hi : 4; };
struct P : Base {
uint a : 3; uint b : 5; int c : 4;
uint d;
uint e : 30; uint f : 4;
uint sum() { return a + b + lo + hi; }
void bump() { b += 1; hi++; }
};
cbuffer CB { P cp; };
RWStructuredBuffer<P> sb : register(u0);
RWStructuredBuffer<int> o : register(u1);
[numthreads(1,1,1)] void main() {
P p = sb[0];
p.b = 7;
p.c = -3;
p.bump();
sb[1] = p;
P q = {1, 2, 3, 4, -5, 6, 7, 8};
sb[2] = q;
sb[3].f |= 2;
o[0] = p.a + p.c + cp.e + cp.f + p.sum() + q.c;
}

View File

@ -1,13 +0,0 @@
// PROFILE: cs_6_0
// Structured buffers of matrices: whole loads and stores, rows (constant
// and dynamic) and row components.
// ZCHECK: OpMemberDecorate %type_StructuredBuffer_mat4v3float 0 MatrixStride 16
// ZCHECK: OpMemberDecorate %type_RWStructuredBuffer_mat2v3float 0 MatrixStride 8
StructuredBuffer<float4x3> m : register(t0);
RWStructuredBuffer<float2x3> r : register(u1);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
o[i] = float4(m[i][1], 1) + r[i][0].x + float4(m[0][i % 4], m[1][2].y);
r[i] = r[i] * 2;
o[i + 1] = mul(float4(1, 2, 3, 4), m[i]).xyzz;
}

View File

@ -1,16 +0,0 @@
// PROFILE: cs_6_0
// Byte-address buffer loads, stores, atomics and sizes.
RWByteAddressBuffer rb : register(u0);
ByteAddressBuffer ro : register(t0);
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 v = ro.Load4(i * 16) + rb.Load2(4).xyxy;
rb.Store3(i * 12, v.xyz);
uint old; rb.InterlockedAdd(0, 1, old);
rb.InterlockedCompareStore(8, 1, 2);
uint n = 0;
rb.Store(20, n + old);
uint w; rb.GetDimensions(w); rb.Store(16, w);
}

View File

@ -1,17 +0,0 @@
// PROFILE: cs_6_2
// FLAGS: -enable-16bit-types
// Templated byte-address Load/Store of structs, matrices (by column in
// SPIR-V), 16- and 64-bit components from 32-bit words.
struct S { float a; double b; uint16_t c; int2 d; };
RWByteAddressBuffer buf : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
S s = buf.Load<S>(i * 32);
float3x2 m = buf.Load<float3x2>(64);
half4 h = buf.Load<half4>(128);
S arr[2] = buf.Load<S[2]>(256);
s.a += m[1][0] + h.y + arr[1].d.x;
buf.Store<S>(i * 32 + 512, s);
buf.Store<float3x2>(96, m);
buf.Store<half4>(136, h);
buf.Store<double>(160, s.b);
}

Some files were not shown because too many files have changed in this diff Show More