Compare commits

..

79 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
Peter Li 7a4649ed63 Inline SPIR-V types (vk::SpirvType, vk::SpirvOpaqueType) and cooperative matrices
- A spirv type kind: opcode with type, constant and literal operands
  (vk::integral_constant, vk::Literal), sized (SpirvType) or opaque.
  Integer, float and pointer types map to zdxc's own; others are
  declared as spelled and deduplicated. Capabilities and extensions on
  aliases, fields and declarations travel with the type.
- vk::WorkgroupSpirvPointer and other inline pointers are values, never
  variables; passing one to a function adds VariablePointers (dxc
  inlines the call instead).
- __builtin_spv_CooperativeMatrixLengthKHR; template argument deduction
  through aliases of inline types and qualified patterns; function
  template instances keep their arguments.
- [[vk::ext_literal]] defaults, constants resolved where Sema saw them,
  static members through objects, enum-typed values in SPIR-V.
- [[vk::ext_decorate(_string)]] on struct members; capabilities from
  inline SPIR-V add the extensions they need; PhysicalStorageBuffer64
  addressing with physical storage buffer pointers.
- All vk::khr::CooperativeMatrix tests compile to valid SPIR-V.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 19:22:10 -07:00
Peter Li 0ceb237938 Templates: S<T>::member, partial specialization, member templates, SFINAE, out-of-line members, ADL
- Qualified names through template instances (S<T>::x, S<T>::f(),
  typename S<T>::type).
- Partial specialization patterns matched structurally
  (matrix<T, N, M>, S<T>); the injected class name inside instances.
- Member function templates (obj.f<T>(), S::f<T>()), including calls
  from other members; S::f<1>(x) parsed as a call.
- SFINAE: candidates whose signature fails to substitute are dropped;
  a declared-then-defined template uses its definition.
- Out-of-line member definitions, for plain structs (keeping static),
  namespaces and class templates (given to every instance), including
  nested template<> template<> member templates.
- Deduction from resources (RWStructuredBuffer<T>), through alias
  templates and from the injected class name; argument-dependent lookup.
- static const members evaluated in their instance's scope; sizeof(T)
  in template arguments; ::template; instantiation depth limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:58:46 -07:00
Peter Li a951eba760 Vulkan memory model, ROV interlock, globallycoherent, legacy buffer matrix order
- -fspv-use-vulkan-memory-model: a port of spirv-opt's UpgradeMemoryModel
  (Coherent / Volatile become access flags, Device scope becomes
  QueueFamily); also used when ray tracing reads subgroup built-ins
  below Vulkan 1.3, as dxc does.
- Rasterizer-ordered views: SPIR-V fragment shader interlock around the
  entry; DXIL ROV metadata, properties, RDAT flag and shader flag.
- globallycoherent: SPIR-V Coherent; DXIL metadata, properties, RDAT.
- -fspv-use-legacy-buffer-matrix-order: row-major byte-address matrices.
- -fspv-preserve-interface accepted (zdxc keeps every interface variable).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:26:53 -07:00
Peter Li 4e52358128 SubpassInput, vk::image_format and inline SPIR-V
SubpassInput / SubpassInputMS with [[vk::input_attachment_index]] (a
SubpassData image read at (0, 0), with the sample for MS). Explicit
[[vk::image_format]] on storage images and texel buffers, followed from
the variable to every load and element access.

Inline SPIR-V: calls of [[vk::ext_instruction(op[, set])]] functions emit
the instruction (OpExtInst for a set) with [[vk::ext_literal]] and
[[vk::ext_reference]] operands; vk::ext_result_id<T>; ext_capability /
ext_extension on functions, variables and entry points;
ext_builtin_input / ext_builtin_output variables; ext_storage_class;
ext_decorate, ext_decorate_id and ext_decorate_string on variables and
entry parameters; vk::ext_execution_mode(_id). The capabilities and
extensions instructions, builtins, decorations and execution modes need
come from a table generated from the SPIR-V grammar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:08:44 -07:00
Peter Li 1ac6d65718 SPIR-V reflection, extension and entry point options; vk::builtin
-fspv-reflect adds SPV_GOOGLE UserSemantic, UserTypeGOOGLE and
CounterBuffer decorations; -fspv-extension= restricts the extensions
used (KHR allows all KHR ones; the NV compute derivatives extension is
used when only it is allowed); -fspv-entrypoint-name= renames the entry
point; -fspv-enable-maximal-reconvergence; -fvk-support-nonzero-base-
instance / -vertex subtract the base instance / vertex as dxc does;
-fspv-use-unknown-image-format. [[vk::builtin(...)]] on parameters and
fields (PointSize, HelperInvocation, BaseVertex, BaseInstance, DrawIndex,
DeviceIndex). Constant buffer block types are named type.<buffer> only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:55:14 -07:00
Peter Li 35dc3b9fcf Vulkan layout and position options; packoffset; 64-bit buffer access
-fvk-use-gl-layout (strict std140 / std430), -fvk-use-dx-layout (FXC
cbuffer / structured buffer packing) and -fvk-use-scalar-layout pick the
constant buffer, tbuffer and structured buffer rules as dxc picks them;
[[vk::offset]] places members (and is checked against the rules).
-fvk-invert-y flips SV_Position.y in the last pre-raster stage;
-fvk-use-dx-position-w reciprocates SV_Position.w in pixel shaders.

