Commit Graph

90 Commits

Author SHA1 Message Date
Peterino2 97517cc5b1 SPIR-V: selection controls from [branch] and [flatten]
[branch] and [flatten] on if and switch were dropped: every
OpSelectionMerge had selection control None, leaving the driver to
flatten or keep the branch by its own heuristics. They now become
DontFlatten and Flatten, as in dxc (the Hyperion engine's shaders use
them 21 times). The IR keeps them on the header block; unrolling and
inlining carry them over.
2026-11-02 08:00:54 +00:00
Peterino2 d39ee30a4c SPIR-V: promote locals to SSA values; inline top-down
ir/ssa.zig, after inlining:

1. A local struct or array accessed only whole and with constant
   indices is split into one local per leaf member / element (scalar
   replacement, up to 64 leaves): whole reads construct the value,
   whole writes store each part. Promoting whole aggregates instead
   made each member write a copy of the aggregate; on the Glide shader
   that has many of them RADV then spilled ten times as many scalar
   registers.
2. Locals loaded and stored only whole (no resources) become SSA
   values: semi-pruned phi placement over dominance frontiers,
   renaming over the dominator tree, trivial phis folded, dead phis
   (cycles included) dropped. Reads before any write are the new IR
   `undef` (OpUndef). Phis take one value per predecessor the emitter
   writes, unreachable merge and continue targets included.

Constants that were behind locals fold afterwards. The SPIR-V emitter
emits OpPhi, patching operands emitted after the phi.

The inliner now works top-down from the entry points (each call gets a
copy of the callee's own body, whose calls are inlined as the scan
reaches them), copies only instructions in the callee's blocks (and
locals on first use), and remaps only instructions naming a call
result; scans use a non-allocating operand visitor (opt.eachOperand).

On Glide: loads 115040 -> 20322, stores 63644 -> 5832 (dxc: 11423,
2498), SPIR-V 12.0 -> 13.2 MB (callee bodies copied); compile time
587 -> 771 ms on 327 shaders (dxc: 8.6 s). Two more corpus files
compile (texel offsets that are constants once promoted).
2026-11-02 07:54:10 +00:00
Peterino2 afc4587596 SPIR-V: inline calls in the IR
dxc's SPIR-V gets its calls inlined by legalization; zdxc emitted every
function and left inlining to the driver, with 10361 calls across the
Hyperion engine's Glide shaders. ir/inline.zig now inlines bottom-up
before emission:

- The calling block is split at the call: it branches to a copy of the
  callee, and the rest of the block (terminator and merge included)
  moves to a continuation block. Parameters become the arguments.
- A callee with one return outside every construct branches from it to
  the continuation. Returns inside selections or switches become
  breaks out of a loop that runs once around the callee, the return
  value going through a local.
- Callees that return from inside a loop, [noinline] ones, ones with
  RayQuery or by-reference resource parameters, and ones returning a
  resource from several places stay functions (resource arguments then
  still get specializations).
- Functions nothing reaches any more are marked dead and not emitted.

Only modules with vertex, pixel and compute entry points and no
rasterizer-ordered views for now (the emitter treats the others'
functions specially). -Od and the new -zdxc-no-opt skip it; -zdxc-ir
prints the IR after the SPIR-V passes.

On Glide: 37 calls left; the SPIR-V grows (517k to 838k instructions,
callee bodies copied, one-trip loops) until promotion to SSA values
removes the locals; compile time 597 to 765 ms. The driver's own
statistics barely move, except one compute shader passing float4[28]
arrays by value, whose copies now take more scratch.
2026-11-02 07:10:23 +00:00
Peterino2 2ed08b08e1 SPIR-V: loop controls from [unroll] and [loop]
Loops the IR keeps (its unrolling gave up, or [loop] asked it not to)
lost their attribute: every OpLoopMerge had loop control None. The
driver now gets Unroll for [unroll] and DontUnroll for [loop], as from
dxc.

On the Hyperion engine's Glide shaders this is what made its half
resolution Glimmer irradiance pass about 5% slower than with dxc: an
[unroll] loop over a run-time count that RADV unrolls for dxc's output
stayed a loop for zdxc's (2381 instructions against dxc's 5765; now
5856).
2026-11-02 06:55:33 +00:00
Peter Li 01a66d456a SPIR-V: dynamically selected resources in calls and resource locals
A resource array element at a dynamic index (textures[i], bindless)
passed to a function failed: specializations re-create constant
elements only. The recipe now keeps dynamic index positions; the call
passes their values as extra arguments, the specialization takes them
as parameters and builds the access chain from them, and passes them
on to its own callees. A NonUniformResourceIndex selection stays
NonUniform in the specialization.

