Commit Graph

13 Commits

Author SHA1 Message Date
Peter Li c6d58c0017 Add a DXC drop-in: dxc and a dxcompiler library with DXC's COM API
zig build dropin installs the command line as bin/dxc and builds
dxcompiler (libdxcompiler.so / .dylib, dxcompiler.dll) exporting
DxcCreateInstance and DxcCreateInstance2. It implements IDxcCompiler3,
IDxcVersionInfo and IDxcUtils over compile, with DXC's result shapes,
status codes and include-path spellings, so programs that load DXC's
library (SDL_shadercross, for one) run on zdxc unchanged.

compile.Request gains compat_notes, off for the drop-in: its clients
read any diagnostic text as a warning.
2026-11-01 17:59:17 -08:00
Peter Li 31f3293380 zdxc: C API and static libzdxc
include/zdxc.h: compile a dxc command line in memory and read the
outputs (object, diagnostics, -P, -Frs) from a result; an optional
callback serves the input and #include files. No global state, so any
number of threads can compile at once. zig build installs libzdxc.a
(-Dlinkage=dynamic for a shared library) with the compiler runtime
bundled and only the zdxc_* symbols visible. docs/c-api.md describes it.

The pipeline moves from main.zig into compile.zig, which returns its
outputs instead of writing files; the command line and the C API both
use it, and produce the same bytes. The executable's build step is now
zdxc-cli so that artifact("zdxc") names the library; it still installs
as bin/zdxc. Writing an output file now fails with a message instead of
an error trace.
2026-11-01 17:15:16 -08:00
Peter Li badcdd8593 zdxc: make the tree a clean public source drop
Move the oracle tests, the benchmark 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/.
2026-11-01 15:39:53 -08:00
Peter Li a7f86d1a88 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.
2026-11-01 09:46:47 -08:00
Peter Li ead0a0b9a6 Textures and samplers on both backends
Texture1D/2D/3D/Cube (and arrays), Texture2DMS, RWTexture*, Buffer and
RWBuffer, SamplerState and SamplerComparisonState. Methods: Sample,
SampleBias, SampleLevel, SampleGrad, SampleCmp, SampleCmpLevelZero,
SampleCmpLevel/Bias/Grad (DXIL 6.7/6.8), Load, operator[] reads and
writes, Gather and GatherCmp (per channel, one offset),
CalculateLevelOfDetail(Unclamped), GetDimensions (textures and buffers)
and, on DXIL, GetSamplePosition. Argument roles come from one shared
decoder (src/ir/texture.zig); out parameters of methods go through
temporaries.

DXIL follows dxc's argument layout (undef padding, zero offsets),
resource metadata and properties, replicated typed stores and the typed
UAV load flag. SPIR-V follows dxc's image types (unknown depth, inferred
formats for typed buffers and RW textures), capabilities and image
operands.

Also: SPIR-V interpolation decorations on pixel inputs and vertex
outputs (as dxc), a crash on array pixel inputs, and a miscompile on both
backends where swizzle components lived in a 16-entry static buffer, so
a function with more than 16 swizzles could silently read the wrong
components. test/spirv/check.sh (part of `zig build oracle`) checks
SPIR-V disassembly like test/dxil/check.sh does for DXIL.

Not yet: status (sparse feedback) arguments, Gather with four offsets,
and texel offsets that need loop unrolling to become constants.
2026-10-31 10:00:06 -07:00
Peter Li ca171b5776 DXIL vertex and pixel shaders
Signatures follow dxc: semantic interpretation per signature point, a port
of the prefix-stable signature packer (registers and masks match dxc, so
stages link with dxc-compiled ones), canonical system-value names,
SV_Target arrays split per render target, ISG1/OSG1, PSV0 signature
elements and dependency tables, and signature metadata. Inputs and
outputs go through loadInput/storeOutput; shadow and not-in-signature
system values use their intrinsics. Adds discard, clip, derivatives and
fwidth, and signature-driven shader flags.

Also fixes two miscompiles found along the way: static global
initializers were dropped (both backends; they now run on entry in
declaration order, and DXIL keeps static globals in allocas), and DXIL
float constants were written as f64 bit patterns, so every float literal
read back as 0.0.