Constant buffer members honor packoffset / register(cN) on both
backends, the rest following the last explicit member (as dxc; DXIL used
to ignore them). Packed structs round their size up to their widest
component, so structured buffers of {double; float3} have dxc's 24-byte
stride on both backends (was 20). 64-bit structured buffer loads and
stores before SM 6.3 go through i32 words (bufferLoad / rawBufferLoad
.i32 with makeDouble / splitDouble), as dxc; they used invalid 64-bit
overloads before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:35 -07:00
Peter Li 2496fce3c0 Vulkan bindings, locations, push constants and spec constants
SPIR-V descriptor bindings are numbered as dxc numbers them: Sema keeps
global and cbuffer declarations in order, lowering records every
descriptor declaration (used or not), and the backend assigns
[[vk::binding]] / [[vk::counter_binding]] first, then register() with the
-fvk-{b,t,s,u}-shift options, then the rest on the next free bindings in
declaration order (Append / Consume counters right after their buffer,
other counters last). Adds -fvk-bind-register, -fvk-bind-globals,
-auto-binding-space, -fvk-auto-shift-bindings, -fvk-stage-io-order and
-fspv-flatten-resource-arrays (one variable per element where indices
are constant), [[vk::push_constant]] buffers (std430, PushConstant),
[[vk::constant_id]] specialization constants, [[vk::location]] and
[[vk::index]], interface variables named after the semantic as written,
and location counts for 1xN / Nx1 matrices. -fcgl is accepted.

Against dxc on the corpus, bindings and locations now match on all 1234
comparable SPIR-V outputs (865 differed before). The SPIR-V checks now
compare bindings and locations with dxc for every test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:38:16 -07:00
Peter Li 0570274b65 Root signatures in shaders, libraries and rootsig targets
[RootSignature(...)] on an entry compiles (global mode, version 1.1 or
-force-rootsig-ver) into an RTS0 part after PSV0; errors are reported as
dxc reports them. Libraries' GlobalRootSignature / LocalRootSignature
subobjects carry their serialized root signature in RDAT's raw bytes.
-T rootsig_1_0 / rootsig_1_1 compile the macro -E names into a root
signature container; -rootsig-define, -Frs and -Qstrip_rootsignature
are supported. All 49 corpus shaders with root signatures match dxc's
RTS0; the DXIL checks now compare RTS0 as well as RDAT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:09:26 -07:00
Peter Li f703c1fc7e Root signature compiler
A port of dxc's root signature parser, verifier and serializer (versions
1.0 and 1.1, local / global modes): text to the RTS0 blob, with dxc's
error messages. Checked byte for byte against dxc on 409 accepted
signatures, and on 307 rejected ones for the same errors. Not wired in
yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:04:30 -07:00
Peter Li 6beddc7de1 DXIL graphics shaders in libraries
Vertex, pixel, geometry, hull, domain, mesh and amplification shaders in
libraries: entries carry their signatures (without usage masks, as dxc)
and stage state; hull shaders' patch constant functions are defined under
their mangled HLSL names. Library functions are defined in declaration
order, as dxc defines them, so RDAT records come in the same order.
Prerelease shader model libraries (experimental RDAT) are reported as
unsupported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:04:01 -07:00
Peter Li f7bdd90876 DXIL exported library functions and native 16-bit types
Exported functions become definitions of their own: scalars and vectors
by value (vectors split with extractelement / rebuilt with insertelement),
structs and out / inout values by pointer, with dxc's mangled names (type
and name back-references), function annotations (qualifiers, component
types, semantics) and RDAT records as library functions.