A resource local assigned different elements of one resource array
(tex = textures[a] in one branch, textures[b] in another) failed with
"assigning different resources to one variable". Such a local is now
kept as Function variables holding the indices: each assignment stores
them, each read loads them and re-creates the element. dxc emits an
OpPhi of images there, which spirv-val rejects, unless inlining folds
the branches away.
2026-11-01 20:16:21 -08:00
Peter Li 5f9543170d Parse the builtin pseudo-enum typedefs as type names
RAY_FLAG, RAYQUERY_FLAG, COMMITTED_STATUS, CANDIDATE_TYPE,
MEMORY_TYPE_FLAG and BARRIER_SEMANTIC_FLAG were declared as uint
typedefs in Sema but unknown to the parser, so `const RAY_FLAG f = ...`
failed with "unknown type name".
2026-11-01 20:16:21 -08:00
Peter Li 0d4837d5fb Static locals read from another static's initializer
A function-local static whose initializer reads another local static
(static const int n = min((order + 1) * (order + 1), 9)) failed with
"this variable is not supported yet": initializers are lowered in
functions of their own, where the other static is not a local. It is
its private global there, as a file-scope static is.
2026-11-01 20:16:21 -08:00
Peter Li 2716772d98 Accept "-opt value" passed as one argument
dxc's option parser skips spaces after an option name, so a separate
option given as "-HV 2021" in a single argument is "-HV" with value
2021 (programs calling IDxcCompiler3::Compile pass it that way).
zdxc rejected it as an unknown argument. "-HV2021" stays an error, as
in dxc.
2026-11-01 20:16:21 -08:00
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 265fd17fd8 removing the zdxc binary 2026-11-01 15:26:33 -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 9aa5f83508 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).
2026-11-01 09:27:47 -08:00
Peter Li 3fbbd5c4b5 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.
2026-11-01 09:12:38 -08:00
Peter Li 717a0a9fad 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.
2026-11-01 08:53:09 -08:00
Peter Li d33c3838e2 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.
2026-11-01 00:58:07 -07:00
Peter Li 3c4372d2bc 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.
2026-11-01 00:39:38 -07:00
Peter Li 8a6698c925 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).
2026-11-01 00:28:56 -07:00
Peter Li 5f4d2dc8e4 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.
2026-11-01 00:07:09 -07:00
Peter Li e88c8500d1 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.
2026-10-31 23:55:37 -07:00
Peter Li 56d0da0b92 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.
2026-10-31 22:10:48 -07:00
Peter Li e830120128 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.
2026-10-31 21:55:56 -07:00
Peter Li 45b4805a25 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.
2026-10-31 21:12:07 -07:00
Peter Li 3c7fdb2ad2 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).
2026-10-31 20:49:41 -07:00
Peter Li 77f4fb539c 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.
2026-10-31 20:25:57 -07:00
Peter Li 56adacfc4a 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.
2026-10-31 19:22:10 -07:00
Peter Li 478bb4faf6 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.
2026-10-31 18:58:46 -07:00
Peter Li d05bf92af5 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).
2026-10-31 17:26:53 -07:00
Peter Li 9e0375fbc5 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.
2026-10-31 17:08:44 -07:00
Peter Li 3f33ec209b 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.
2026-10-31 16:55:14 -07:00
Peter Li 726d0016eb 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.
2026-10-31 16:47:35 -07:00
Peter Li eff23d800e 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.
2026-10-31 16:38:16 -07:00
Peter Li 1c5d9bed09 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.
2026-10-31 16:09:26 -07:00
Peter Li 41d973183b 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.
2026-10-31 16:04:30 -07:00
Peter Li 198bb1d2af 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.
2026-10-31 16:04:01 -07:00
Peter Li 06058621ee 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.
2026-10-31 15:57:14 -07:00
Peter Li 948a7fd864 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).
2026-10-31 15:49:15 -07:00
Peter Li bd04934bb3 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.
2026-10-31 15:45:56 -07:00
Peter Li 3db2bf6dda 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.
2026-10-31 15:24:08 -07:00
Peter Li 16eada87b0 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.
2026-10-31 15:19:52 -07:00
Peter Li ebf4d1dd23 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.
2026-10-31 15:15:31 -07:00
Peter Li bfd5ba9d3f 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.
2026-10-31 13:50:31 -07:00
Peter Li 9c6968061f 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.
2026-10-31 13:45:50 -07:00
Peter Li e21f2d95e7 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.
2026-10-31 13:36:27 -07:00
Peter Li 11904b196a 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.
2026-10-31 13:32:52 -07:00
Peter Li 5a59d07211 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.
2026-10-31 13:25:13 -07:00
Peter Li 707fad0b90 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).
2026-10-31 13:06:07 -07:00
Peter Li 5ac8c1254a 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).
2026-10-31 12:58:48 -07:00
Peter Li c32f29c596 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:.
2026-10-31 12:55:12 -07:00