- dxcapi: the legacy IDxcCompiler and IDxcCompiler2 interfaces (Compile,
Preprocess, CompileWithDebug) on the compiler object, as hassle-rs and
other older clients call them: entry point, profile and DxcDefines become
-E / -T / -D, the source blob is decoded by its encoding, and the result
is the IDxcResult (an IDxcOperationResult). kajiya's view app now runs on
zdxc's dxcompiler.dll unchanged.
- SPIR-V: a resource local nothing assigns (a struct copied with a
resource member left unset, read only behind a flag dxc's legalization
folds) reads as undefined: copies pass it on without assigning, and a
real use takes a resource global of the same type (an OpUndef pointer
would break logical addressing). kajiya's rtdgi/restir_spatial compiles.
- SPIR-V: globalOf gives up after 256 steps through copies between
resource locals, which can form cycles.
kajiya 77 of 78 compile (dxc 77), Sascha Willems' samples 307 of 308
(dxc 307), every object valid.
`dot(1, v)` bound dot's `numeric<c>` size from its first argument, a
scalar: c = 1, and v converted to a float (its x). dxc splats the scalar
to v's size instead, and so does zdxc now, for every intrinsic whose
arguments share a symbolic size (dot, distance, reflect, faceforward...).
Unreal decodes every instance's rotation with `dot(1, abs(Oct))`
(HemiOctahedronToUnitVector): StarterMap's beams were drawn rotated, or
not where they belong. 3,666 of Unreal's 11,488 compiles change.
Fixes from replaying kajiya's and SaschaWillems/Vulkan's HLSL through the
drop-in against dxc 1.7.2308:
- parser: `const` after the type (`float const x`, `uint const pass`)
joins the declaration's qualifiers.
- sema: binary integer literals (`0b10u`).
- sema: a function template instance's default argument that does not
convert to its parameter is an error only at a call that uses it, as
C++ instantiates defaults on use.
- intrinsics: a dimension several arguments share (`dot`'s `numeric<c>`,
`mul`'s `<r, c>`) takes the smallest argument's value; longer arguments
are truncated with dxc's -Wconversion warning at the argument.
`float4 a = mul(float3x3, float4)` is now rejected, as in dxc.
- SPIR-V: calls of functions returning resources (or structs holding
them) are inlined before resources are split out of structs, in every
stage; the splitter skips dead functions and walks blocks in reverse
postorder.
- SPIR-V: printf as NonSemantic.DebugPrintf with an OpString format.
Unreal's 11,488 compiles came out 1.7 times dxc's DXIL; now 1.09.
- cfg.zig: blocks that only branch to a block with no other
predecessor take it in; blocks holding only a branch are bypassed;
if/else arms with up to two cheap instructions become selects (dxc's
simplifycfg); a branch or switch going one way everywhere goes there.
- cse.zig: repeated computations over the dominator tree (arithmetic,
readnone dx.ops, cbuffer loads, handles), as EarlyCSE and GVN.
- promote: floating-point constants folded (arithmetic, FAbs, Saturate,
rounding, Sqrt, min/max), `zext i1 != 0`, `and` by known-zero bits,
and compares of selects and phis of constants (`(c ? 2 : 1) == 3`).
- [unroll] loops: their back edge is marked for the unroller, which
unrolls them up to dxc's 1024 iterations whatever their size.
- -Od promotes locals and removes dead code, as dxc's does: 14 times
dxc's size before, 0.89 now.
Every compile validates with Unreal's validator 1.8. Compile time
over the corpus: 584 s summed, 539 before.
[Shader("node")] functions in lib_6_8 libraries: the node input and
output objects (DispatchNodeInputRecord ... GroupNodeOutputRecords) in
sema, lowered as node_io / record accesses, and emitted with dxc's ops
238..253 (handles created and annotated with their I/O flags and record
size, records through getNodeRecordPtr in address space 6), the node
entry properties (launch, ID, dispatch grids, inputs and outputs with
record size, SV_DispatchGrid and alignment), and RDAT's node tables
(NodeID, function and I/O attributes, IONode, NodeShaderInfo).
Also: Barrier on records, GetRemainingRecursionLevels, atomics on record
fields and the *FloatBitwise compares (on the float's bits), node objects
in locals, parameters and return values, the NodeLaunch value check, and
dxc's noduplicate attribute on the SM 6.8 barriers.
DXC's work graph tests (test/workgraph in zdxc-internal): every case DXC
compiles, zdxc compiles too and validator 1.8 accepts, Unreal's node
shader (recording 10056) among them. Other output is unchanged.
- Barrier(memory types, semantics) and Barrier(UAV, semantics) lower to
barrierByMemoryType (244) and barrierByMemoryHandle (245), as dxc does;
libraries mark a function as needing a group for groupshared memory
(not via ALL_MEMORY) or group sync / scope semantics, as dxc's
BarrierRequiresGroup.
- shader.validator is the one validator version zdxc writes for; the
PSV runtime info (4 from 1.10, else 3) and RDAT's function records
(FunctionInfo3 from 1.10, else 2) follow it. Building for validator
1.8 is now changing that constant. (Validator 1.8 rejected the RDAT of
12 Glide libraries only because their records were 1.10's: built for
1.8, all of Glide's compiles validate.)
[WaveSize] was checked but not written: the entry properties had no wave
size, so a shader written for one wave size could run with another.
DXC writes tag 11 { size } before SM 6.8 and tag 23 { min, max,
preferred } from 6.8; PSV's and RDAT's expected wave lane counts take
the minimum and the maximum (or the minimum again).
Unreal: 44 of the 2,080 verify compiles use WaveSize and change; all
11,488 validate (validator 1.8).
Each loop's block list was sorted after the walk that found its blocks,
for every loop on each of unrollOne's calls (230 calls of about 200
loops on 00828). The body's bitset already holds them in order: they
are read out of its words.
The hill-climbing set: -8.1% (A/B); output unchanged on the verify
corpus.
Values stored to locals were forwarded to later loads in the same block
only when constants (or status values); every value now is. Such loads
need no getelementptr, load or conversion back from i32 storage.
- The hill-climbing set: -2.4% (A/B).
- Output: 1,349 of 19,624 verify compiles change (loads from locals that
stay in memory, such as arrays also indexed at run time, read the
stored value directly).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid; Glide's the same 12
invalid as before.
The same as a parameter's copy: a local stored once, whole, in the entry
block before any other use of it (the entry not branched back to),
otherwise only read and only indexed by constants, is now the stored
values (Unreal: `ViewState View = GetPrimaryView();` and the like). Its
store sets them; there is no alloca, store or load.
- The hill-climbing set: 781 ms to 718 ms (-8.1%).
- Output: 10,789 of 19,624 verify compiles change. Samples of 25 Unreal
and 25 Glide ones: Glide's differ only in the type table; Unreal's
lose zext / icmp ne / bitcast round trips through i32 storage, and
nothing else (no instruction added).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid; Glide's the same 12
invalid as before.
An inlined function's by-value parameter is copied into a local, and a
struct parameter copied whole: every component a getelementptr and a
store (and a bitcast or zext where storage mixes types), then a load per
read, all of which promotion deletes again. Unreal passes its view state
(thousands of components) by value: 00195 inlined a 6-instruction
function 256 times and lowered 3.3 million instructions for it.
A copy that is never written and only indexed by constants
(regsLocals) is now the argument's values themselves: no alloca, stores
or loads; reads take the components at their offset.
- The hill-climbing set: 1,095 ms to 773 ms (-29%); 00195 -59%, Unreal's
other shaders 10-28%, Glide's 1-4.5%.
- Output: 2,853 of the 19,624 verify compiles change. Those checked
differ only in the type table, or lose zext / icmp ne round trips of
bools through i32 storage (the same code, smaller).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid; Glide's 8,772 the
same 12 invalid as before this change.
unrollOne handles one loop and is called again until none is left (230
times on Unreal's slowest shader to unroll, 00828, with about 200 loops
in 13,000 blocks). Each call gave every loop an nb-byte body array and
scanned all nb blocks to visit it, rewrote a flag per instruction for
each loop it considered deleting, and built per-block successor and
predecessor lists. Bodies are now bitsets with sorted block lists,
deletion marks only the loop's own instructions (cleared after), and the
CFG's lists are slices of two packed arrays.
00828: unrolling 256 ms to 176 ms; the hill-climbing set -1.0% (A/B);
output unchanged on the verify corpus.
TypeTable's key (tag, a, b) has padding, so the automatic context hashed
it field by field through Wyhash's streaming interface on every vector,
matrix and array type looked up. KeyContext mixes its words.
Glide's shaders in the hill-climbing set: -1.1% (A/B); output unchanged
on the verify corpus.
finish passed each instruction to remapInst by value, got it back by
value and appended that: three copies of 48 bytes per instruction
lowered. It now copies each once, into its place, and renumbers there.
The hill-climbing set: -3.8% (A/B); output unchanged on the verify
corpus.
A Value has padding, so the emitter's maps keyed by one (the forwarding
map, status values, nonuniform values, texel copies) hashed it field by
field with Wyhash's streaming interface. ValueContext mixes its tag and
index into one word.
The hill-climbing set: -2.8% (A/B); output unchanged on the verify
corpus.
The type and constant pools hashed their small keys with Wyhash's
streaming interface (init, update per field, final). A splitmix64
finalizer over the fields does (slices still go through Wyhash).
The hill-climbing set: -1.1% (A/B); output unchanged on the verify
corpus.
Each stored component looked itself up in the status values and removed
its key from the forwarding map, both hash operations, though the first
is usually empty and the second often. Both are now skipped when empty.
The hill-climbing set: -0.8% (A/B, near noise); output unchanged on the
verify corpus.
Every liveness round re-examined every phi's entries. A phi has an entry
per edge, and folding only takes edges away, so a phi with as many
entries as its block has edges in from reachable blocks lost none; one
pass over the terminators counts those.
The hill-climbing set: -4.2% (A/B); output unchanged on the verify
corpus.
Dropping the entries of edges a folded branch removed checked each entry
against every earlier one, and counted its block's edges again: quadratic
in a phi's entries, every liveness round. Per-block counters (reset
after each phi) make it one pass.
ue-ps-q75: -2.5% (A/B); output unchanged on the verify corpus.
A file with any backslash (most headers: macro continuations) was copied
a byte at a time. The runs between backslashes are now found with
indexOfScalarPos (vectorized) and copied whole.
The hill-climbing set: preprocessing -5 to -8%; output unchanged on the
verify corpus.
std.StaticStringMap compares a word against every key of the same
length, and most identifiers the parser asks about are not keywords.
The word table is now an open-addressing table on an FNV hash, built at
compile time, comparing a stored hash before any bytes. The reserved
declaration specifiers and effect object names, scanned linearly per
identifier, are flags in it too.
Glide's small pixel shaders: -1.8% (A/B); output unchanged on the
verify corpus.
Sema.lookup hashed the name again in every scope out to the global one;
it now hashes once and probes each scope with that hash. TypeTable.scalar
interned its key through the type map on every call; it now keeps the
result per scalar.
Glide's shaders in the hill-climbing set: -3.1% (A/B); output unchanged
on the verify corpus.
Zig 0.17's ArenaAllocator is safe to share between threads: every
allocation is an atomic add, and some a compare-exchange. A compile
allocates millions of times on one thread. BumpArena does what it does
(chunks from a child allocator, growth and freeing in place for the
newest allocation, reset keeping capacity) without the atomics, and now
backs every arena that belongs to one compile: the DXIL emitter's and
module's, the front end's, rootsig, reflection, SPIR-V, the C API, the
job runner's workers and the DXC drop-in's per-thread arena. (The
drop-in's result objects keep std's: a caller may share them.)
The hill-climbing set: -5.4% (A/B), Glide's shaders -6.3%; output
unchanged on the verify corpus.
The constants block held every constant ever made, in the order they
were first asked for, including those only code that optimization later
removed used. Output bytes therefore depended on how much throwaway code
lowering made. writeBitcode now drops unused constants and numbers the
rest by first use (grouped by type, aggregates after their elements),
remapping every reference.
- Output: -7% on the hill-climbing set; Unreal shaders up to -59%
(ue-vs-2021: 10.2 KB to 4.2 KB).
- Cost: about 1.2 ms for the set (bitcode stage +18%, 0.25% of the total).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid (10056, a work graph
node shader, fails to compile as before).
Of promotion's 16 passes over every instruction, 11 look only at
allocas, getelementptrs or loads and stores. The first pass now lists
those, and the others walk the lists.
The hill-climbing set: -2.1% (A/B); output unchanged on the verify
corpus.
Resolving an intrinsic call matches every overload, comparing class names
as strings, and the same calls (mul, dot, saturate, ...) recur with the
same argument types. Resolutions are memoized by name, object type,
explicit type and the arguments' types and lvalues (not those that
reported a diagnostic).
The hill-climbing set: sema -5.7%, its allocation calls -25%; output
unchanged on the verify corpus.
Few instructions carry metadata (!dx.nonuniform), but each had room for
an optional (kind, node) pair. It is now an index into Module.inst_mds,
and every pass moves 14% less memory.
The hill-climbing set: -2.1%; output unchanged on the verify corpus.
Liveness runs again each time an empty branch folds (up to 10 rounds on
the largest functions), and each round scanned every instruction for the
ones with effects. That list does not change between rounds.
The hill-climbing set: promotion -16%; output unchanged on the verify
corpus.
The emitter kept each block's instructions (56 bytes, with their id) in a
growing list per block, copied whenever one grew. Instructions now go to
fixed chunks by id that never move, and blocks and the prologue list
4-byte ids.
The hill-climbing set: -5.5% (lowering -12%, finish -12%); output
unchanged on the verify corpus.
Every constant and structured buffer access laid out its whole struct
again (layout.fieldOffsets), and loading a struct component by component
did so for each component (layout.componentOffset). Both are now cached
per struct or type and layout rules.
The hill-climbing set: -2.8% (lowering -9.5%); output unchanged on the
verify corpus.
Each element access allocated its { 0, k } index pair and looked its
pointer type up; constant pairs are now shared (by the index constant)
and the last pointer type kept. loadPtr also skips the forwarding lookup
when nothing is forwarded.
The hill-climbing set: -7.8% (lowering -12.7%, its allocation calls
halved); output unchanged on the verify corpus.
DXIL emission spent most of its time on three lookups that grew with the
shader:
- componentType and flatCount recursed through a struct's fields for
every component, so loading or storing a struct of n components was
O(n^2). Each struct's component types are now worked out once
(structComps), and mixedSizes / mixedStorage are cached per type.
- Module.constant and Module.getType searched every existing constant or
type; they are now hash-indexed with the same equality. intType and
small i32 constants also have direct caches.
- unroll's dominates walked the immediate-dominator chain; it is now an
interval check on the dominator tree's depth-first numbering.
finish also keeps operand slices with nothing to renumber instead of
copying them.
Output is unchanged on the hill-climbing set, every Glide recording and
2,080 Unreal ones. The hill-climbing set compiles in 638 ms instead of
2,130 (-70%); DXIL lowering is 86% faster and unrolling 84%.
A caller that wants them points stats.current at a Stats for the thread;
zones in compile (options, preprocess, parse, sema, lower, ir_opt, DXIL,
SPIR-V) and in DXIL emission (lowering, finish, promote, sccp, unroll,
bitcode, container) add their time and the caller's allocation counts,
and counters record DXIL instructions lowered and kept. Without a Stats a
zone costs one thread-local load.
The Unreal work unrolled far more than dxc does: the IR unrolled any
small constant-count loop, and the DXIL unroller any loop of up to 256
trips. On Glide's GlimmerProbeTrace and GlimmerSHUpdate compiles took
10-17x longer and DXIL grew to 470 KB (dxc: 155 KB), so Glide's
replayed compiles took 2.7x as long as with main.
- the IR's automatic unrolling is gone again (it did little for Unreal)
- DXIL unrolls a loop only when unrolled it stays within 300
instructions, as dxc unrolls only small loops without [unroll]
- SCCP visits blocks in reverse postorder, so it settles in a few passes
Glide, against main (bb942b0): 24 threads 1.36 s vs 1.25 s, serial sum
13.2 s vs 11.8 s, DXIL 58.1 MB vs 61.4 MB. Unreal's corpus still
compiles, validates, and reflects no UAV dxc leaves out.
Every shader the editor compiles (11,488 recorded Compile calls) now
compiles, passes DXC 1.8's validator, and reflects bindings the engine
accepts; the editor runs with the D3D debug layer clean.
Front end and semantics:
- -HV 2016..2018 and 2021, with HLSL 2018's component-wise &&, || and ?:
- overload ranking with DXC's conversion costs (worst, then sum), where
intrinsics compete with user functions and templates; ref parameters
of intrinsics (Interlocked* destinations) match exactly
- template class methods checked on use; elaborated struct declarations;
struct fields before globals in methods
- layout of structs over 256 fields
DXIL backend:
- loops with a constant trip count unrolled after promotion (unroll.zig)
- sparse conditional constant propagation (sccp.zig)
- loops with no effects deleted; constant switches folded; float compares
of constants folded; phis read on the edge their branch's condition
decides; empty branches folded through chains of empty blocks
- unreachable blocks, unused groupshared, and resources no code uses any
more dropped; shader flags, PSV and handle properties from what is left
- 64-bit typed resources and atomics