-enable-16bit-types now reaches the DXIL backend: the native 16-bit data
layout and the UseNativeLowPrecision flag (feature NativeLowPrecision
instead of MinimumPrecision). 16-bit isinf / isnan / isfinite / isnormal
test the bits before SM 6.9, as dxc does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:57:14 -07:00
Peter Li 02e2730fa2 DXIL library subobjects
State object config, exports associations, shader / pipeline configs and
hit groups declared in a library become RDAT subobject records (root
signature subobjects still need a root signature compiler).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:49:15 -07:00
Peter Li f1745698ed DXIL library targets with ray tracing shaders
Libraries emit each entry as a function of its own: ray tracing shaders
with Microsoft-mangled names taking payload / attributes / parameters by
pointer, compute shaders by name. Resources become external globals
whose handles come from createHandleForLib (annotated from SM 6.6) in the
functions that use them; unbound ones stay at -1 until linked. Adds the
ray tracing operations (TraceRay, CallShader, ReportHit, IgnoreHit,
AcceptHitAndEndSearch, system values), library metadata (function
annotations, entries by name with payload / attribute sizes), and the
RDAT part, built as dxc builds it: per-function flags, valid stages and
minimum shader model come from the emitted instructions and a table of
dxc's per-operation requirements. Libraries without shaders are empty, as
in dxc. The DXIL checks compare RDAT with dxc's byte for byte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:45:56 -07:00
Peter Li 7d9331969a DXIL RayQuery and acceleration structures
RayQuery locals allocate their query in the prologue on first use (copies
alias it); methods lower to dx.op.rayQuery_* (TraceRayInline, Proceed,
commits, and the scalar / vector / matrix state reads). Acceleration
structures are SRVs of kind 16 (raw in PSV); using RayQuery sets the
Raytracing tier 1.1 shader flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:24:08 -07:00
Peter Li 5ac6c4c066 SPIR-V shader record buffers and Volatile ray tracing builtins
[[vk::shader_record_ext]] / [[vk::shader_record_nv]] ConstantBuffers and
cbuffers become ShaderRecordBufferKHR blocks (std430, no descriptor),
listed only in the interfaces of entries that use them. Builtins that
change during a ray tracing invocation are Volatile from SPIR-V 1.6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:19:52 -07:00
Peter Li f572308b2b SPIR-V library targets, KHR ray tracing and RayQuery
The IR holds every entry point of a library (functions remember the entry
they were lowered for), and the SPIR-V backend gives each entry its own
interface, computed from the variables its call tree uses. Adds ray
tracing stages (payload / hit attribute / callable data storage, TraceRay,
CallShader, ReportHit, IgnoreHit, AcceptHitAndEndSearch, the system value
builtins), RayQuery objects and methods, exported functions (Linkage in
universal environments), and the SPIR-V version macros of the target
environment. The codegen oracle now covers library targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:15:31 -07:00
Peter Li 116da4c87c SPIR-V counters through function parameters and buffer arrays
Which structured buffers need a counter now follows them into the
functions they are passed to (a fixed point over parameters and
resource locals); arrays of buffers get arrays of counters, indexed
like the buffer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:50:31 -07:00
Peter Li 7d3d39ec6d Add vk::SampledTexture
vk::SampledTexture1D ... SampledTextureCUBEArray as resource kinds of
their own (element type defaulting to float4, checked like textures'),
with their VkSampledTexture*Methods: SPIR-V combined image sampler
variables, sampled directly; Load, GetDimensions and [] go through
OpImage. .mips / .sample views as for textures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:45:50 -07:00
Peter Li 6e83f05c9c Add Gather with four offsets and compute derivatives
Gather with four offsets: four gathers taking a component each (DXIL),
ConstOffsets (SPIR-V). Derivatives and implicit-LOD sampling in
compute, mesh and amplification shaders: SM 6.6 in DXIL (with the
mesh / amplification flag), SPV_KHR_compute_shader_derivatives over
quads or lines of the thread group in SPIR-V.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:36:27 -07:00
Peter Li 4821f76b61 Add texture status arguments and CheckAccessFullyMapped
DXIL: the ResRet's status element goes to the status argument;
CheckAccessFullyMapped (op 71) - its operand is forwarded through
locals within a block, as the validator wants the status value itself.
The tiled resources flag follows CheckAccessFullyMapped and LOD clamps.
SPIR-V: the sparse image instructions (SparseResidency) and
OpImageSparseTexelsResident.

Also: cube Gather's extra argument is a status (cubes take no offsets),
and 1-component constant offsets are scalars in SPIR-V.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:32:52 -07:00
Peter Li 33f8315e12 Add remaining intrinsics and system values
Intrinsics on both backends: firstbitlow / firstbithigh, f32tof16 /
f16tof32, and / or / select, isnan / isinf / isfinite / isnormal, fmod,
integer dot, any / all on matrices, ddx_fine / ddy_fine, clip (SPIR-V),
IsHelperLane, and the device / group / all memory barriers.

SPIR-V system values: ClipDistance / CullDistance (packed into one
array per direction by semantic index, as dxc), ViewIndex, BaseVertex /
BaseInstance, ViewportIndex / Layer outside geometry shaders, shading
rate, SampleMask, FullyCoveredEXT, FragStencilRefEXT, barycentrics,
conservative depth; DXIL flags for barycentrics and extended command
info.

Intrinsic overloads: all '<>' types of an intrinsic share their
dimensions (scalars splat to the widest), as dxc - f16tof32(uint2) is
a float2. Typed resources of bool are U32.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:25:13 -07:00
Peter Li e77b648314 Add tbuffer and TextureBuffer<T>; fix 64-bit vector layout
tbuffer blocks and TextureBuffer<S>: DXIL TBuffer SRVs read a 16-byte
register at a time with bufferLoad (cbuffer layout); SPIR-V read-only
std430 buffer blocks.

SPIR-V layouts: only vectors of 32-bit (or narrower) components are
relaxed; 64-bit vectors keep their full alignment, which also raises
their structs' and arrays' alignment and padded size (as dxc).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:06:07 -07:00
Peter Li 8844c5445a Add structured buffers of matrices
SPIR-V: MatrixStride / RowMajor on the block's array member (std430
strides, as dxc). DXIL: rows and row components read through the whole
matrix (a column-major row is not contiguous).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:58:48 -07:00
Peter Li 913c63d810 Add templated byte-address Load/Store
Load<T> / Store<T> of any numeric, struct or array type: one access
per component at natural-alignment offsets (matrices by row in DXIL,
by column in SPIR-V, as dxc). DXIL uses 64-bit raw buffer overloads
from SM 6.3 and two words (makeDouble / splitDouble) before; SPIR-V
assembles 64-bit values from word pairs and 16-bit ones from halves.

