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.
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.
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.
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).
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.
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.
[[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.
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.
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.
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.
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.
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.
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.
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).
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).
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:.
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.
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).
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.
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.
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.
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.
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'.
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).
-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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
- 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.
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.
- 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.
- 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).
- 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.
- 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.
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).
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.
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.
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%.
- 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.
- 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 74979f0 (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.