test/dxil/check.sh (part of `zig build oracle`) compares signatures with
dxc and checks the disassembly, since dxv does not catch wrong values.
2026-10-31 07:40:06 -07:00
Peter Li 01bc248563 DXIL backend for compute shaders
src/dxil/emit.zig lowers IR to DXIL: calls are inlined while emitting
(returns merge through phis), values are scalarized, locals become
flattened [N x scalar] allocas, and resources become handles created on
entry (createHandle before SM 6.6, createHandleFromBinding plus
annotateHandle from 6.6). Structured, byte-address and typed buffer
reads and writes use bufferLoad/Store or rawBufferLoad/Store by shader
model; math intrinsics map to dx.op unary / binary / tertiary / dot
operations; compute system values to threadId and friends. The module
carries dx.resources, entry properties (shader flags, numthreads) and a
PSV0 part with resource bindings; dxv accepts the output.

The bitcode writer gains alloca, load, store, getelementptr, unreachable
and aggregate constants. Float-to-int constant folding saturates instead
of panicking on out-of-range values.

zig build oracle-codegen: SPIR-V 281 valid, DXIL 2 valid (compute only so
far), 0 invalid on either backend.
2026-10-31 05:05:51 -07:00
Peter Li f81c049912 Add semantic analysis (Sema) with dxc-derived oracles
Sema type-checks a parsed translation unit: an interned type table, scopes
and symbols, declarations, statements and expressions, implicit and explicit
conversions, user-function overload resolution, and intrinsic / builtin
method matching driven by dxc's gen_intrin_main.txt (vendored, turned into a
Zig table at build time by tools/gen_intrinsics.zig).

Rules ported from dxc where it matters for exact agreement:
- operator result types (CombineBasicTypes, shift and bool rules)
- literal suffix types and diagnostics, including `1.#INF`
- declaration modifier validity and conflicts (DiagnoseHLSLDecl) and
  row_major / column_major checks, using source-ordered qualifier words
- constant folding of asuint / max / min
- `_Static_assert`, `__decltype` and `std::is_same` builtins
  (`static_assert` is an ordinary identifier in HLSL 2021)

Templates, operator overloading and bitfields report "not supported yet
(planned for milestone 0.2)".

Oracles:
- zig build oracle-sema: no false errors on the 1604 dxc-valid corpus
  files (1537 clean, 67 need milestone 0.2 features)
- zig build oracle-verify: error-line agreement with dxc's SemaHLSL
  -verify tests under HLSL 2021 (53% of expected error lines caught,
  80 false error lines)

Also fixes the provenance commit of gen_intrin_main.txt (55a61aa79).
2026-10-31 03:17:40 -07:00
Peter Li 88fe78bb3d dxc-compatible command line
zdxc now accepts dxc's command line as-is, so it can replace dxc in build
scripts.