DXIL locals and statics whose components have several sizes live in
struct-typed memory; 16-bit values set the low-precision shader flag.
Test files may give extra compiler flags with // FLAGS:.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:55:12 -07:00
Peter Li d676e56797 Add ConstantBuffer<T> and descriptor heaps
ConstantBuffer<S>: members (and bitfields, methods, whole-struct reads)
through the buffer, arrays of them, as function arguments. DXIL: cbuffer
resources from the handle; SPIR-V: a Block struct of its own per S.

ResourceDescriptorHeap / SamplerDescriptorHeap (SM 6.6): DXIL
createHandleFromHeap + annotateHandle (with the heap shader flags);
SPIR-V runtime arrays per element type on the next free bindings of set
0, as dxc.

SPIR-V specializations now take elements of resource arrays (and heap
elements at constant indices): the callee re-creates the access chain
instead of using the caller's id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:44:45 -07:00
Peter Li 2ff3afc7ef Add mesh and amplification shaders
Output arrays (vertices, primitives, indices) are a pointer space of
their own: stores through it become storeVertexOutput /
storePrimitiveOutput / emitIndices in DXIL and per-attribute output
arrays in SPIR-V (SPV_EXT_mesh_shader, SPIR-V 1.4+). Payloads are
struct-typed memory accessed by GEP in DXIL (getMeshPayload, a
groupshared or local variable for dispatchMesh) and TaskPayloadWorkgroupEXT
storage in SPIR-V. MS/AS state metadata, PSV info and PSG1. PSV now
reports UsesViewID with its (empty) masks.

The codegen oracle passes each test's -fspv-target-env (spirv-val
spells vulkan1.1spirv1.4 as vulkan1.1spv1.4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:29:20 -07:00
Peter Li af26ea5e9e Add hull and domain shaders
Both backends: control points in and out, patch constants, the patch
constant function (a function of its own in DXIL, called once after a
barrier in SPIR-V), SV_TessFactor / SV_InsideTessFactor (TessLevelOuter
/ TessLevelInner), SV_DomainLocation, SV_OutputControlPointID. DXIL:
PSG1, HS/DS state metadata and PSV info, the full SigPoint table.
SPIR-V: hull outputs and domain inputs located by semantic as dxc.
Also fixes geometry shader per-vertex inputs taking a location per
vertex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:12:06 -07:00
Peter Li b4e1450241 Add bitfields
Consecutive bitfields pack into hidden storage fields as dxc lays them
out (DXIL by type size, SPIR-V by exact type); member reads shift and
mask, writes read-modify-write. Also: dxc's bitfield diagnostics, sizeof
evaluation, SPIR-V base-class layout as a nested struct, operator[]
results are not addressable, and the codegen oracle reports crashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:50:22 -07:00
Peter Li 49c38a40a1 Allow out-of-line operator definitions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:33:41 -07:00
Peter Li 9f5cfebc17 Match dxc's operator overloading rules
Operators dxc forbids (=, compound assignments, ++, --, ->, new/delete,
non-member operators) are errors at the declaration; unary operators and
compound assignment on structs are 'scalar, vector, or matrix expected',
as in dxc. test/dxil/check.sh now fails when dxc rejects a test instead
of comparing with stale output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:26 -07:00
Peter Li 47c1edf791 Operator overloading (M0.2, part 2)
Member operator functions are ordinary methods; binary, unary, [], ()
and compound-assignment expressions on struct operands resolve to them
(op= falls back to op plus assignment) and lower as method calls on the
first operand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:30:02 -07:00
Peter Li 23fffdd49d Templates and member functions (M0.2, part 1)
Function, class, typedef and variable templates: each instance checks a
deep copy of the template's AST (src/front/ast_clone.zig) with the
parameters bound in a scope under the declaring scope, so lowering sees
ordinary functions and structs. Explicit arguments, defaults, deduction
from T, vector<T, N>, matrix<T, R, C>, arrays and class-template
instances; overload sets of function templates; partial and explicit
specializations (struct and variable templates); forward-declared class
templates completed by their definition; nested typedefs in instances.

Member functions now lower: a hidden this parameter, unqualified fields
and methods inside methods, this, and calls through copies for base
methods on derived objects and non-local objects (as Vulkan requires).
Template uses zdxc cannot model (dx/linalg.h metaprogramming) report
'not supported yet'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:26:03 -07:00
Peter Li ddf0082220 Geometry shaders on both backends
Lowering: per-vertex inputs (point/line/triangle/lineadj/triangleadj
arrays), stream outputs registered per stream parameter in order, and
Append/RestartStrip from any function (streams are compile-time only and
drop out of IR signatures). [maxvertexcount] and [instance].

DXIL: GSVIn/GSIn/GSOut signatures (SV_PrimitiveID as a shadow element,
SV_GSInstanceID by intrinsic), vertex-indexed loadInput, emitStream /
cutStream, GS state metadata, PSV0 geometry info, MaxVertexCount and
per-stream dependency tables. SPIR-V: the Geometry execution model and
modes, arrayed per-vertex inputs, OpEmitVertex / OpEndPrimitive (stream
variants for several streams), and the PrimitiveId, InvocationId, Layer,
ViewportIndex and SampleId builtins (Flat on integer fragment builtins).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:11:28 -07:00
Peter Li 3daa1943b8 SPIR-V target environments and wave intrinsics
-fspv-target-env picks the SPIR-V version (vulkan1.1: 1.3, vulkan1.2:
1.5, vulkan1.3: 1.6, ...). From SPIR-V 1.4 storage buffers use the
StorageBuffer class with Block and the entry interface lists all
globals. Wave/quad intrinsics become GroupNonUniform operations and
subgroup builtins (Vulkan 1.1+). The codegen oracle validates each test
in its own target environment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:03:51 -07:00
Peter Li 20678aa180 Static locals; DXIL wave and quad intrinsics
Static locals are private globals initialized on entry with the other
statics. DXIL wave/quad intrinsics (lane queries, votes, ballot, reads,
active and prefix reductions, quad reads and votes) match dxc's calls,
with the wave-ops shader flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:58:41 -07:00
Peter Li c4d5b0742c switch statements on both backends
Lowering builds one block per case label (consecutive labels fall
through), with break leaving the switch and continue reaching the
enclosing loop. DXIL gains the LLVM switch instruction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:56:48 -07:00
Peter Li 9e857cea54 Groupshared memory, atomics, counters and byte-address buffers
DXIL: groupshared variables are address-space-3 module globals (the
bitcode writer gains global variables, atomicrmw and cmpxchg), with the
PSV0 groupshared byte count. Interlocked* on groupshared memory,
structured and byte-address buffers, typed buffers and texels
(atomicBinOp / atomicCompareExchange). ByteAddressBuffer Load/Store
(2..4) and atomic methods; IncrementCounter / DecrementCounter, Append
and Consume buffers with the counter flag in metadata, PSV0 and SM 6.6
handle properties. Also fixes void intrinsics (barriers) in DXIL.

SPIR-V: the same atomics (OpImageTexelPointer for texels, Workgroup or
Device scope, Int64Atomics), byte-address buffer methods, and dxc's
separate counter buffers for counters and Append/Consume. Typed-buffer
elements reached through assignments read and write as images.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:51:26 -07:00
Peter Li 88fd16781a Intrinsics with out parameters; 64-bit DXIL cbuffer members
Lowering passes `out` arguments of intrinsics through temporaries and
`ref` arguments (atomic destinations) as the storage itself. sincos,
modf, frexp (dxc's bit-level lowering on DXIL; ModfStruct/FrexpStruct
per row on SPIR-V, so matrices work) and asuint(double, out lo, out hi).
DXIL constant buffers now load 64-bit and 16-bit members, and SPIR-V
64-bit fragment inputs are Flat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:40:10 -07:00
Peter Li 0148195c7c Arrays of resources on both backends
Arrays of textures, buffers and samplers (sized, multi-dimensional and
unsized) are register ranges: DXIL creates each element's handle where
it is used (lower bound + flattened index, folded when constant) and
records the range in metadata and PSV0; SPIR-V uses array-typed
variables and access chains (runtime arrays need descriptor indexing).
NonUniformResourceIndex sets the non-uniform handle flag on DXIL and
decorates the index, access chain, load and sampled image NonUniform on
SPIR-V, with dxc's capabilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:35:47 -07:00
Peter Li c9e924d2ab Loop unrolling and constant folding
A shared IR pass (src/ir/opt.zig) runs before both backends:

- Full unrolling of loops with a constant trip count: [unroll] loops, and
  loops whose texture calls take texel offsets, which DXIL and Vulkan need
  as constants (dxc gets them from its unroller). The induction variable
  is a local only loaded and stored, initialized before the loop and
  stepped once in the continue block; each copy reads it as a constant.
  Innermost loops go first, so nests unroll fully. [loop] loops, loops
  with break or continue (their jumps would leave SPIR-V's structured
  regions), non-constant bounds and trips over the limit stay loops.
- Constant folding of scalar and vector arithmetic, comparisons,
  conversions, splats, extracts and shuffles, wrapping integers to their
  width.

Integer `static const` scalars now lower to constants (loop bounds such
as `x < KERNEL_END`). Also fixes negative int16_t SPIR-V constants, which
were written zero-extended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:20:57 -07:00
Peter Li d708b31c55 Resources as function parameters and locals
DXIL: a resource local aliases the one handle stored into it (assigning
two different resources to one variable is reported, not miscompiled).
SPIR-V: functions with resource parameters are specialized per distinct
set of resource arguments, since Vulkan cannot pass buffer pointers to
functions; buffer block types are shared per HLSL type, and access chains
into buffers reached through parameters stay in Uniform std430 storage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:08:53 -07:00
Peter Li adde88078f 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:00:06 -07:00
Peter Li 476358a4df DXIL math intrinsics
atan2, fmod, isnan/isinf/isfinite, sign, step, smoothstep, degrees,
radians, ldexp, distance, reflect, refract, faceforward, cross and
determinant, lowered as dxc's HLOperationLower does (including its NaN
behavior for step and its atan2 quadrant fixups).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 07:42:59 -07:00
Peter Li 50a86683f2 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 07:40:06 -07:00
Peter Li 270c48fd55 Matrices and structs in codegen
SPIR-V:
- Float matrices are OpTypeMatrix with HLSL rows as columns (as dxc);
  integer / bool matrices are arrays of row vectors; 1xN / Nx1 are
  vectors. Arithmetic, comparisons, selects and component-wise
  intrinsics go row by row; mul maps to OpMatrixTimesVector /
  OpVectorTimesMatrix / OpMatrixTimesMatrix / OpDot with dxc's operand
  order (manual expansion for integers and vector-shaped matrices);
  transpose, matrix swizzles.
- Structs as OpTypeStruct. Buffer contents use laid-out type variants:
  std430 (structured buffers) and relaxed std140 (cbuffers), with member
  offsets, array strides, MatrixStride and RowMajor / ColMajor matching
  dxc; whole values convert between laid-out and plain types; access
  chains into structured buffer elements (buf[i].field).

Both backends:
- src/ir/layout.zig gains std430 and DXIL's packed structured-buffer
  layout and per-field row_major (recorded by Sema on fields and
  variables).
- Lowering: matrix-aware conversions (truncation, vector <-> matrix),
  constructors and initializer lists for structs and arrays, aggregate
  casts, derived-to-base conversion and stores through base casts.
- Entry points take and return structs: fields become signature
  elements, and a semantic on a struct numbers its fields.
- DXIL: structured buffers of structs (packed offsets, runs merged into
  4-wide loads / stores), buffer element access chains, mixed 32-bit
  struct locals, mul / transpose, cbuffer matrices by orientation.

oracle-codegen: SPIR-V 528 valid (was 313), DXIL 13 valid, 0 invalid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:37:25 -07:00
Peter Li 3feaaeecfb Constant buffers on both backends; default arguments
- Sema records each variable's cbuffer and the $Globals members in
  order; lowering turns a cbuffer (all members, since layout depends on
  every one) into a global of a synthetic struct type in a new .cbuffer
  space.
- src/ir/layout.zig: DX legacy cbuffer packing (DXIL) and dxc's relaxed
  std140 (SPIR-V), with field offsets, array strides and per-component
  offsets (column-major matrices).
- DXIL: cbufferLoadLegacy by register plus extractvalue, cbuffer handles
  and metadata records (size in bytes), $Globals first on the next free
  b register, CBV entries in PSV0.
- SPIR-V: Block structs with Offset / ArrayStride decorations matching
  dxc's bindings; bools stored as uints in externally visible storage.
- Calls fill missing trailing arguments from the parameters' defaults.

oracle-codegen: SPIR-V 313 valid, DXIL 6 valid (compute only), 0 invalid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:15:15 -07:00
Peter Li 22df96e507 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:05:51 -07:00
Peter Li d42fc71c5d IR, AST lowering and a SPIR-V backend
- src/ir/ir.zig: typed values in a structured CFG (selection / loop
  headers name their merge and continue blocks), memory-form locals,
  functions kept, plus a text dump (-zdxc-ir).