- vendor/dxc/HLSLOptions.td (dxc's option definitions) is turned into a
  Zig table at build time by tools/gen_options.zig (no tablegen/Python).
- src/options.zig parses with LLVM OptTable's rules, as dxc does: `-`,
  `/` and `--` prefixes; flags, joined, separate, joined-or-separate,
  multi-arg and comma-joined options; longest spelling first; aliases;
  case-sensitive; `/`-prefixed non-options are input paths; the last input
  wins. `-T cs_6_0`, `/T cs_6_0` and `-Tcs_6_0` are all accepted.
- Every dxc option has a support level:
  - implemented (-T -E -Fo -D -I -P -Fi -HV -spirv -enable-16bit-types
    -WX -no-warnings -W[no-]x -fdiagnostics-format= -ferror-limit=
    -fdiagnostics-color[=] -O0..3 -Od -Vd -help --version -nologo ...),
  - accepted with a one-line note, no effect yet (-Zpr, -Gis, -Qstrip_*,
    -Fh, -fvk-*, -fspv-target-env=, ... ),
  - rejected with a reason: dropped features (-Zi/-Fd debug info,
    -Fc/-dumpbin disassembly, -recompile, -link, -verify, -ast-dump, LLVM
    internals) or "not supported by zdxc yet".
- Errors match dxc's: "unknown argument: '-x'", "argument to '-T' is
  missing"; exit codes 1 (command line / I/O) and 5 (compile errors).
- -help lists dxc's groups and help text for what zdxc accepts.
- zdxc-only options (-zdxc-*, -f[no-]color-diagnostics) use names dxc
  does not define.
- `zig build oracle-cli`: all 5873 `RUN: %dxc` command lines in the DXC
  test corpus parse; 3392 are accepted and 2481 rejected only for
  deliberately unsupported features, with 0 unknown/missing arguments.
2026-10-31 02:27:52 -07:00
Peter Li 9089c5ea56 M0.1: HLSL 2021 parser and syntax tree
- src/front/ast.zig: purely syntactic tree (declarations, statements,
  expressions, types as written, attributes, semantics/registers).
- src/front/parser.zig: recursive descent over the preprocessed tokens,
  with a scoped type-name table to tell declarations from expressions,
  casts from parenthesized expressions and template arguments from
  comparisons. Covers the M0.1 language plus the syntax M0.2 needs
  (templates incl. partial specialization and variable templates, operator
  overloading, bitfields, methods, namespaces, enums, typedef/using) and
  dxc-isms seen in the corpus: payload access qualifiers, typed
  [[attributes]], legacy annotations / state blocks, `.template` calls,
  condition declarations, functions returning arrays.
- Error recovery at declaration and statement boundaries.
- src/front/ast_dump.zig and -zdxc-ast / -zdxc-parse dev flags.
- `zig build oracle-parse`: all 1604 corpus files that dxc compiles under
  -HV 2021 parse without errors; no crashes over all 4764 test files.
2026-10-31 01:20:46 -07:00
Peter Li 05f0a965be Preprocessor performance, round 1: benchmark + vector scans
Adds `zig build bench` (bench/pp_bench.zig): lexes / preprocesses / prints
a file list in-process, best of N, files served from memory.

On the 4764-file, 13.1 MB DXC test corpus (Apple M-series, ReleaseFast,
interleaved A/B against the previous commit):
  lex    13.3 -> 11.2 ms  (-16%)
  pp     49.7 -> 40.1 ms  (-19%)
  print  68.6 -> 53.2 ms  (-22%)

Kept:
- src/front/scan.zig: portable @Vector scans (width from
  std.simd.suggestVectorLength). Comment bodies are skipped with vector
  searches; line-start tables are built from per-block newline bitmasks.
- An identifier character table for the (short) identifier scans.
- A line cursor for -P printing: O(1) per token instead of a binary search.
- A 1024-bit filter over macro names so most identifiers skip hashing;
  the macro table is presized.

Tried and dropped (no gain): vector skipping of blank runs (2% slower;
gaps between tokens are mostly a single space) and fusing splice detection
into the newline scan.
2026-10-31 00:45:52 -07:00
Peter Li fb322f24a7 M0.1: HLSL preprocessor matching dxc -P across the DXC test corpus
- Source manager (line splicing, UTF-8 BOM) and clang-style diagnostics.
- Lexer producing preprocessing tokens.
- Preprocessor modelled on clang's: object and function-like macros, #/##,
  variadics with GNU comma elision, painted recursion blocking, nested
  argument pre-expansion, #if/#elif expressions, #include with -I and
  #pragma once, #line, #error/#warning, pass-through #pragma, and dxc's
  predefined macros (__HLSL_VERSION, __SHADER_TARGET_*, __spirv__, ...).
- dxc's compiled-in HLSL headers (<dx/linalg.h>, <vk/spirv.h>, ...) are
  vendored as data and used as the fallback for angled includes.
- -P/-Fi/-D/-I/-HV 2021/-enable-16bit-types options; profiles now cover
  lib_, ms_, as_ and SM 6.0-6.11.
- `zig build oracle-pp`: token-for-token comparison with dxc -P. 2060 of
  2060 corpus files dxc accepts match.
2026-10-31 00:16:50 -07:00
Peter Li 8e38009a69 git package 2026-10-30 23:52:41 -07:00