- src/ir/lower.zig: lowers the entry point and everything it reaches
  from the AST and Sema's new resolutions (variables, call targets,
  intrinsic overloads, struct fields): statements, structured loops and
  selections, short-circuit operators, implicit conversions, copy-in /
  copy-out arguments, swizzle stores, resource reads and writes, and a
  parameterless entry wrapper over the stage inputs and outputs.
- src/spirv/emit.zig: IR -> SPIR-V with dxc's conventions (BufferBlock
  structured buffers with std430 strides, default register bindings,
  stage builtins, GLSL.std.450 intrinsics, structured merges).
- test/oracle/codegen.sh: compiles every dxc-valid corpus file and
  validates the output: 281 files produce SPIR-V spirv-val accepts, 0
  invalid; the rest report the construct not supported yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:54:45 -07:00
Peter Li 2b6638b9c6 Sema: unit tests for operator, register, indexing and recursion checks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:37:21 -07:00
Peter Li b9eb170044 Sema/parser: fewer false errors on legacy and edge-case code
- Legacy effect syntax (technique blocks, effect object declarations,
  sampler_state assignments, local state blocks) is skipped with dxc's
  deprecation warnings.
- f16 / f32 / f64 float suffixes are accepted with dxc's 202x-extension
  warning (f16 needs -enable-16bit-types).
- Casts of lvalues that keep the component type are lvalues.
- No error for const locals without an initializer (dxc accepts them).
- 'using namespace dx' is accepted in every shader model.

oracle-verify: 85% of expected error lines caught, 12 false (was 51).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:27:44 -07:00
Peter Li e0908bb618 Sema: more of dxc's declaration, type and TU checks
- Type attributes (row_major / column_major / unorm / snorm) are tracked
  as sugar through template arguments and typedefs, with dxc's conflict
  and applicability errors.
- Reserved C/C++ keywords (volatile, signed, long, ...) are rejected by
  the parser as in dxc.
- Typed resource element and template-argument count checks; vector /
  matrix size ranges (long vectors need SM 6.9) and scalar elements;
  constant out-of-bounds vector / matrix indices; `unsigned` on
  non-integer types; mixed matrix swizzle forms.
- packoffset syntax and placement, conflicting register semantics,
  string placement rules, conflicting [shader] / [WaveSize] attributes,
  builtin base classes, unsized inner array dimensions.
- Call graph and dxc's no-recursion check over exported / entry
  functions (run only on an otherwise valid unit).
- Typedef redeclaration with the same type is accepted.

oracle-verify: 85% of expected error lines caught (was 79%), 51 false.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 04:18:43 -07:00
Peter Li 4fdb7a6cd0 Sema: port dxc's operator, conversion and register checks
- Binary, compound-assignment and unary operators follow dxc's
  CheckBinOpForHLSL / CheckUnaryOpForHLSL: operand requirements, bool
  lvalues, objects / structs / arrays, min-precision division, double
  modulo.
- Shape conversions use a port of ConvertDimensions / CombineDimensions
  for implicit and explicit conversions and binary operands; assignment
  errors use dxc's "cannot [implicitly] convert" wording, and a
  declaration with a bad initializer no longer cascades errors.
- register(...) syntax and per-type register class validation.
- Resource subscripts check index dimensions; `.mips` / `.sample` views;
  unknown members of resource types are reported.
- Uses of operators on structs that declare overloads stay silent
  (milestone 0.2, reported at the declaration).

oracle-verify: 79% of expected error lines caught (was 53%), 66 false.
oracle-sema: still no false errors on the dxc-valid corpus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:59:16 -07:00
Peter Li e8bca47e87 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).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:17:40 -07:00
Peter Li 412600a56e 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 02:27:52 -07:00
Peter Li 35222efd97 Proper error reporting: macro backtraces, include chains, clang/msvc output
Diagnostics now match dxc's layout on the cases compared (nested macros,
include chains, #line, bracket matching, missing ';', fatal errors), with
range underlines and fix-it hints on top.

Locations:
- Macro-expanded tokens get clang-style macro locations: an expansion
  record (spelling, expansion point, macro name, argument or body).
  Errors print at the expansion site with "expanded from macro" notes,
  outermost first; argument tokens report at their own position.
- Files remember the #include that entered them ("In file included from").
- #line remapping moved into the source manager so diagnostics use
  presumed locations.
- UTF-16 sources with a BOM are decoded, as dxc does.

Engine (src/diag.zig):
- Diagnostics carry a range, notes, fix-it text and a warning group.
- Rendered in source order: the preprocessor runs ahead of the parser, so
  diagnostics are sorted by token position; a fatal error hides only what
  follows it.
- -fdiagnostics-format=clang|msvc|vi, colors when stderr is a terminal
  (-f[no-]color-diagnostics), -WX, -no-warnings, -Wno-<group>,
  -ferror-limit=N (default 20, applied in source order).

Messages:
- Missing ';' is reported after the previous token with a ';' fix-it and
  context ("at end of declaration", "after expression", ...); parsing
  continues when the next token starts a new line.
- Missing ')' / ']' / '}' get "note: to match this '('".
- "expected ';' after struct", "unknown type name 'X'", macro redefinition
  with "previous definition is here" [-Wmacro-redefined], #warning
  [-W#warnings], carets on the directive name / file name.
- Errors at end of file point just past the last token.
- Empty read()/write() payload qualifiers and static_assert (HLSL 202x)
  are rejected, matching dxc under -HV 2021.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:50:47 -07:00
Peter Li 39b8e38765 Parser performance: keyword map and cheaper isIdent
pp_bench gains a `parse` mode (preprocess + parse). On the 4764-file,
13.1 MB DXC test corpus (ReleaseFast, interleaved A/B):
  parse  130.9 -> 78.2 ms (-40%); the parser's own share 92 -> 39 ms.

- A third of parse time was mem.eql in linear scans over keyword and
  builtin-type lists. All of them now go through one comptime
  std.StaticStringMap of per-word flags (reserved, qualifier, contextual,
  scalar, object, template): -38%.
- Token.isIdent compares lengths inline before calling mem.eql: -3%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:29:58 -07:00
Peter Li f6b2e9cf36 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:20:46 -07:00
Peter Li b8560a5b05 Preprocessor performance, round 2: inline the lexer into lexRaw
- Lexer.next is force-inlined into the preprocessor's raw token loop and
  the _Pragma check no longer runs a string compare on every identifier
  (pp: -3%).
- pp_bench gains a `load` mode (source manager only).

Overall vs 93d1e03 (before any tuning), 4764-file DXC test corpus,
ReleaseFast, interleaved A/B:
  lex    13.28 -> 10.34 ms  (-22%)
  load    6.89 ->  3.96 ms  (-43%)
  pp     50.11 -> 38.74 ms  (-23%)
  print  70.78 -> 48.99 ms  (-31%)

Tried and dropped in this round (no gain): a single-space fast path in
Lexer.next, and vector blank skipping limited to runs of 4+ spaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:50:49 -07:00
Peter Li 6e5860b1db 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:45:52 -07:00
Peter Li 93d1e03d3b Preprocessor: close the remaining review gaps
- '#' not followed by a parameter in a function-like macro is an error
  (object-like macros keep '#' literally), as in dxc.
- _Pragma("...") is destringized and handled like a #pragma line;
  "#pragma once in main file" now warns instead of registering.
- GNU line markers (`# 40 "file" 1 3`, `#40`) work like #line.
- Macro-argument pre-expansion and #if parentheses are limited to 512
  levels of nesting with a diagnostic, instead of overflowing the stack
  (dxc segfaults at a few thousand levels).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:35:58 -07:00
Peter Li c4f2220c4e Preprocessor review fixes: include search order, #if short-circuit, caching
- Quoted includes now search the directory of every file on the include
  stack (innermost first) before -I, and angled includes search only -I
  and the compiled-in headers, matching dxc. Angled lookups that only a
  quoted include would find get dxc's "use quotes" diagnostic.
- #if evaluation short-circuits &&, || and ?:; division by zero in an
  unevaluated operand is no longer an error (dxc accepts these).
- File contents are read once per path (with negative caching); each
  inclusion still gets its own FileId so #line state stays per inclusion.
- Include-guarded files (#ifndef X / #if !defined(X) wrapping the whole
  file) are not re-entered once X is defined. 2000 guarded includes:
  65 ms -> 2 ms per run (dxc: 3 ms).
- Skipped lines are now skipped token by token, so "/*" inside a string
  in an #if 0 block no longer swallows the #endif.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:29:29 -07:00
Peter Li feab1bf63b 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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:16:50 -07:00
Peter Li be9b6908cf M0.0: DXIL container, hash, bitcode writer and SPIR-V builder
- Port of DXC's container hash (ComputeHashRetail); matches dxc-signed
  containers on both padding paths.
- DXIL container reader/writer that signs its output.
- LLVM bitstream writer and a minimal LLVM 3.7 IR model that encodes types,
  constants, functions, core instructions and metadata as bitcode.
- An empty compute shader that dxv accepts for SM 6.0 through 6.9.
- SPIR-V builder; the empty compute module passes spirv-val (Vulkan 1.0).
- `zig build oracle` runs these checks against the DXC build.
- Zig 0.17 skill in .claude/skills/zig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:01:46 -07:00

Diff Content Not Available