Compare commits

..

66 Commits

Author SHA1 Message Date
Peterino2 76a41b790b Merge branch 'ue-workgroups' 2026-11-04 08:51:52 -07:00
Peterino2 0ba9de16fa documentation updates 2026-11-04 08:51:40 -07:00
Peter Li 68f9a9d061
Merge pull request #3 from peterino2/ue-workgroups
Ue workgroups
2026-11-04 01:03:32 -07:00
peterino2 eeb5a3fcd1 Merge open-engine-fixes: kajiya and Sascha Willems' samples 2026-11-03 23:01:37 -08:00
peterino2 8d3026b57e Drop-in: IDxcCompiler/IDxcCompiler2; SPIR-V: unassigned resource reads
- 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.
2026-11-03 22:59:17 -08:00
peterino2 992307e183 README: Unreal's editor compiles its startup shaders 4.3 times faster 2026-11-03 22:48:05 -08:00
peterino2 24bdbfe7e9 sema: a vector size shared by intrinsic arguments takes the widest
`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.
2026-11-03 22:45:45 -08:00
peterino2 886b64da89 Open engine corpora: kajiya and Sascha Willems' samples
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.
2026-11-03 22:12:27 -08:00
peterino2 987b2a573c README: Hyperion's numbers at ddefd45, and Unreal's editor 2026-11-03 20:55:41 -08:00
peterino2 ddefd450f7 dxil: smaller code, as dxc's optimizer makes it
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.
2026-11-03 19:45:14 -08:00
peterino2 e4cf1caaf2 work graphs: node shaders, as dxc compiles them
[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.
2026-11-03 14:13:29 -08:00
peterino2 8a77bb723b dxil: SM 6.8 Barrier(), and one validator version for PSV and RDAT
- 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.)
2026-11-03 13:36:18 -08:00
peterino2 285505e36b dxil: write [WaveSize] to the entry, PSV and RDAT
[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).
2026-11-03 13:20:03 -08:00
Peter Li 3ba5acaf75
Merge pull request #2 from peterino2/hillclimb
Hillclimb
2026-11-03 13:31:41 -07:00
Peter Li cedf1b46e9 Merge remote-tracking branch 'gh/main' into hillclimb 2026-11-03 11:37:11 -08:00
Peter Li 00adb5a617 rc filter 2026-11-03 11:34:24 -08:00
peterino2 bfc0e58319 Merge remote-tracking branch 'origin/main' into hillclimb 2026-11-03 11:30:57 -08:00
peterino2 35dedc171e unroll: a loop's blocks in order from its bits, not a sort
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.
2026-11-03 11:05:35 -08:00
peterino2 9bb4feb32b dxil: forward every value stored to a local to loads in its block
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.
2026-11-03 11:01:24 -08:00
peterino2 531b5c6227 dxil: a local stored once from a value can be that value too
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.
2026-11-03 10:55:24 -08:00
peterino2 e4d5bb5ddc dxil: a by-value parameter's copy can be the argument's values
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.
2026-11-03 10:47:31 -08:00
peterino2 9b2fc76c56 Merge branch 'constprune' into hillclimb 2026-11-03 10:30:01 -08:00
peterino2 5c99b1c4db unroll: loop bodies as bitsets and block lists; a packed CFG
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.
2026-11-03 10:26:24 -08:00
peterino2 4a12f2b89a sema: hash type keys as words
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.
2026-11-03 10:11:09 -08:00
Peter Li 8cec70db9e Add MIT LICENSE 2026-11-03 10:09:48 -08:00
peterino2 0634987f5e dxil: finish renumbers instructions in place
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.
2026-11-03 10:07:17 -08:00
peterino2 69b33c2af2 dxil: hash Value keys as one word
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.
2026-11-03 10:01:35 -08:00
peterino2 2c8f5c5f53 dxil: hash pool keys with a word mix, not streaming Wyhash
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.
2026-11-03 09:59:16 -08:00
peterino2 5c31ce84b8 dxil: storePtr skips forwarding-map lookups that cannot match
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.
2026-11-03 09:36:45 -08:00
peterino2 bc8aee17eb promote: skip phis that lost no edges when branches fold
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.
2026-11-03 09:29:03 -08:00
peterino2 6d38019763 promote: decide which phi entries stay in one pass
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.
2026-11-03 09:26:30 -08:00
peterino2 3833ea57d0 source: splice lines by copying the runs between backslashes
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.
2026-11-03 09:16:19 -08:00
peterino2 9f8c46792b parser: keywords in a hashed word table, not length-bucketed scans
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.
2026-11-03 09:09:23 -08:00
peterino2 e8982e3378 sema: hash a name once per lookup; cache scalar types
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.
2026-11-03 09:03:38 -08:00
peterino2 b659b5a4af BumpArena: a single-threaded arena for compiles
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.
2026-11-03 08:59:20 -08:00
peterino2 0a2607946f dxil: write only used constants, in order of first use
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).
2026-11-03 08:58:02 -08:00
peterino2 ab2641a57d promote: walk lists of allocas, getelementptrs and memory accesses
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.
2026-11-03 08:51:20 -08:00
peterino2 e05a217cc1 sema: resolve each intrinsic call signature once per compile
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.
2026-11-03 08:46:15 -08:00
peterino2 5019d2b838 dxil: instruction metadata out of line (instructions 56 -> 48 bytes)
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.
2026-11-03 08:33:41 -08:00
peterino2 dfb629ace0 promote: list what has effects once, not every liveness round
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.
2026-11-03 08:29:20 -08:00
peterino2 ec64ffa4b0 dxil: instructions in chunks by id; blocks list ids
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.
2026-11-03 08:25:53 -08:00
peterino2 1594c37464 dxil: field and component offsets worked out once per type
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.
2026-11-03 08:23:18 -08:00
peterino2 c423c0c1a0 dxil: share getelementptr index slices, cache elementPtr's pointer type
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.
2026-11-03 08:19:43 -08:00
Peterino2 610737354c new readme, and updated workflows 2026-11-03 09:18:17 -07:00
Peterino2 57800241e9 shorter readme, new manual 2026-11-03 09:15:14 -07:00
peterino2 d3538e1db3 dxil: per-type layouts, indexed constants and types, O(1) dominance
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%.
2026-11-03 08:13:21 -08:00
Peter Li c5742db4e3
Merge pull request #1 from peterino2/unreal-engine
Unreal engine support
2026-11-03 08:30:05 -07:00
peterino2 e6a089eb34 stats: time and allocations per compilation stage
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.
2026-11-03 01:03:23 -08:00
peterino2 72f1760844 Unroll small loops only, and SCCP in reverse postorder
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.
2026-11-03 00:12:50 -08:00
peterino2 a80a77c0b8 Compile Unreal Engine 5.8's shaders as a DXC drop-in
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
2026-11-02 23:34:14 -08:00
Peterino2 077696151a github workflow 2026-11-02 14:22:40 -07:00
Peterino2 0de619c694 Merge remote-tracking branch 'origin/main' 2026-11-02 14:15:49 -07:00
peterino2 bb942b06c7 DXIL reflection for the DXC drop-in
Unreal Engine's D3D12 shader compiler needs DXC_OUT_REFLECTION and reads
every shader's parameters through ID3D12ShaderReflection; it also strips
parts with IDxcContainerBuilder and blobs through IDxcLibrary.

- The DXIL emitter builds the reflection with the object (dxil/reflect.zig):
  bound resources, constant buffers with their variables and types, and
  per-function data for libraries. A variable is marked used from the
  optimized code, by the cbuffer components actually loaded, as DXC marks
  them. Input signature usage is likewise taken from the optimized code.
- The drop-in returns it as DXC_OUT_REFLECTION, and IDxcUtils::
  CreateReflection serves ID3D12ShaderReflection and
  ID3D12LibraryReflection over it.
- New classes: DxcContainerBuilder and DxcContainerReflection; the utils
  object also answers IDxcLibrary.

On the 65 test/dxil shaders, reflection printed through the D3D12
interfaces matches DXC 1.8's on 46; the rest differ in details clients do
not read (bitfield members, -Zpr matrix classes, resource order).
2026-11-02 13:14:37 -08:00
Peterino2 7079b6385d adding reference to zdxc.org 2026-11-02 14:07:27 -07:00
Peterino2 951777a23d Udated readme, adding github actions 2026-11-02 13:58:46 -07:00
peterino2 2526fa65f7 --job: keep file I/O off the compile threads
Windows (here, with Defender's on-access scanning) serializes opening
files: creating the corpus's 8,772 outputs takes about 1.8 s whatever
the thread count. The compile threads blocked on it, so --job barely
gained past 8 threads.

- A reading thread reads each job's input ahead of the compiles (at
  most 256 jobs ahead), and a writing thread writes the outputs, in job
  order, after them. An output that cannot be written is reported after
  every job's output and fails its job.
- Files the jobs read through the compiler (headers) are cached for the
  whole run, with misses remembered, so each is opened once instead of
  once per job and include directory searched.

On the Glide corpus: compiles only, 13.6 -> 12.1 s on 1 thread and
2.75 -> 2.6 s on 24; preprocess and compile, 36.2 -> 17.1 s on 1 thread
and 7.3 -> 5.9 s on 24, which is about the time it takes to create its
17,544 output files. Outputs and diagnostics are identical to 0622292
on all 17,544 calls.
2026-11-02 07:28:12 -08:00
peterino2 b5eba0625f Allocate less per compile
Every compile ran in an arena, where a growing list leaves each old
buffer behind, and a few sites dominated: the Glide corpus's 8,772
compiles allocated 38 GB. Now 24 GB:

- intrinsics: build the Db once per process and share it read-only
  (it was rebuilt from the static table on every compile, 3.5 GB);
- parser: reserve the token list from the source size (5.2 GB of
  regrowth), and collect name parts on the stack (25M allocations);
- dxil emit: reserve the function's instruction list in finish (5.0 GB);
- sema: reserve resolutions from the token count (1.0 GB).

zdxc --job on the corpus: 15.4 -> 14.3 s on 1 thread, 3.0 -> 2.65 s on
24. Output is byte-identical on a 1,462-compile subset.
2026-11-02 07:06:58 -08:00
peterino2 22e1bcbc2a dxil emit: look instruction types up by id
valueType searched the prologue and every block for the instruction,
so lowering was quadratic in function size. On the Glide corpus it was
half of all samples in zdxc --job; with a type per id the corpus's
8,772 compiles take 15.4 s on 1 thread (was 21.6 s) and 3.0 s on 24
(was 7.4 s). Output is byte-identical on a 1,462-compile subset.
2026-11-02 06:46:52 -08:00
peterino2 db87b47e6f dxcapi: keep each thread's compile arena between calls
Freeing the arena after every Compile gave its blocks back to the OS
(smp_allocator maps 64 KiB and up directly), so each call faulted about
4 MB of fresh pages in again. On the Glide corpus's 8,770 compiles that
was 9.06M page faults and up to 28 s of kernel time; with the arena kept
(reset to at most 64 MiB) it is 0.4-1.0M, and the replay is 25% faster
on 1 thread, 30% on 8 and 16% on 24. Output is byte-identical.
2026-11-02 06:37:44 -08:00
peterino2 06222920e5 Merge dev/windows-fix: DXIL local promotion and copy elision, on the SPIR-V IR passes
Glide (Hyperion engine) now runs on zdxc's DXIL.

# Conflicts:
#	src/dxil/emit.zig
2026-11-02 01:16:31 -08:00
peterino2 4666275a0b DXIL: fold promoted values, pass constant buffer structs in place
GlimmerProbeTrace (Glide) still came out at 374 KB of DXIL against
dxc's 155 KB, with 130 allocas against 40. Most of the remainder:
by-value struct parameters copied out of the constant buffer at every
call (GlimmerGroundParams and GlimmerSpanParams, 32 i32s each), then
indexed dynamically, which pinned each copy in memory.

- Arguments loaded from a constant buffer are passed as the constant
  buffer place itself, structs as well as arrays (not with matrices,
  whose constant buffer access is narrower than a local's). Locals still
  alias only within a block with no write since. The alias now comes
  first in local_var lowering, so the skipped parameter store always
  matches.
- Peepholes on promoted values: bitcast round trips (int/float mixing
  locals store i32s), constant integer arithmetic and comparisons,
  identities, selects on a constant. A constant out-of-bounds array
  index this exposes (on a path that cannot run) becomes 0, since the
  validator rejects it.
- Inlined callees' array locals return to a per-type pool on return,
  for later callees to reuse.
- -Od and -zdxc-no-opt skip promotion, aliasing and reuse, as they skip
  the SPIR-V IR passes.

GlimmerProbeTrace: 374 KB to 191 KB, 21 allocas, 282 bitcasts (from
7198). Its pipeline builds in 3.6 s on an RX 9070 XT (was 5.1 s). All
of Glide's 400 DXIL compiles: 5.91 MB (dxc: 6.11 MB), 7.1x faster than
dxc. All pass dxc 1.8.2505's validator, and Glide renders.
2026-11-02 01:13:16 -08:00
peterino2 dce6d0eade DXIL: promote locals to SSA, elide by-value array copies
Locals were left as allocas, so every access was a store or a reload.
Glide's GlimmerProbeTrace came out as 2.3 MB of DXIL (DXC: 155 KB) that
AMD's driver took over ten minutes to build into a pipeline, and the game
stalled on a black screen.

- promote.zig: SROA + mem2reg over the finished function. An alloca whose
  accesses are loads and stores through constant indices becomes one SSA
  variable per element, with phis at the iterated dominance frontiers.
  Trivial phis fold away, and dead instructions go. Locals read before
  they are written read zero, since the validator rejects reads of undef.
- Dynamically indexed locals pin only what the index can reach. The
  emitter records each dynamic getelementptr's range (the indexed array's
  extent), and the rest of the local is still promoted.
- A by-value array parameter that the callee only reads aliases the
  caller's storage when the argument was loaded from a local in the same
  block with no write since. This drops the per-call copies.
- Declarations that lose their last call are pruned before writing, since
  the validator rejects unused external functions.

On Glide's 400 DXIL compiles, total output goes from 34.5 MB to 6.8 MB
(DXC: 6.1 MB), and GlimmerProbeTrace from 2.3 MB to 374 KB. Its
pipeline now builds in about 5 s. All 400 objects pass DXC 1.8.2505's
validator (checked with a copy built to claim validator 1.8), and Glide
renders on zdxc.
2026-11-02 00:57:49 -08:00
Peter Li cd951ea29b DXIL: dynamic constant buffer vector indices, library resource arrays, selected resource locals
- A constant buffer vector indexed at run time loads the whole vector and
  selects the component.
- Resource arrays in libraries: globals of class arrays, mangled as
  pointers to their element (as dxc); each access loads its element for
  createHandleForLib. NonUniform indices put !dx.nonuniform on the
  getelementptr, so the bitcode writer now writes metadata kinds and
  instruction attachments.
- Array types in mangled names count their dimensions as dxc does.
- A resource local assigned different elements of one resource array keeps
  the element's index and makes the handle where it is read.
2026-11-02 00:57:49 -08:00
Peter Li ab7b167270 DXIL: keep the library prologue's use marks per thread
markUses kept the array it marks in a static, which concurrent library
compiles under --job shared: one could mark into another's array, or index
past its own. Make it thread-local.
2026-11-02 00:57:49 -08:00
Peter Li 83f2298773 DXIL: dynamic constant buffer vector indices, library resource arrays, selected resource locals
- A constant buffer vector indexed at run time loads the whole vector and
  selects the component.
- Resource arrays in libraries: globals of class arrays, mangled as
  pointers to their element (as dxc); each access loads its element for
  createHandleForLib. NonUniform indices put !dx.nonuniform on the
  getelementptr, so the bitcode writer now writes metadata kinds and
  instruction attachments.
- Array types in mangled names count their dimensions as dxc does.
- A resource local assigned different elements of one resource array keeps
  the element's index and makes the handle where it is read.
2026-11-01 21:24:32 -08:00
Peter Li 5792d653b5 DXIL: keep the library prologue's use marks per thread
markUses kept the array it marks in a static, which concurrent library
compiles under --job shared: one could mark into another's array, or index
past its own. Make it thread-local.
2026-11-01 21:24:31 -08:00
64 changed files with 10705 additions and 508 deletions

99
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,99 @@
name: Cross-platform builds
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
permissions:
contents: read
concurrency:
group: builds-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: ${{ matrix.name }}
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- name: windows-x86_64
target: x86_64-windows-gnu
archive: zip
- name: linux-x86_64
target: x86_64-linux-gnu.2.28
archive: tar.gz
- name: macos-aarch64
target: aarch64-macos.13.0
archive: zip
steps:
- name: Check out source
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Install Zig
uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2
with:
version: 0.17.0
- name: Build compiler, C library, and DXC drop-in
run: >-
zig build install dropin
-Doptimize=ReleaseFast
-Dtarget=${{ matrix.target }}
-Dcpu=baseline
--prefix zig-out/${{ matrix.name }}
- name: Package Linux build
if: matrix.archive == 'tar.gz'
run: >-
tar -czf zdxc-${{ matrix.name }}.tar.gz
-C zig-out/${{ matrix.name }} bin lib include
- name: Package Windows and macOS builds
if: matrix.archive == 'zip'
working-directory: zig-out/${{ matrix.name }}
run: zip -r ../../zdxc-${{ matrix.name }}.zip bin lib include
- name: Upload build
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: zdxc-${{ matrix.name }}
path: zdxc-${{ matrix.name }}.${{ matrix.archive }}
if-no-files-found: error
retention-days: 14
release:
name: Publish release binaries
needs: build
if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, '-rc')
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
contents: write
steps:
- name: Download all platform bundles
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
pattern: zdxc-*
path: artifacts
merge-multiple: true
- name: Create or update GitHub Release
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
TAG: ${{ github.ref_name }}
run: |
if gh release view "$TAG" >/dev/null 2>&1; then
gh release upload "$TAG" artifacts/*.tar.gz artifacts/*.zip --clobber
else
gh release create "$TAG" artifacts/*.tar.gz artifacts/*.zip \
--verify-tag --title "zdxc $TAG" --generate-notes
fi

26
LICENSE Normal file
View File

@ -0,0 +1,26 @@
MIT License
Copyright (c) 2026 Peter Li
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Files under vendor/ are third-party and remain under their own licenses; see
vendor/PROVENANCE.md and vendor/hlsl-headers/LICENSE.txt.

104
README.md Normal file
View File

@ -0,0 +1,104 @@
<p align="center">
<img src="docs/assets/logo.svg" width="100" alt="zdxc" />
</p>
<p align="center">
<strong>A small, fast HLSL compiler. Built to shorten the edit–compile–run loop.</strong>
</p>
<p align="center">
HLSL 2018 / 2021 → DXIL / SPIR-V · Written in Zig · No LLVM dependency
</p>
<p align="center">
<a href="https://zdxc.org">zdxc.org</a> ·
<a href="#quick-start">Quick start</a> ·
<a href="https://zdxc.org/manual.html">Manual</a> ·
<a href="docs/manual/">Manual source</a>
</p>
---
zdxc is an HLSL compiler written from scratch in Zig. It supports HLSL 2018
and 2021, emits DXIL and SPIR-V, supports DXC-style command lines, and
provides a DXC-compatible COM interface for existing engine integrations.
Use it as a development drop-in replacement for DXC, link its small C API directly,
or import it as a Zig module. The compiler has no package dependencies and
signs its own DXIL, so there is no separate `dxil.dll` to ship.
| Fast iteration | Small footprint | Easy to embed |
| :--- | :--- | :--- |
| About **15× faster compilation** in the Hyperion benchmark. | **4.2 MB** Windows drop-in, compared with **19.3 MB** for DXC plus its DXIL library. | A **static library** by default, with a C API and a native Zig module. |
## Quick start
Requires **Zig 0.17**. Build the command-line compiler and library:
```sh
git clone https://github.com/peterino2/zdxc.git
cd zdxc
zig build -Doptimize=ReleaseFast
```
Compile the same shader to either backend:
```sh
# DirectX / DXIL
zig-out/bin/zdxc -T ps_6_0 -E main shader.hlsl -Fo shader.dxil
# Vulkan / SPIR-V
zig-out/bin/zdxc -spirv -T ps_6_0 -E main shader.hlsl -Fo shader.spv
```
The build installs the compiler in `zig-out/bin/`, the library in
`zig-out/lib/`, and the public header in `zig-out/include/`.
## Documentation and downloads
Read the [manual on zdxc.org](https://zdxc.org/manual.html) for command-line
options, batch compilation, the C API, DXC drop-in support, and Zig integration.
The [manual Markdown sources](docs/manual/) live in this repository.
For an existing DXC integration, build the drop-in executable and shared library:
```sh
zig build dropin -Doptimize=ReleaseFast
```
Download Windows, Linux, and macOS bundles from a successful run's **Artifacts**
section on [GitHub Actions](https://github.com/peterino2/zdxc/actions).
Each bundle includes the CLI, static C library, header, and DXC drop-in.
See the [case studies](https://zdxc.org/case-studies.html) for benchmark
measurements and methodology. In Hyperion's Windows DXIL cook, zdxc's compile
step was **15.5× faster** and the complete shader cook was **2.5× faster**;
Unreal Engine 5.8's editor compiled its 11,156 startup shaders **4.3× faster**.
## Status
zdxc is **alpha software**. HLSL 2021 is the default; use `-HV 2018` for
HLSL 2018 shaders. DXIL supports work graph node shaders in `lib_6_8`
libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph nodes
are not supported by the SPIR-V backend. See the
[command-line guide](docs/manual/03-command-line.md) for examples.
DXC compatibility is still being developed; not every interface or feature
is implemented.
The [drop-in manual](https://zdxc.org/manual.html#section-dxc-drop-in) documents
the current interface coverage.
To run the unit tests:
```sh
zig build test
```
If you find a problem, [open an issue](https://github.com/peterino2/zdxc/issues)
with a minimal shader, the compiler arguments, your platform, and the
expected result.
---
Created by [Peterino](https://peterino.com) as an experiment in agentic
engineering. Open source, MIT licensed.

5
docs/assets/logo.svg Normal file
View File

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" fill="none">
<title>zdxc — tiny directx shader compiler</title>
<rect x="4" y="4" width="64" height="64" rx="12" fill="#111110"/>
<path d="M20 20h32v8L32 44h20v8H20v-8l20-16H20Z" fill="#f4f4ee"/>
</svg>

After

Width:  |  Height:  |  Size: 271 B

View File

@ -24,8 +24,10 @@ no `dxil.dll`: zdxc signs DXIL itself.
| Class | Interfaces |
|---|---|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcVersionInfo` (reports 1.11) |
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart` |
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcCompiler` (`Compile`, `Preprocess`), `IDxcCompiler2` (`CompileWithDebug`), `IDxcVersionInfo` (reports 1.11) |
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart`, `CreateReflection` |
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection`: load and inspect container parts, `GetPartReflection` |
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder`: load, add/remove parts, serialize a signed container |
`Compile` takes the same arguments as the command line and follows DXC:
@ -44,13 +46,21 @@ no `dxil.dll`: zdxc signs DXIL itself.
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
or `E_NOTIMPL`. These include:
- the legacy `IDxcCompiler` and `IDxcCompiler2` interfaces;
- `Disassemble`;
- `CreateReflection`, `BuildArguments` and `GetPDBContents`;
- the validator, linker, container and PDB classes.
- `BuildArguments` and `GetPDBContents`;
- the validator, linker, and PDB classes.
The result has no `DXC_OUT_REFLECTION` output (the reflection container
that `CreateReflection` reads).
DXIL results include `DXC_OUT_REFLECTION`. `CreateReflection` reads zdxc
reflection blobs and exposes `ID3D12ShaderReflection` or
`ID3D12LibraryReflection`. `CompileWithDebug` compiles the shader but returns
no separate debug name or blob; zdxc does not write PDBs.
Language support is zdxc's own: HLSL 2021, with `-HV 2021` as the only
version.
Language support is zdxc's own. HLSL 2021 is the default; pass `-HV 2018`
for HLSL 2018's component-wise `&&`, `||`, and numeric `?:`, which evaluate
both operands or branches. `-HV 2016` and `-HV 2017` use the same legacy
operator semantics. These options apply to both executable and library calls.
DXIL supports work graph node shaders compiled as `lib_6_8`, including
node input/output records and the `broadcasting`, `coalescing`, and `thread`
launch modes. Work graph nodes are not supported with `-spirv`.

View File

@ -0,0 +1,28 @@
---
type: guide
order: 1
title: Introduction
---
zdxc is a from-scratch HLSL compiler written in Zig. It emits DXIL and
SPIR-V and has no package dependencies. The same compiler is available through
four interfaces:
| Interface | Use |
| --- | --- |
| `zdxc` | A dxc-style command-line compiler. |
| `libzdxc` | A small C API that returns compilation outputs in memory. |
| `zdxc` Zig module | Direct access to the compiler from a Zig build. |
| `dxc` / `dxcompiler` | Drop-in names and entry points for existing DXC clients. |
HLSL 2021 is the default language version. Select HLSL 2018 with `-HV 2018`;
`-HV 2016` and `-HV 2017` are also accepted with the same legacy operator
semantics. The language version is independent of the target shader model.
Compute shaders support thread groups, `groupshared` storage, and group
barriers. The DXIL backend also supports work graph node shaders in
`lib_6_8` libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph
nodes are not supported in SPIR-V. See the
[command-line guide](03-command-line.md) for language and work graph examples.
DXIL output is signed by zdxc itself, so no separate `dxil` library is needed.

View File

@ -0,0 +1,76 @@
---
type: guide
order: 2
title: Getting started
---
```quickstart
{
"title": "Quick start",
"tabs": [
{
"label": "Download",
"steps": [
{"title": "Get the bundle", "code": "unzip zdxc-VERSION-PLATFORM.zip && cd zdxc-VERSION-PLATFORM", "text": "Download it for your platform from the [releases](https://github.com/peterino2/zdxc/releases). `bin/` holds `zdxc` and the DXC drop-in; `lib/` and `include/` hold `libzdxc` and `zdxc.h`."},
{"title": "Drop in for DXC", "code": "cp bin/dxc* bin/*dxcompiler* ENGINE/bin/", "text": "Put `dxc` and `dxcompiler` where your engine looks for DXC's. There is no `dxil.dll` to copy."},
{"title": "Compile a shader", "code": "bin/zdxc -T ps_6_0 -E main shader.hlsl -Fo shader.dxil", "text": "dxc's command line. Add `-spirv` for SPIR-V, or compile many shaders at once with `--job`."}
],
"links": [
{"href": "https://github.com/peterino2/zdxc/releases", "label": "Releases"}
]
},
{
"label": "Build from source",
"steps": [
{"title": "Get the source", "code": "git clone https://github.com/peterino2/zdxc.git && cd zdxc", "text": "One Zig codebase with no dependencies."},
{"title": "Build", "code": "zig build -Doptimize=ReleaseFast", "text": "Needs Zig 0.17 and nothing else. You get `zdxc`, `libzdxc.a` and `zdxc.h` in `zig-out`."},
{"title": "Drop in for DXC", "code": "zig build dropin -Doptimize=ReleaseFast", "text": "Builds `dxc` and `dxcompiler`. Put them where your engine looks for DXC's; there is no `dxil.dll` to copy."},
{"title": "Compile a shader", "code": "zig-out/bin/zdxc -T ps_6_0 -E main shader.hlsl -Fo shader.dxil", "text": "dxc's command line. Add `-spirv` for SPIR-V, or compile many shaders at once with `--job`."}
],
"links": [
{"href": "https://github.com/peterino2/zdxc", "label": "Source on GitHub"}
]
}
]
}
```
## Requirements
Install Zig 0.17.0 or newer. zdxc has no library or package dependencies.
## Build
Run the build from the zdxc package directory:
```sh
zig build -Doptimize=ReleaseFast
```
The default install contains:
```text
zig-out/bin/zdxc command-line compiler
zig-out/lib/libzdxc.a static C library
zig-out/include/zdxc.h public C header
```
Build a shared C library instead with `-Dlinkage=dynamic`. Cross-compilation
uses Zig's usual target option:
```sh
zig build -Dtarget=x86_64-windows-gnu -Doptimize=ReleaseFast
```
## Compile a shader
The command line follows dxc. Specify a target profile, entry point, input,
and output file:
```sh
./zig-out/bin/zdxc -T cs_6_0 -E main shader.hlsl -Fo shader.dxil
./zig-out/bin/zdxc -T vs_6_0 -E main -spirv shader.hlsl -Fo shader.spv
```
Use `zdxc -help` for the complete option list and `zdxc --version` for the
compiler version.

View File

@ -0,0 +1,96 @@
---
type: guide
order: 3
title: Command line
---
zdxc accepts dxc command-line arguments. A compilation can read its input from
a file or, through the library interfaces, from memory.
| Option | Meaning |
| --- | --- |
| `-T <profile>` | Target profile, such as `vs_6_0`, `ps_6_0`, or `cs_6_0`. |
| `-E <name>` | Shader entry point. |
| `-HV <version>` | HLSL language version: `2021` (default), `2018`, `2017`, or `2016`. |
| `-D <name[=value]>` | Define a preprocessor macro. |
| `-I <directory>` | Add an include search directory. |
| `-Fo <file>` | Write the object to a file. |
| `-Fi <file>` | Write preprocessed output when used with `-P`. |
| `-Frs <file>` | Write a root-signature container. |
| `-P` | Preprocess instead of compiling. |
| `-spirv` | Emit SPIR-V instead of DXIL. |
| `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. |
| `-O0` … `-O3`, `-Od` | Select the optimization level. `-Od`, as in dxc, still promotes locals to SSA values and removes dead code, but does nothing else. |
| `--job=<file>` | Compile a JSON batch of shaders in one process. |
DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and
`-fspv-*` options controlling Vulkan bindings, layout, and target environment.
## HLSL language versions
Use `-HV 2018` when compiling shaders written for HLSL 2018:
```sh
zdxc -HV 2018 -T ps_6_0 -E main shader.hlsl -Fo shader.dxil
zdxc -HV 2018 -spirv -T ps_6_0 -E main shader.hlsl -Fo shader.spv
```
The default is `-HV 2021`. In the legacy modes (`2016`, `2017`, and `2018`),
`&&` and `||` evaluate both operands and operate component-wise on vectors;
numeric `?:` evaluates both branches and permits a vector condition to
select per component. In 2021 mode, logical operands and the conditional
test are scalar, and evaluation short-circuits. Code that relies on an
unevaluated expression to avoid side effects needs particular care when
switching to a legacy mode.
The preprocessor macro `__HLSL_VERSION` reflects the selected version.
`-HV` selects language semantics; `-T` independently selects the shader
stage and shader model. These options also work in batch jobs and through
the C API and DXC drop-in.
## Compute thread groups and work graphs
Compute shaders use `[numthreads(x, y, z)]` to declare their thread group
size, `groupshared` for group-local storage, and intrinsics such as
`GroupMemoryBarrierWithGroupSync()` for synchronization. Compile them with
a compute profile, for example `-T cs_6_0 -E main`, for DXIL or SPIR-V.
For DXIL, `[WaveSize]` is emitted in entry-point and runtime metadata,
including the minimum, maximum, and preferred sizes for SM 6.8 wave-size
ranges. SM 6.8's `Barrier()` supports memory flags, UAVs, and node records.
Work graphs use node shaders in a shader library. Compile with `-T lib_6_8`
and mark each node with `[Shader("node")]` and its `[NodeLaunch]` mode;
there is no single `-E` entry point for the library. The supported launch
modes are `broadcasting`, `coalescing`, and `thread`. Node input/output
records, record allocation and completion, dispatch grids, node IDs, and
`GetRemainingRecursionLevels()` are supported by the DXIL backend.
For example, save this broadcasting node as `node.hlsl`:
```hlsl
RWStructuredBuffer<uint> values : register(u0);
[Shader("node")]
[NodeLaunch("broadcasting")]
[NodeDispatchGrid(1, 1, 1)]
[numthreads(64, 1, 1)]
void Fill(uint3 id : SV_DispatchThreadID)
{
values[id.x] = id.x;
}
```
```sh
zdxc -T lib_6_8 node.hlsl -Fo node.dxil
```
This produces a node shader library for a host application's work graph.
Work graph nodes are DXIL-only; compiling them with `-spirv` reports an
unsupported-feature error.
## Diagnostics and exit status
Diagnostics follow dxc's command-line format. Exit status is 0 for success,
1 for bad options or input/output failures, and 5 for source compilation
errors. Warnings can appear in successful compilations.

View File

@ -0,0 +1,75 @@
---
type: guide
order: 4
title: Batch compilation
---
`zdxc --job=build/shaders.json` compiles every shader a job file lists in
one process, on all cores. Starting a process costs more than compiling most
shaders (about 2 ms against a few hundred microseconds), so a build with many
shaders is much faster this way than with one compiler run per shader.
On the 1,481 corpus shaders zdxc compiles (10-core M-series Mac, release
build):
| How | Wall time |
| ------------------------------------------- | --------: |
| `zdxc --job`, all cores | 0.064 s |
| `zdxc --job`, `"threads": 1` | 0.24 s |
| one `zdxc` per shader, 10 in parallel | 1.09 s |
| one `dxc` per shader, 10 in parallel | 1.68 s |
## The job file
```json
{
"threads": 8,
"args": ["-HV", "2021", "-I", "shaders/include"],
"jobs": [
{ "args": ["-T", "cs_6_0", "shaders/blur.hlsl", "-Fo", "out/blur.dxo"] },
{ "args": ["-T", "ps_6_0", "-E", "PS", "shaders/mesh.hlsl", "-Fo", "out/mesh_ps.dxo"] },
{ "args": ["-T", "vs_6_0", "-E", "VS", "-spirv", "shaders/mesh.hlsl", "-Fo", "out/mesh_vs.spv"] }
]
}
```
- `jobs` (required): each job's `args` is a dxc command line without the
program name — any option zdxc accepts on its own command line.
- `args` (optional): options shared by every job.
- `threads` (optional): how many shaders compile at once. Defaults to the
number of CPUs.
A job's full command line is the file's `args`, then any options given next
to `--job` on the real command line, then the job's own `args`. So
`zdxc --job=shaders.json -O3 -Qstrip_debug` adds `-O3 -Qstrip_debug` to every
job, and a job can override a shared option where a later option wins on the
command line. Unknown fields are errors, reported with their line and column.
Paths in the file are relative to the current directory, as on the command
line, not to the job file. `--job` cannot appear inside a job file.
## Output and exit code
Every job writes its own `-Fo` / `-Fh` / ... outputs. What a job prints —
diagnostics, and text output such as `-P` without a file — comes out
exactly as one zdxc run of that command line would print it, kept together
and in job order, whatever order the jobs finish in. The outputs are
byte-identical to separate runs.
When jobs fail, the other jobs still run, and a last line says how many
failed:
```text
zdxc: 2 of 112 jobs failed
```
The exit code is 0 when every job succeeds; otherwise 1 if any job failed
on its command line or on I/O (a missing input, an unwritable output), else
5 (compile errors) — the codes one zdxc run uses.
Reading and writing files is kept off the compiling threads: one thread
reads the jobs' input files ahead of the compiles, and another writes
their outputs after them. Files the jobs include are read once for the
whole run, so a header that every shader includes is opened once (a file
that changes while the run is going is not read again). An output that
cannot be written is reported after every job's output, and fails its job.

86
docs/manual/05-c-api.md Normal file
View File

@ -0,0 +1,86 @@
---
type: guide
order: 5
title: The C API
---
zdxc is also a library with a small C API, [`include/zdxc.h`](source.html).
Unlike dxcompiler, it links statically: there is no DLL to ship or load, no
COM, and nothing to link besides the platform's C library.
```sh
zig build # zig-out/lib/libzdxc.a, zig-out/include/zdxc.h
zig build -Dlinkage=dynamic # libzdxc.so / .dylib / zdxc.dll instead
zig build -Dtarget=x86_64-windows-gnu -Doptimize=ReleaseFast
```
Link `libzdxc.a` like any static library (`cc app.c -Izig-out/include
zig-out/lib/libzdxc.a`). It exports
only the `zdxc_*` functions; the compiler runtime it carries is hidden. For
a macOS binary you ship, give the target a minimum version
(`-Dtarget=aarch64-macos.13.0`), or the linker warns that the library was
built for a newer macOS than the app.
## Compiling
A compilation is a dxc command line, with the outputs returned in memory:
```c
#include <zdxc.h>
const char *args[] = {"-T", "ps_6_0", "-E", "PS", "-D", "SHADOWS=1"};
zdxc_compile_info info = {
.size = sizeof info,
.args = args,
.arg_count = 6,
.source = text,
.source_size = text_size,
.source_name = "mesh.hlsl",
};
zdxc_result *r = zdxc_compile(&info);
if (!r) return OUT_OF_MEMORY;
const char *diags = zdxc_result_output(r, ZDXC_OUTPUT_DIAGNOSTICS, NULL);
if (diags) fputs(diags, stderr); /* errors, or warnings on success */
if (zdxc_result_status(r) == ZDXC_STATUS_OK) {
size_t size;
const void *dxil = zdxc_result_output(r, ZDXC_OUTPUT_OBJECT, &size);
upload(dxil, size);
}
zdxc_result_free(r);
```
- **Options** are exactly the command line's (`-T`, `-E`, `-D`, `-I`,
`-spirv`, `-fvk-*`, `-Zpr`, `-O3`, ...), without the program name.
- **The source** is in memory (`source`, with or without a trailing NUL),
or, when `source` is NULL, the input file named in the options.
- **Files** — the input when given by name, and every `#include` candidate —
are read from disk relative to the current directory, unless you pass a
`read_file` callback. The callback gets each candidate path (the
including file's directory, then each `-I` directory) and returns 0 with
the file's bytes, or nonzero to try the next candidate. Returned memory
only has to last until `zdxc_compile` returns.
- **Status** is `ZDXC_STATUS_OK` (0), `ZDXC_STATUS_FAILED` (1: bad options,
unreadable input) or `ZDXC_STATUS_COMPILE_FAILED` (5: errors in the
source) — the command line's exit codes. `zdxc_compile` returns NULL only
when out of memory.
- **Outputs** are `OBJECT` (a DXIL container or SPIR-V module),
`DIAGNOSTICS`, `PREPROCESSED` (`-P`), `ROOT_SIGNATURE` (`-Frs`) and `TEXT`
(`-help`, `--version`). Each is NUL-terminated for convenience and lives
until `zdxc_result_free`. `zdxc_result_output_name` gives the name an
option assigned (`-Fo`, `-Fi`, `-Frs`); zdxc never writes files.
The output is byte-for-byte what the command line writes for the same
options and files.
## Threads
zdxc has no global state. Any number of threads may call `zdxc_compile` at
once, and a result may be read or freed on any thread.
## Zig
Zig projects can skip the C API: depend on this package and import the
`zdxc` module, whose `compile.compile(arena, request)` is what the C API
wraps.

View File

@ -0,0 +1,70 @@
---
type: guide
order: 6
title: The DXC drop-in
---
Programs that run DXC usually do it in one of two ways: they call the `dxc`
executable, or they load `dxcompiler` (`dxcompiler.dll`,
`libdxcompiler.so`, `libdxcompiler.dylib`) and call `DxcCreateInstance`.
SDL_shadercross, for one, does the second. The `dropin` step builds both on
top of zdxc, so these programs can use zdxc without being changed:
```sh
zig build dropin # zig-out/bin/dxc, zig-out/lib/libdxcompiler.{so,dylib}
zig build dropin -Dtarget=x86_64-windows-gnu -Doptimize=ReleaseFast
# zig-out/bin/dxc.exe, dxcompiler.dll, lib/dxcompiler.lib
```
Put them where the program looks for DXC, in place of DXC's files. There is
no `dxil.dll`: zdxc signs DXIL itself.
- `dxc` is the zdxc command line under DXC's name.
- `dxcompiler` exports `DxcCreateInstance` and `DxcCreateInstance2`, with
`dxcapi.h`'s ABI. On Windows it imports only `kernel32` and `ntdll`. On
other platforms it links the C library and nothing else.
## What the library implements
| Class | Interfaces |
|---|---|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcCompiler` (`Compile`, `Preprocess`), `IDxcCompiler2` (`CompileWithDebug`), `IDxcVersionInfo` (reports 1.11) |
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart`, `CreateReflection` |
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection`: load and inspect container parts, `GetPartReflection` |
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder`: load, add/remove parts, serialize a signed container |
`Compile` takes the same arguments as the command line and follows DXC:
- **Status.** A compile error is a successful call whose status is
`E_FAIL`. A bad option has status `E_INVALIDARG`.
- **Outputs.** The result holds the same outputs DXC's does: the object,
the errors (UTF-8, empty when there are none), the shader hash for DXIL,
the root signature, `-P` text, and the names given with `-Fo`, `-Fi` and
`-Frs`.
- **Includes.** Includes go through the `IDxcIncludeHandler` you pass,
with paths spelled the way DXC spells them (`./inc/common.hlsli`). With no
handler, includes fail, as they do in DXC.
- **Accepted-but-ignored options.** Options that zdxc accepts but does not
act on yet produce no note here. Many clients treat any diagnostic text
as a warning.
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
or `E_NOTIMPL`. These include:
- `Disassemble`;
- `BuildArguments` and `GetPDBContents`;
- the validator, linker, and PDB classes.
DXIL results include `DXC_OUT_REFLECTION`. `CreateReflection` reads zdxc
reflection blobs and exposes `ID3D12ShaderReflection` or
`ID3D12LibraryReflection`. `CompileWithDebug` compiles the shader but returns
no separate debug name or blob; zdxc does not write PDBs.
Language support is zdxc's own. HLSL 2021 is the default; pass `-HV 2018`
for HLSL 2018's component-wise `&&`, `||`, and numeric `?:`, which evaluate
both operands or branches. `-HV 2016` and `-HV 2017` use the same legacy
operator semantics. These options apply to both executable and library calls.
DXIL supports work graph node shaders compiled as `lib_6_8`, including
node input/output records and the `broadcasting`, `coalescing`, and `thread`
launch modes. Work graph nodes are not supported with `-spirv`.

View File

@ -0,0 +1,38 @@
---
type: guide
order: 7
title: Zig integration
---
Declare zdxc as a package dependency, then make its module available to your
executable or library:
```zig
const zdxc = b.dependency("zdxc", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zdxc", zdxc.module("zdxc"));
```
Import the module and call the same compilation layer used by the command line
and C API:
```zig
const std = @import("std");
const zdxc = @import("zdxc");
pub fn compileShader(arena: std.mem.Allocator, io: std.Io, source: []const u8) !zdxc.compile.Result {
return zdxc.compile.compile(arena, .{
.args = &.{ "-T", "ps_6_0", "-E", "PS", "-D", "SHADOWS=1" },
.source = source,
.source_name = "mesh.hlsl",
.io = io,
});
}
```
The returned result contains the status, object, diagnostics, and any requested
auxiliary outputs. Its allocations belong to the supplied arena. The compiler
does not write files; `-Fo`, `-Fi`, and `-Frs` only name the corresponding
in-memory outputs.

View File

@ -0,0 +1,8 @@
---
type: guide
order: 8
title: API reference
---
The public C API is declared in [`zdxc.h`](source.html). Each symbol below has
its declaration, ownership rules, and a link to the corresponding source line.

View File

@ -0,0 +1,13 @@
---
type: api
order: 1
title: ZDXC_API_VERSION
kind: macro
line: 41
---
```c
#define ZDXC_API_VERSION 1
```
The public C API version. The current version is 1.

View File

@ -0,0 +1,15 @@
---
type: api
order: 2
title: zdxc_result
kind: type
line: 43
---
```c
typedef struct zdxc_result zdxc_result;
```
An opaque compilation result. It owns the object, diagnostics, and other
outputs returned by `zdxc_compile`. Read its outputs with
`zdxc_result_output` and release it with `zdxc_result_free`.

View File

@ -0,0 +1,29 @@
---
type: api
order: 3
title: zdxc_status
kind: type
line: 46
---
```c
typedef enum zdxc_status {
ZDXC_STATUS_OK = 0,
ZDXC_STATUS_FAILED = 1,
ZDXC_STATUS_COMPILE_FAILED = 5
} zdxc_status;
```
A compilation's outcome. The values match dxc's command-line exit codes.
### ZDXC_STATUS_OK
Compilation succeeded. Diagnostics may still contain warnings.
### ZDXC_STATUS_FAILED
Bad options or an input that could not be read.
### ZDXC_STATUS_COMPILE_FAILED
The source contains compilation errors.

View File

@ -0,0 +1,39 @@
---
type: api
order: 4
title: zdxc_output
kind: type
line: 54
---
```c
typedef enum zdxc_output {
ZDXC_OUTPUT_OBJECT = 0,
ZDXC_OUTPUT_DIAGNOSTICS = 1,
ZDXC_OUTPUT_PREPROCESSED = 2,
ZDXC_OUTPUT_ROOT_SIGNATURE = 3,
ZDXC_OUTPUT_TEXT = 4
} zdxc_output;
```
Selects one output from a compilation result.
### ZDXC_OUTPUT_OBJECT
The DXIL container or SPIR-V module.
### ZDXC_OUTPUT_DIAGNOSTICS
Errors, warnings, and notes in command-line format.
### ZDXC_OUTPUT_PREPROCESSED
Preprocessed source requested with `-P`.
### ZDXC_OUTPUT_ROOT_SIGNATURE
The root-signature container requested with `-Frs`.
### ZDXC_OUTPUT_TEXT
Other command-line text, such as `-help` or `--version`.

View File

@ -0,0 +1,15 @@
---
type: api
order: 5
title: zdxc_read_file_fn
kind: callback
line: 75
---
```c
typedef int (*zdxc_read_file_fn)(void *user, const char *path, const char **data, size_t *size);
```
Reads the main input or an `#include` candidate. On success, set `data` and
`size` and return 0. Return nonzero to let zdxc try the next candidate. The
returned bytes need only remain valid until `zdxc_compile` returns.

View File

@ -0,0 +1,55 @@
---
type: api
order: 6
title: zdxc_compile_info
kind: struct
line: 77
---
```c
typedef struct zdxc_compile_info {
uint32_t size;
const char *const *args;
size_t arg_count;
const char *source;
size_t source_size;
const char *source_name;
zdxc_read_file_fn read_file;
void *user;
} zdxc_compile_info;
```
Describes one in-memory or file-based compilation. Initialize `size` to
`sizeof(zdxc_compile_info)` so later API versions can add fields.
### size
The structure size in bytes; use `sizeof(zdxc_compile_info)`.
### args
dxc command-line options without the program name.
### arg_count
Number of arguments in `args`.
### source
The main source text, or NULL to read the named input file.
### source_size
Source byte length; a trailing NUL is allowed.
### source_name
Name used in diagnostics and relative include resolution.
### read_file
Optional file callback; NULL reads from disk.
### user
Opaque pointer passed to `read_file`.

View File

@ -0,0 +1,18 @@
---
type: api
order: 7
title: zdxc_compile
kind: function
line: 99
---
```c
zdxc_result *zdxc_compile(const zdxc_compile_info *info);
```
Runs one compilation. It returns NULL only for an invalid or too-small
descriptor, or when memory is exhausted. Every compilation failure is reported
by the result's status and diagnostics.
The compiler has no global state. Independent calls may run concurrently on
any number of threads.

View File

@ -0,0 +1,13 @@
---
type: api
order: 8
title: zdxc_result_status
kind: function
line: 101
---
```c
zdxc_status zdxc_result_status(const zdxc_result *result);
```
Returns the compilation's `zdxc_status`.

View File

@ -0,0 +1,18 @@
---
type: api
order: 9
title: zdxc_result_output
kind: function
line: 106
---
```c
const void *zdxc_result_output(const zdxc_result *result, zdxc_output output, size_t *size);
```
Returns the selected output's bytes. The bytes are followed by a NUL for
convenience; `size` does not count that terminator and may be NULL. If the
output was not produced, returns NULL and stores zero in `size`.
The pointer remains valid until `zdxc_result_free`. Binary object outputs can
contain interior NUL bytes; always use the returned size.

View File

@ -0,0 +1,14 @@
---
type: api
order: 10
title: zdxc_result_output_name
kind: function
line: 109
---
```c
const char *zdxc_result_output_name(const zdxc_result *result, zdxc_output output);
```
Returns the file name assigned by `-Fo`, `-Fi`, or `-Frs`, or NULL when the
output has no assigned name. zdxc does not write that file itself.

View File

@ -0,0 +1,14 @@
---
type: api
order: 11
title: zdxc_result_free
kind: function
line: 111
---
```c
void zdxc_result_free(zdxc_result *result);
```
Releases a result and all of its outputs. Any output pointers previously
obtained from it become invalid.

View File

@ -0,0 +1,13 @@
---
type: api
order: 12
title: zdxc_version
kind: function
line: 114
---
```c
const char *zdxc_version(void);
```
Returns zdxc's version as a NUL-terminated string, such as `0.1.0`.

View File

@ -1,5 +1,5 @@
/*
* zdxc: an HLSL 2021 to DXIL and SPIR-V compiler.
* zdxc: an HLSL 2018 / 2021 to DXIL and SPIR-V compiler.
*
* The C API. Link libzdxc statically (zig build -Dlinkage=static, the
* default) or dynamically (-Dlinkage=dynamic); it needs nothing besides

193
src/BumpArena.zig Normal file
View File

@ -0,0 +1,193 @@
//! An arena for one thread: what std.heap.ArenaAllocator does, without the
//! atomic operations that make that one safe to share between threads (an
//! atomic add on every allocation). A compile runs on one thread and
//! allocates millions of times.
//!
//! Memory comes from the child allocator in chunks, each larger than the
//! last; freeing or resizing an allocation works in place only for the
//! most recent one. reset can keep the chunks for the next use.
const BumpArena = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;
child: Allocator,
/// Chunks in use, newest first; allocations bump `end` in the newest.
used: ?*Chunk = null,
/// Chunks a reset kept, for reuse.
spare: ?*Chunk = null,
end: usize = 0,
const Chunk = struct {
next: ?*Chunk,
/// Bytes after the header.
len: usize,
fn data(c: *Chunk) [*]u8 {
return @as([*]u8, @ptrCast(c)) + @sizeOf(Chunk);
}
};
const chunk_align: Alignment = .@"16";
const min_chunk = 64 << 10;
pub fn init(child: Allocator) BumpArena {
return .{ .child = child };
}
pub fn deinit(b: *BumpArena) void {
freeList(b.child, b.used);
freeList(b.child, b.spare);
b.* = undefined;
}
fn freeList(child: Allocator, first: ?*Chunk) void {
var c = first;
while (c) |chunk| {
c = chunk.next;
const bytes: [*]u8 = @ptrCast(chunk);
child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress());
}
}
pub fn allocator(b: *BumpArena) Allocator {
return .{ .ptr = b, .vtable = &vtable };
}
const vtable: Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free };
/// Total bytes of the chunks held (in use and spare).
pub fn queryCapacity(b: *const BumpArena) usize {
var n: usize = 0;
inline for (.{ b.used, b.spare }) |first| {
var c = first;
while (c) |chunk| : (c = chunk.next) n += chunk.len;
}
return n;
}
pub const ResetMode = std.heap.ArenaAllocator.ResetMode;
/// Frees every allocation. `.retain_capacity` keeps the chunks for reuse;
/// `.retain_with_limit` keeps them up to that many bytes (largest first
/// kept); `.free_all` gives them back.
pub fn reset(b: *BumpArena, mode: ResetMode) bool {
const limit: usize = switch (mode) {
.free_all => 0,
.retain_capacity => std.math.maxInt(usize),
.retain_with_limit => |l| l,
};
// All chunks, then keep the largest that fit under the limit.
var all = b.used;
if (all) |first| {
var last = first;
while (last.next) |nx| last = nx;
last.next = b.spare;
} else all = b.spare;
b.used = null;
b.spare = null;
b.end = 0;
var kept: usize = 0;
var c = all;
while (c) |chunk| {
c = chunk.next;
if (kept + chunk.len <= limit) {
kept += chunk.len;
chunk.next = null;
b.addSpare(chunk);
} else {
const bytes: [*]u8 = @ptrCast(chunk);
b.child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress());
}
}
return true;
}
/// Adds a chunk to the spare list, largest first.
fn addSpare(b: *BumpArena, chunk: *Chunk) void {
var link = &b.spare;
while (link.*) |s| : (link = &s.next) if (s.len < chunk.len) break;
chunk.next = link.*;
link.* = chunk;
}
fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
const b: *BumpArena = @ptrCast(@alignCast(ctx));
if (b.used) |c| {
const base = c.data();
const start = alignment.forward(@intFromPtr(base) + b.end) - @intFromPtr(base);
if (start + n <= c.len) {
b.end = start + n;
return base + start;
}
}
return b.allocSlow(n, alignment, ra);
}
fn allocSlow(b: *BumpArena, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
const need = n + alignment.toByteUnits();
// A spare chunk big enough (the largest is first), else a new one half
// again as large as the current.
const chunk: *Chunk = if (b.spare != null and b.spare.?.len >= need) blk: {
const s = b.spare.?;
b.spare = s.next;
break :blk s;
} else blk: {
const grow = if (b.used) |c| c.len + c.len / 2 else 0;
const len = @max(need, grow, min_chunk);
const bytes = b.child.rawAlloc(@sizeOf(Chunk) + len, chunk_align, ra) orelse return null;
const c: *Chunk = @ptrCast(@alignCast(bytes));
c.len = len;
break :blk c;
};
chunk.next = b.used;
b.used = chunk;
const base = chunk.data();
const start = alignment.forward(@intFromPtr(base)) - @intFromPtr(base);
b.end = start + n;
return base + start;
}
/// Whether `buf` is the newest allocation (the only one that can change
/// in place).
fn isLast(b: *const BumpArena, buf: []u8) bool {
const c = b.used orelse return false;
return buf.ptr + buf.len == c.data() + b.end;
}
fn resize(ctx: *anyopaque, buf: []u8, _: Alignment, new_len: usize, _: usize) bool {
const b: *BumpArena = @ptrCast(@alignCast(ctx));
if (!b.isLast(buf)) return new_len <= buf.len;
const c = b.used.?;
const start = @intFromPtr(buf.ptr) - @intFromPtr(c.data());
if (start + new_len > c.len) return false;
b.end = start + new_len;
return true;
}
fn remap(ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ra: usize) ?[*]u8 {
return if (resize(ctx, buf, alignment, new_len, ra)) buf.ptr else null;
}
fn free(ctx: *anyopaque, buf: []u8, _: Alignment, _: usize) void {
const b: *BumpArena = @ptrCast(@alignCast(ctx));
if (b.isLast(buf)) b.end -= buf.len;
}
test "allocations, growth in place, reset" {
var b: BumpArena = .init(std.testing.allocator);
defer b.deinit();
const a = b.allocator();
var list: std.ArrayList(u32) = .empty;
for (0..100_000) |k| try list.append(a, @intCast(k));
for (list.items, 0..) |x, k| try std.testing.expectEqual(k, x);
const big = try a.alignedAlloc(u8, .@"64", 1 << 20);
try std.testing.expect(std.mem.isAligned(@intFromPtr(big.ptr), 64));
const cap = b.queryCapacity();
_ = b.reset(.retain_capacity);
try std.testing.expectEqual(cap, b.queryCapacity());
_ = try a.alloc(u8, 100);
_ = b.reset(.{ .retain_with_limit = 0 });
try std.testing.expectEqual(0, b.queryCapacity());
}

View File

@ -2,6 +2,7 @@
//! owns an arena; nothing is global.
const std = @import("std");
const BumpArena = @import("zdxc").BumpArena;
const zdxc = @import("zdxc");
const compile = zdxc.compile;
const FileSystem = zdxc.front.source.FileSystem;
@ -22,7 +23,7 @@ const CompileInfo = extern struct {
const Output = enum(c_int) { object, diagnostics, preprocessed, root_signature, text, _ };
const Result = struct {
arena: std.heap.ArenaAllocator,
arena: BumpArena,
status: compile.Status,
/// Indexed by `Output`; each NUL-terminated.
outputs: [5]?[:0]const u8,
@ -32,7 +33,7 @@ const Result = struct {
export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
const i = info orelse return null;
if (i.size < @sizeOf(CompileInfo)) return null;
var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator);
var arena: BumpArena = .init(std.heap.smp_allocator);
const r = compileInto(&arena, i) catch {
arena.deinit();
return null;
@ -41,7 +42,7 @@ export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
return r;
}
fn compileInto(arena: *std.heap.ArenaAllocator, i: *const CompileInfo) !*Result {
fn compileInto(arena: *BumpArena, i: *const CompileInfo) !*Result {
const a = arena.allocator();
const args = try a.alloc([]const u8, i.arg_count);
for (args, 0..) |*d, k| d.* = std.mem.span(i.args.?[k] orelse return error.InvalidArgument);

View File

@ -11,6 +11,7 @@ const container = zdxc.dxil.container;
const front = zdxc.front;
const options = zdxc.options;
const FileSystem = front.source.FileSystem;
const stats = zdxc.stats;
pub const Request = struct {
/// dxc command-line options, without the program name: "-T", "ps_6_0",
@ -53,6 +54,9 @@ pub const Result = struct {
/// The root signature container (-Frs) and its name.
root_signature: ?[]const u8 = null,
root_signature_name: ?[]const u8 = null,
/// DXIL: the shader's reflection (dxil/reflect.zig), for the DXC
/// drop-in's DXC_OUT_REFLECTION.
reflection: ?[]const u8 = null,
/// Preprocessed source (-P) and its -Fi name.
preprocessed: ?[]const u8 = null,
preprocessed_name: ?[]const u8 = null,
@ -105,6 +109,7 @@ pub fn compile(arena: std.mem.Allocator, req: Request) error{OutOfMemory}!Result
};
if (result.status != .ok) {
result.object = null;
result.reflection = null;
result.root_signature = null;
result.preprocessed = null;
}
@ -164,6 +169,8 @@ const Options = struct {
preprocess: bool = false,
pp_output: ?[]const u8 = null,
enable_16bit: bool = false,
/// -HV: 2021, or 2016-2018 (component-wise `&&`, `||` and `?:`).
hlsl_version: u16 = 2021,
row_major: bool = false,
col_major: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
@ -245,8 +252,12 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
} else try opts.defines.append(arena, .{ .name = v }),
.I => try opts.include_dirs.append(arena, v),
.hlsl_version => if (!std.mem.eql(u8, v, "2021")) {
return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
.hlsl_version => {
const n = std.fmt.parseInt(u16, v, 10) catch 0;
if (n != 2021 and (n < 2016 or n > 2018)) {
return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2016-2018 and 2021", .{v});
}
opts.hlsl_version = n;
},
.P => opts.preprocess = true,
.spirv => opts.spirv = true,
@ -361,7 +372,9 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
}
fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
const za = stats.begin(.args);
const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return;
za.end();
ctx.result.object_name = opts.output;
ctx.result.root_signature_name = opts.rootsig_output;
ctx.result.preprocessed_name = opts.pp_output;
@ -431,16 +444,22 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.spirv = opts.spirv,
.spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0,
.enable_16bit = opts.enable_16bit,
.hlsl_version = opts.hlsl_version,
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
const zp = stats.begin(.preprocess);
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
zp.end();
} else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
zp.end();
const zparse = stats.begin(.parse);
const tu = try parser.parseTranslationUnit();
zparse.end();
if (opts.dump_ast) try front.ast_dump.dumpUnit(ctx.stdout, tu);
if (!opts.parse) {
const is_lib = if (profile) |p| p.kind == .library else true;
@ -448,12 +467,18 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.entry = if (opts.sema or is_lib) null else opts.entry,
.spirv = opts.spirv,
.enable_16bit = opts.enable_16bit,
.hlsl_version = opts.hlsl_version,
.sm_minor = if (profile) |p| p.minor else 10,
.library = is_lib,
.root = opts.entry,
.row_major = opts.row_major,
});
// About one resolution per expression: reserve rather
// than grow, which leaves every old buffer in the arena.
const zs = stats.begin(.sema);
try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len);
try sema.checkUnit(tu);
zs.end();
if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex,
@ -466,10 +491,12 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.amplification => .amplification,
else => .library,
};
const zl = stats.begin(.lower);
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null,
else => |x| return x,
};
zl.end();
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.row_major = opts.row_major;
@ -495,8 +522,13 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (opts.parse or opts.sema) return;
if (profile == null) return ctx.fail("missing -T <profile>", .{});
if (module) |*m| {
const zo = stats.begin(.ir_opt);
try zdxc.ir.opt.run(arena, m);
zo.end();
const zv = stats.begin(.spirv);
defer if (opts.spirv) zv.end();
if (opts.spirv) {
try zdxc.ir.inline_calls.runResourceReturns(m);
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
@ -531,15 +563,18 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
};
const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) {
const zd = stats.begin(.dxil);
const dxil_out = zdxc.dxil.emit.emitWithReflectionAt(arena, m, profile.?, &diags, if (opts.no_opt) .none else if (opts.opt_level == .od) .debug else .full) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return error.CompileFailed;
},
else => |x| return x,
};
zd.end();
try ctx.needOutput(opts);
ctx.result.object = bytes;
ctx.result.object = dxil_out.object;
ctx.result.reflection = dxil_out.reflection;
if (opts.rootsig_output != null) {
const text = (if (m.entries.items.len == 1) m.entries.items[0].root_signature else null) orelse return ctx.fail("-Frs: the shader has no root signature", .{});
var d: zdxc.dxil.rootsig.Diagnostic = .{};

View File

@ -3,6 +3,7 @@
//! include chains and macro expansion backtraces.
const std = @import("std");
const BumpArena = @import("BumpArena.zig");
const Allocator = std.mem.Allocator;
const source = @import("front/source.zig");
const Loc = source.Loc;
@ -56,7 +57,7 @@ pub const Report = struct {
};
pub const Diagnostics = struct {
arena: std.heap.ArenaAllocator,
arena: BumpArena,
list: std.ArrayList(*Diagnostic) = .empty,
error_count: u32 = 0,
warning_count: u32 = 0,

File diff suppressed because it is too large Load Diff

497
src/dxil/cfg.zig Normal file
View File

@ -0,0 +1,497 @@
//! Control-flow cleanup, as dxc's simplifycfg does it: a block that only
//! branches to a block with no other predecessor takes that block in, and
//! a block holding nothing but an unconditional branch is bypassed (its
//! predecessors branch straight to its successor). Lowering gives every
//! statement, scope and inlined call its own blocks, and the optimizer
//! empties many more; without this they stay as chains of branches.
//!
//! Run on a function in SSA form, after promotion (which drops the blocks
//! no path reaches).
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const promote = @import("promote.zig");
const stats = @import("../stats.zig");
const Value = module.Value;
const Inst = module.Inst;
const none = std.math.maxInt(u32);
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
const Case = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "switch"), "cases")).pointer.child;
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
/// Most cost of the instructions one arm of an if may hoist above its
/// branch to become a select (LLVM's phi-node-folding-threshold, as in
/// dxc).
const max_arm_cost = 2;
const State = struct {
a: Allocator,
m: *const module.Module,
insts: []Inst,
/// Each block's instructions (old indices), its terminator last.
body: []std.ArrayList(u32),
/// Predecessor edges (a block twice if it branches here twice).
preds: []std.ArrayList(u32),
/// The block that now holds a merged block's terminator: phis naming
/// the merged block mean it.
owner: []u32,
alive: []bool,
/// Phis replaced by their one input.
repl: []?Value,
fn find(s: *State, b: u32) u32 {
var x = b;
while (s.owner[x] != x) x = s.owner[x];
var y = b;
while (s.owner[y] != x) {
const next = s.owner[y];
s.owner[y] = x;
y = next;
}
return x;
}
fn term(s: *State, b: u32) *Inst {
const items = s.body[b].items;
return &s.insts[items[items.len - 1]];
}
fn hasPhis(s: *State, b: u32) bool {
return s.insts[s.body[b].items[0]].op == .phi;
}
fn removePred(s: *State, b: u32, p: u32) void {
const l = &s.preds[b];
for (l.items, 0..) |x, k| if (x == p) {
_ = l.swapRemove(k);
return;
};
}
fn renamePred(s: *State, x: u32, from: u32, to: u32) void {
for (s.preds[x].items) |*p| {
if (p.* == from) p.* = to;
}
}
fn countPred(s: *State, b: u32, p: u32) u32 {
var c: u32 = 0;
for (s.preds[b].items) |x| c += @intFromBool(x == p);
return c;
}
/// `b` (unconditional branch to `c`, `c`'s only predecessor) takes in
/// `c`.
fn merge(s: *State, b: u32, c: u32) Allocator.Error!void {
const cb = s.body[c].items;
var k: usize = 0;
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
s.repl[cb[k]] = s.insts[cb[k]].op.phi.incoming[0].val;
}
const bb = &s.body[b];
_ = bb.pop();
try bb.appendSlice(s.a, cb[k..]);
s.alive[c] = false;
s.owner[c] = b;
// (`c`'s successors now have `b` for a predecessor.)
switch (s.term(b).op) {
.br => |br| {
s.renamePred(br.then, c, b);
if (br.@"else") |e| s.renamePred(e, c, b);
},
.@"switch" => |sw| {
s.renamePred(sw.default, c, b);
for (sw.cases) |x| s.renamePred(x.block, c, b);
},
else => {},
}
}
/// Retargets `p`'s edges to `b` at `c`.
fn retarget(s: *State, p: u32, b: u32, c: u32) Allocator.Error!void {
const t = s.term(p);
switch (t.op) {
.br => |*br| {
if (br.then == b) br.then = c;
if (br.@"else") |*e| if (e.* == b) {
e.* = c;
};
},
.@"switch" => |*sw| {
if (sw.default == b) sw.default = c;
const cs = try s.a.dupe(Case, sw.cases);
for (cs) |*x| if (x.block == b) {
x.block = c;
};
sw.cases = cs;
},
else => unreachable,
}
}
/// True if `b` is cheap instructions safe to run on either path (see
/// cost) and `br m`, and only `p` branches to it.
fn armFrom(s: *State, b: u32, p: u32, m: u32) bool {
if (s.preds[b].items.len != 1 or s.preds[b].items[0] != p) return false;
const t = s.term(b).op;
if (t != .br or t.br.@"else" != null or t.br.then != m) return false;
const items = s.body[b].items;
var total: u32 = 0;
for (items[0 .. items.len - 1]) |i| {
total += s.cost(s.insts[i]) orelse return false;
if (total > max_arm_cost) return false;
}
return true;
}
/// What hoisting `inst` above a branch costs, or null if it cannot
/// be: it has an effect, may trap (integer division), or reads memory.
fn cost(s: *State, inst: Inst) ?u32 {
return switch (inst.op) {
.binop => |b| switch (b.op) {
.udiv, .sdiv, .urem, .srem => if (s.m.types.items[inst.ty] == .int) null else 1,
else => 1,
},
.cast => |c| if (c.op == .bitcast) 0 else 1,
.cmp, .select, .extractvalue, .extractelement, .insertelement => 1,
else => null,
};
}
/// The instructions of `b` before its terminator, moved to the end of
/// `p` (before its terminator).
fn hoist(s: *State, b: u32, p: u32) Allocator.Error!void {
const from = s.body[b].items;
if (from.len < 2) return;
const to = &s.body[p];
const t = to.pop().?;
try to.appendSlice(s.a, from[0 .. from.len - 1]);
try to.append(s.a, t);
from[0] = from[from.len - 1];
s.body[b].shrinkRetainingCapacity(1);
}
/// A branch to one block every way goes there unconditionally; the
/// phis there keep one input from it.
fn collapse(s: *State, b: u32) Allocator.Error!bool {
const t = s.term(b);
const target: u32 = switch (t.op) {
.br => |br| if (br.@"else") |e| (if (e == br.then) e else return false) else return false,
.@"switch" => |sw| blk: {
for (sw.cases) |c| if (c.block != sw.default) return false;
break :blk sw.default;
},
else => return false,
};
t.op = .{ .br = .{ .then = target } };
while (s.countPred(target, b) > 1) s.removePred(target, b);
const cb = s.body[target].items;
var k: usize = 0;
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
const phi = &s.insts[cb[k]].op.phi;
var out: std.ArrayList(Edge) = .empty;
var seen = false;
for (phi.incoming) |in| {
if (s.find(in.block) == b) {
if (seen) continue;
seen = true;
}
try out.append(s.a, in);
}
phi.incoming = out.items;
}
return true;
}
/// `m`'s two predecessors: a conditional branch and a block it
/// branches to (a triangle), or two blocks one conditional
/// branch picks between (a diamond). `m`'s phis become selects on the
/// branch's condition, and the branch goes straight to `m` (dxc's
/// simplifycfg folds two-entry phis so). True if done.
fn ifConvert(s: *State, m: u32) Allocator.Error!bool {
const ps = s.preds[m].items;
if (ps.len != 2 or ps[0] == ps[1]) return false;
// The branching block, and the block each of its arms reaches `m`
// from.
var p: u32 = none;
var via: [2]u32 = undefined;
for (0..2) |k| {
const q = ps[k];
const other = ps[1 - k];
const t = s.term(q).op;
if (q == m or t != .br) continue;
const e = t.br.@"else" orelse continue;
if (t.br.then == m and e == other and s.armFrom(other, q, m)) {
p = q;
via = .{ q, other };
} else if (e == m and t.br.then == other and s.armFrom(other, q, m)) {
p = q;
via = .{ other, q };
}
}
if (p == none) {
// A diamond: both predecessors empty, from one branch.
if (s.preds[ps[0]].items.len != 1) return false;
const q = s.preds[ps[0]].items[0];
if (q == m or !s.armFrom(ps[0], q, m) or !s.armFrom(ps[1], q, m)) return false;
const t = s.term(q).op;
if (t != .br) return false;
const e = t.br.@"else" orelse return false;
if (t.br.then == ps[0] and e == ps[1]) {
via = .{ ps[0], ps[1] };
} else if (t.br.then == ps[1] and e == ps[0]) {
via = .{ ps[1], ps[0] };
} else return false;
p = q;
}
const cond = s.term(p).op.br.cond.?;
const mb = s.body[m].items;
var k: usize = 0;
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
const inst = &s.insts[mb[k]];
var vals: [2]?Value = .{ null, null };
for (inst.op.phi.incoming) |in| {
const from = s.find(in.block);
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
}
if (vals[0] == null or vals[1] == null) return false;
}
k = 0;
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
const inst = &s.insts[mb[k]];
var vals: [2]Value = undefined;
for (inst.op.phi.incoming) |in| {
const from = s.find(in.block);
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
}
if (std.meta.eql(vals[0], vals[1])) {
s.repl[mb[k]] = vals[0];
} else inst.op = .{ .select = .{ .cond = cond, .t = vals[0], .f = vals[1] } };
}
// `p` goes to `m`, running what the arms did first; their blocks
// go.
for (via) |v| if (v != p) try s.hoist(v, p);
s.term(p).op = .{ .br = .{ .then = m } };
for (via) |v| if (v != p) {
s.alive[v] = false;
s.preds[v].clearRetainingCapacity();
};
s.preds[m].clearRetainingCapacity();
try s.preds[m].append(s.a, p);
return true;
}
/// Bypasses `b` (only `br c`): its predecessors branch to `c`.
fn bypass(s: *State, b: u32, c: u32) Allocator.Error!void {
const ps = try s.a.dupe(u32, s.preds[b].items);
const phis = s.hasPhis(c);
// `c`'s phis: the input from `b` comes from each of `b`'s
// predecessors instead.
const cb = s.body[c].items;
var k: usize = 0;
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
const phi = &s.insts[cb[k]].op.phi;
var out: std.ArrayList(Edge) = .empty;
try out.ensureTotalCapacity(s.a, phi.incoming.len + ps.len);
for (phi.incoming) |in| {
if (s.find(in.block) == b) {
for (ps) |p| out.appendAssumeCapacity(.{ .val = in.val, .block = p });
} else out.appendAssumeCapacity(in);
}
phi.incoming = out.items;
}
// (Each distinct predecessor once: retarget moves all its edges.)
for (ps, 0..) |p, i| {
if (std.mem.indexOfScalar(u32, ps[0..i], p) != null) continue;
try s.retarget(p, b, c);
}
s.removePred(c, b);
try s.preds[c].appendSlice(s.a, ps);
s.preds[b].clearRetainingCapacity();
s.alive[b] = false;
// A conditional branch now going to `c` both ways goes there
// unconditionally (when `c` has no phis to give two inputs).
if (!phis) for (ps) |p| {
const t = s.term(p);
if (t.op == .br) if (t.op.br.@"else") |e| if (e == t.op.br.then) {
t.op.br = .{ .then = e };
s.removePred(c, p);
};
};
}
};
/// Simplifies `func`'s control flow; true if anything changed.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.cfg);
defer zone.end();
const f = &m.functions.items[func];
const nb = f.num_blocks;
const n: u32 = @intCast(f.insts.items.len);
if (nb < 2) return false;
var s: State = .{
.a = a,
.m = m,
.insts = try a.dupe(Inst, f.insts.items),
.body = try a.alloc(std.ArrayList(u32), nb),
.preds = try a.alloc(std.ArrayList(u32), nb),
.owner = try a.alloc(u32, nb),
.alive = try a.alloc(bool, nb),
.repl = try a.alloc(?Value, n),
};
@memset(s.repl, null);
@memset(s.alive, true);
for (s.owner, 0..) |*o, b| o.* = @intCast(b);
{
var b: u32 = 0;
var start: u32 = 0;
for (s.insts, 0..) |inst, i| {
if (!isTerminator(inst)) continue;
if (b >= nb) return false; // not the block layout expected
s.body[b] = .empty;
try s.body[b].ensureTotalCapacity(a, i + 1 - start);
for (start..i + 1) |k| s.body[b].appendAssumeCapacity(@intCast(k));
start = @intCast(i + 1);
b += 1;
}
if (b != nb or start != n) return false;
}
for (s.preds) |*p| p.* = .empty;
for (0..nb) |b| {
const t = s.term(@intCast(b)).*;
switch (t.op) {
.br => |br| {
try s.preds[br.then].append(a, @intCast(b));
if (br.@"else") |e| try s.preds[e].append(a, @intCast(b));
},
.@"switch" => |sw| {
try s.preds[sw.default].append(a, @intCast(b));
for (sw.cases) |c| try s.preds[c.block].append(a, @intCast(b));
},
else => {},
}
}
var changed = false;
var again = true;
while (again) {
again = false;
for (0..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b]) continue;
// Take in the chain of blocks only `b` leads to.
while (true) {
const t = s.term(b).*;
if (t.op != .br or t.op.br.@"else" != null) break;
const c = t.op.br.then;
if (c == b or c == 0 or s.preds[c].items.len != 1) break;
try s.merge(b, c);
changed = true;
again = true;
}
}
for (1..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b] or s.body[b].items.len != 1) continue;
const t = s.term(b).*;
if (t.op != .br or t.op.br.@"else" != null) continue;
const c = t.op.br.then;
const ps = s.preds[b].items;
if (c == b or ps.len == 0) continue;
if (std.mem.indexOfScalar(u32, ps, b) != null) continue;
// With phis in `c`, a predecessor already branching there could
// need two values on one edge: left alone.
if (s.hasPhis(c)) {
const clash = for (ps) |p| {
if (s.countPred(c, p) != 0) break true;
} else false;
if (clash) continue;
}
try s.bypass(b, c);
changed = true;
again = true;
}
for (0..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b] or !try s.collapse(b)) continue;
changed = true;
again = true;
}
for (1..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b] or !try s.ifConvert(b)) continue;
changed = true;
again = true;
}
}
if (!changed) return false;
// Lay the blocks out again, in their old order, and renumber.
const new_block = try a.alloc(u32, nb);
var kept: u32 = 0;
for (0..nb) |b| {
new_block[b] = if (s.alive[b]) kept else none;
if (s.alive[b]) kept += 1;
}
const index = try a.alloc(u32, n);
@memset(index, none);
var count: u32 = 0;
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
if (s.repl[i] != null) continue;
index[i] = count;
count += 1;
};
const Map = struct {
repl: []const ?Value,
index: []const u32,
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
var x = v;
while (x == .inst) {
const r = ctx.repl[x.inst] orelse break;
x = r;
}
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
}
};
var map: Map = .{ .repl = s.repl, .index = index };
const ma = m.allocator();
var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count);
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
if (s.repl[i] != null) continue;
var inst = s.insts[i];
try promote.operands(true, ma, &inst, &map);
switch (inst.op) {
.phi => |*p| {
const es: []Edge = @constCast(p.incoming);
for (es) |*e| e.block = new_block[s.find(e.block)];
},
.br => |*br| {
br.then = new_block[br.then];
if (br.@"else") |*e| e.* = new_block[e.*];
},
.@"switch" => |*sw| {
sw.default = new_block[sw.default];
const cs = try ma.alloc(Case, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = new_block[c.block] };
sw.cases = cs;
},
else => {},
}
out.appendAssumeCapacity(inst);
};
f.insts = out;
f.num_blocks = kept;
return true;
}

325
src/dxil/cse.zig Normal file
View File

@ -0,0 +1,325 @@
//! Common subexpression elimination over the dominator tree, as dxc's
//! EarlyCSE and GVN do it: an instruction that computes what one in a
//! dominating position already computed (same operation, same operands)
//! is replaced by it. Only instructions without effects and whose result
//! depends on nothing but their operands: arithmetic, comparisons, casts,
//! selects, address computations, readnone dx.op calls, and the readonly
//! ones that read what cannot change during the shader (constant buffer
//! loads, handle creation).
//!
//! Inlining every call and lowering each use of a cbuffer field to its own
//! load leaves many such repeats.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const promote = @import("promote.zig");
const stats = @import("../stats.zig");
const Value = module.Value;
const Inst = module.Inst;
const none = std.math.maxInt(u32);
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
/// dx.op readonly operations that read only what a dispatch cannot change:
/// CreateHandle, CBufferLoad, CBufferLoadLegacy, CreateHandleForLib,
/// CreateHandleFromBinding, CreateHandleFromHeap.
fn stableReadonly(opcode: i64) bool {
return switch (opcode) {
57, 58, 59, 160, 217, 218 => true,
else => false,
};
}
fn eligible(m: *const module.Module, inst: Inst) bool {
return switch (inst.op) {
.binop, .cast, .cmp, .select, .extractvalue, .gep, .extractelement, .insertelement => true,
.call => |c| {
const callee = m.functions.items[c.callee];
if (callee.num_blocks != 0 or !std.mem.startsWith(u8, callee.name, "dx.op.")) return false;
switch (callee.attrs) {
.nounwind_readnone => return true,
.nounwind_readonly => {
if (c.args.len == 0 or c.args[0] != .constant) return false;
return switch (m.constants.items[c.args[0].constant].kind) {
.int => |k| stableReadonly(k),
else => false,
};
},
else => return false,
}
},
else => false,
};
}
/// An instruction's identity as bytes: its operation, type, the fields
/// that are not operands, and its operands (resolved through replaced
/// instructions).
const Key = struct {
buf: std.ArrayList(u8) = .empty,
a: Allocator,
repl: []const ?Value,
failed: bool = false,
fn resolve(k: *const Key, v: Value) Value {
var x = v;
while (x == .inst) {
const r = k.repl[x.inst] orelse break;
x = r;
}
return x;
}
fn word(k: *Key, w: u64) void {
k.buf.appendSlice(k.a, std.mem.asBytes(&w)) catch {
k.failed = true;
};
}
pub fn visit(k: *Key, v: Value, _: promote.Role) Value {
const x = k.resolve(v);
const tag: u64 = @backingInt(std.meta.activeTag(x));
const id: u64 = switch (x) {
inline else => |i| i,
};
k.word(tag << 32 | id);
return v;
}
fn build(k: *Key, inst: Inst) Allocator.Error![]const u8 {
k.buf.clearRetainingCapacity();
k.word(@backingInt(std.meta.activeTag(inst.op)));
k.word(inst.ty);
switch (inst.op) {
.binop => |b| k.word(@as(u64, @backingInt(b.op)) << 32 | b.flags),
.cast => |c| k.word(@backingInt(c.op)),
.cmp => |c| k.word(c.pred),
.extractvalue => |x| k.word(x.index),
.gep => |g| k.word(g.elem),
.call => |c| k.word(c.callee),
else => {},
}
var copy = inst;
try promote.operands(false, k.a, &copy, k);
if (k.failed) return error.OutOfMemory;
return k.buf.items;
}
};
/// Replaces `func`'s repeated computations; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.cse);
defer zone.end();
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
const nb = f.num_blocks;
if (n == 0 or nb == 0) return false;
const block_start = try a.alloc(u32, nb + 1);
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| if (isTerminator(inst)) {
if (b >= nb) return false;
b += 1;
block_start[b] = @intCast(i + 1);
};
if (b != nb or block_start[nb] != n) return false;
}
// Successors, predecessors.
const succ_off = try a.alloc(u32, nb + 1);
var succs: std.ArrayList(u32) = .empty;
for (0..nb) |b| {
succ_off[b] = @intCast(succs.items.len);
switch (insts[block_start[b + 1] - 1].op) {
.br => |br| {
try succs.append(a, br.then);
if (br.@"else") |e| try succs.append(a, e);
},
.@"switch" => |sw| {
try succs.append(a, sw.default);
for (sw.cases) |c| try succs.append(a, c.block);
},
else => {},
}
}
succ_off[nb] = @intCast(succs.items.len);
const pred_off = try a.alloc(u32, nb + 1);
@memset(pred_off, 0);
for (succs.items) |s| pred_off[s + 1] += 1;
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
const preds = try a.alloc(u32, succs.items.len);
{
const fill = try a.dupe(u32, pred_off[0..nb]);
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
preds[fill[s]] = @intCast(b);
fill[s] += 1;
};
}
// Reverse postorder, then immediate dominators (Cooper, Harvey and
// Kennedy).
const rpo_index = try a.alloc(u32, nb);
@memset(rpo_index, none);
const rpo = try a.alloc(u32, nb);
var nr: u32 = 0;
{
const post = try a.alloc(u32, nb);
var np: u32 = 0;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Frame = struct { b: u32, next: u32 };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (top.next < succ_off[top.b + 1]) {
const s = succs.items[top.next];
top.next += 1;
if (!seen[s]) {
seen[s] = true;
try stack.append(a, .{ .b = s, .next = succ_off[s] });
}
} else {
post[np] = top.b;
np += 1;
_ = stack.pop();
}
}
for (0..np) |k| {
rpo[k] = post[np - 1 - k];
rpo_index[rpo[k]] = @intCast(k);
}
nr = np;
}
const idom = try a.alloc(u32, nb);
@memset(idom, none);
idom[0] = 0;
{
var changed = true;
while (changed) {
changed = false;
for (rpo[1..nr]) |b| {
var new: u32 = none;
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
if (idom[p] == none) continue;
if (new == none) {
new = p;
continue;
}
var x = p;
var y = new;
while (x != y) {
while (rpo_index[x] > rpo_index[y]) x = idom[x];
while (rpo_index[y] > rpo_index[x]) y = idom[y];
}
new = x;
}
if (new != idom[b]) {
idom[b] = new;
changed = true;
}
}
}
}
// Dominator tree children, in reverse postorder.
const child_off = try a.alloc(u32, nb + 1);
@memset(child_off, 0);
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
const children = try a.alloc(u32, if (nr > 0) nr - 1 else 0);
{
const fill = try a.dupe(u32, child_off[0..nb]);
for (rpo[1..nr]) |b| {
children[fill[idom[b]]] = b;
fill[idom[b]] += 1;
}
}
const repl = try a.alloc(?Value, n);
@memset(repl, null);
// The keys of the instructions available (in the dominating blocks),
// to the instruction.
var table: std.StringHashMapUnmanaged(u32) = .empty;
var added: std.ArrayList([]const u8) = .empty;
var key: Key = .{ .a = a, .repl = repl };
var found = false;
const Frame = struct { b: u32, next: u32, mark: usize };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = child_off[0], .mark = 0 });
var entered = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (entered) {
entered = false;
top.mark = added.items.len;
for (block_start[top.b]..block_start[top.b + 1]) |i| {
const inst = insts[i];
if (!eligible(m, inst)) continue;
// (The key is built in one buffer, and kept only if new.)
const gop = try table.getOrPut(a, try key.build(inst));
if (gop.found_existing) {
repl[i] = .{ .inst = gop.value_ptr.* };
found = true;
} else {
gop.key_ptr.* = try a.dupe(u8, key.buf.items);
gop.value_ptr.* = @intCast(i);
try added.append(a, gop.key_ptr.*);
}
}
}
if (top.next < child_off[top.b + 1]) {
const c = children[top.next];
top.next += 1;
try stack.append(a, .{ .b = c, .next = child_off[c], .mark = 0 });
entered = true;
} else {
for (added.items[top.mark..]) |k| _ = table.remove(k);
added.shrinkRetainingCapacity(top.mark);
_ = stack.pop();
}
}
if (!found) return false;
// Renumber without the replaced instructions.
const index = try a.alloc(u32, n);
var count: u32 = 0;
for (0..n) |i| {
index[i] = count;
if (repl[i] == null) count += 1;
}
const Map = struct {
repl: []const ?Value,
index: []const u32,
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
var x = v;
while (x == .inst) {
const r = ctx.repl[x.inst] orelse break;
x = r;
}
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
}
};
var map: Map = .{ .repl = repl, .index = index };
const ma = m.allocator();
var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count);
for (insts, 0..) |inst, i| {
if (repl[i] != null) continue;
var copy = inst;
try promote.operands(true, ma, &copy, &map);
out.appendAssumeCapacity(copy);
}
f.insts = out;
return true;
}

File diff suppressed because it is too large Load Diff

View File

@ -191,6 +191,22 @@ pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) I
fl |= bit.requires_group;
info.mask &= stage_group;
},
// Barrier by memory type, UAV or node record: groupshared memory
// (not as part of ALL_MEMORY, which may drop it) or group
// sync / scope semantics need a group (as dxc's
// BarrierRequiresGroup).
244, 245, 246 => if (args.len > 2) {
var needs = false;
if (code == 244) if (constInt(m, args[1])) |mem| {
const kept = if (mem == 0xF) mem & ~@as(i64, 2) else mem;
needs = kept & 2 != 0;
};
if (constInt(m, args[2])) |sem| needs = needs or sem & 3 != 0;
if (needs) {
fl |= bit.requires_group;
info.mask &= stage_group;
}
},
else => {},
}
}
@ -237,7 +253,7 @@ pub fn featureInfo(fl: u64) u64 {
.{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 },
.{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 },
.{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ 1 << 27, 0x400000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
};
var out: u64 = 0;
for (map) |e| if (fl & e[0] != 0) {
@ -306,6 +322,11 @@ fn handleRes(m: *const module.Module, f: *const module.Function, o: Options, h:
},
.load => |l| {
if (l.ptr == .global) return o.globals[l.ptr.global];
// An element of a resource array global.
if (l.ptr == .inst) switch (f.insts.items[l.ptr.inst].op) {
.gep => |g| if (g.ptr == .global) return o.globals[g.ptr.global],
else => {},
};
return null;
},
else => return null,

View File

@ -69,7 +69,11 @@ pub fn global(a: Allocator, t: *TypeTable, name: []const u8, ty: TypeId) Allocat
var names: Names = .{};
try names.add(a, name);
try out.print(a, "\x01?{s}@@3", .{name});
try typeCode(a, t, ty, &out, &names);
// An array global: a pointer to its element.
if (t.get(ty) == .array) {
try out.appendSlice(a, "PA");
try typeCode(a, t, t.get(ty).array.elem, &out, &names);
} else try typeCode(a, t, ty, &out, &names);
try out.append(a, 'A');
return out.items;
}
@ -137,7 +141,7 @@ fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), na
var et = ty;
while (t.get(et) == .array) : (et = t.get(et).array.elem) try dims.append(a, t.get(et).array.len);
try out.append(a, 'Y');
try number(a, dims.items.len - 1, out);
try number(a, dims.items.len, out);
for (dims.items) |d| try number(a, d, out);
try typeCode(a, t, et, out, names);
},

View File

@ -3,6 +3,7 @@
//! unabbreviated records only.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const bitstream = @import("bitstream.zig");
@ -39,6 +40,38 @@ pub const Type = union(enum) {
}
};
/// splitmix64's finalizer: a cheap hash of a word, for the type and
/// constant pools (a hash map uses both its high and low bits).
fn mix(x: u64) u64 {
var z = x;
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
return z ^ (z >> 31);
}
/// Hashes what Type.eql compares.
const TypeContext = struct {
pub fn hash(_: TypeContext, t: Type) u64 {
const tag: u64 = @backingInt(t);
return switch (t) {
.void, .label, .metadata, .half, .float, .double => mix(tag),
.int => |w| mix(tag << 56 | w),
.pointer => |p| mix(tag << 56 | @as(u64, p.addr_space) << 32 | p.elem),
.function => |f| mix(tag << 56 | f.ret) ^ std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.params)),
.@"struct" => |st| mix(tag) ^ std.hash.Wyhash.hash(0, st.name),
.array => |x| mix(mix(tag << 56 | x.elem) ^ x.len),
.vector => |x| mix(tag << 56 | @as(u64, x.len) << 32 | x.elem),
};
}
pub fn eql(_: TypeContext, a: Type, b: Type) bool {
return a.eql(b);
}
};
const no_type = std.math.maxInt(TypeId);
const no_const = std.math.maxInt(ConstId);
pub const Constant = struct {
ty: TypeId,
kind: union(enum) {
@ -52,10 +85,28 @@ pub const Constant = struct {
},
};
/// Constants are equal when their type and kind are (aggregates: the same
/// element slice, as std.meta.eql compares slices).
const ConstantContext = struct {
pub fn hash(_: ConstantContext, c: Constant) u64 {
const head = mix(@as(u64, @backingInt(c.kind)) << 32 | c.ty);
return switch (c.kind) {
.int => |v| mix(head ^ @as(u64, @bitCast(v))),
.float_bits => |v| mix(head ^ v),
.undef, .null => head,
.aggregate => |a| mix(head ^ @intFromPtr(a.ptr) ^ a.len << 48),
};
}
pub fn eql(_: ConstantContext, a: Constant, b: Constant) bool {
return a.ty == b.ty and std.meta.eql(a.kind, b.kind);
}
};
pub const Linkage = enum(u32) { external = 0, internal = 3 };
/// Attribute group for function declarations (e.g. dx.op functions).
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind };
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind, noduplicate_nounwind };
pub const Value = union(enum) {
/// Index into Module.globals (a pointer to the variable).
@ -106,6 +157,23 @@ pub const Inst = struct {
extractelement: struct { vec: Value, index: Value },
insertelement: struct { vec: Value, val: Value, index: Value },
},
/// An attached metadata node, as `!dx.nonuniform` on a resource
/// array's getelementptr (see Module.instMd).
md: InstMd = .none,
};
/// An instruction's metadata attachment: an index into Module.inst_mds,
/// kept out of line (few instructions have one).
/// `unroll` is no attachment: it marks the back edge of an `[unroll]` loop
/// for the unroller, and is not written.
pub const InstMd = enum(u32) {
none = 0,
unroll = std.math.maxInt(u32),
_,
pub fn written(md: InstMd) bool {
return md != .none and md != .unroll;
}
};
pub const Function = struct {
@ -127,15 +195,26 @@ pub const Metadata = union(enum) {
};
pub const Module = struct {
arena: std.heap.ArenaAllocator,
arena: BumpArena,
triple: []const u8 = "dxil-ms-dx",
datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
types: std.ArrayList(Type) = .empty,
/// Index of `types`, for getType to find existing ones.
type_ids: std.HashMapUnmanaged(Type, TypeId, TypeContext, std.hash_map.default_max_load_percentage) = .empty,
constants: std.ArrayList(Constant) = .empty,
/// Index of `constants`, for constant() to find existing ones.
constant_ids: std.HashMapUnmanaged(Constant, ConstId, ConstantContext, std.hash_map.default_max_load_percentage) = .empty,
functions: std.ArrayList(Function) = .empty,
/// intType's and constInt's results for common arguments.
int_types: [65]TypeId = @splat(no_type),
small_i32: [1024]ConstId = @splat(no_const),
globals: std.ArrayList(GlobalVar) = .empty,
metadata: std.ArrayList(Metadata) = .empty,
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
/// Instruction metadata attachments (InstMd), from 1.
inst_mds: std.ArrayList(struct { kind: u32, node: MdId }) = .empty,
/// Instruction metadata kinds, by id.
md_kinds: std.ArrayList([]const u8) = .empty,
pub fn init(gpa: Allocator) Module {
return .{ .arena = .init(gpa) };
@ -150,9 +229,7 @@ pub const Module = struct {
}
pub fn getType(m: *Module, t: Type) !TypeId {
for (m.types.items, 0..) |existing, i| {
if (existing.eql(t)) return @intCast(i);
}
if (m.type_ids.get(t)) |id| return id;
const a = m.allocator();
var owned = t;
switch (owned) {
@ -163,11 +240,18 @@ pub const Module = struct {
},
else => {},
}
const id: TypeId = @intCast(m.types.items.len);
try m.type_ids.ensureUnusedCapacity(a, 1);
try m.types.append(a, owned);
return @intCast(m.types.items.len - 1);
m.type_ids.putAssumeCapacity(owned, id);
return id;
}
pub fn intType(m: *Module, bits: u32) !TypeId {
if (bits < m.int_types.len) {
if (m.int_types[bits] == no_type) m.int_types[bits] = try m.getType(.{ .int = bits });
return m.int_types[bits];
}
return m.getType(.{ .int = bits });
}
@ -195,17 +279,134 @@ pub const Module = struct {
}
pub fn constant(m: *Module, c: Constant) !Value {
for (m.constants.items, 0..) |existing, i| {
if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) };
const gop = try m.constant_ids.getOrPut(m.allocator(), c);
if (!gop.found_existing) {
gop.value_ptr.* = @intCast(m.constants.items.len);
m.constants.append(m.allocator(), c) catch |err| {
m.constant_ids.removeByPtr(gop.key_ptr);
return err;
};
}
try m.constants.append(m.allocator(), c);
return .{ .constant = @intCast(m.constants.items.len - 1) };
return .{ .constant = gop.value_ptr.* };
}
pub fn constInt(m: *Module, bits: u32, v: i64) !Value {
if (bits == 32 and v >= 0 and v < m.small_i32.len) {
const k: usize = @intCast(v);
if (m.small_i32[k] == no_const) m.small_i32[k] = (try m.constant(.{ .ty = try m.intType(32), .kind = .{ .int = v } })).constant;
return .{ .constant = m.small_i32[k] };
}
return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } });
}
/// An attachment of node `node` as metadata kind `kind` (from mdKind).
pub fn instMd(m: *Module, kind: u32, node: MdId) !InstMd {
try m.inst_mds.append(m.allocator(), .{ .kind = kind, .node = node });
return @fromBackingInt(@intCast(m.inst_mds.items.len));
}
/// Drops the constants nothing uses, and numbers the rest in order of
/// first use (functions' instructions, then metadata), grouped by type,
/// with aggregates last, after their elements. The output then depends
/// only on the code that is left, not on code made and removed again or
/// on the order constants were first asked for.
fn pruneConstants(m: *Module) !void {
const a = m.allocator();
const n = m.constants.items.len;
if (n == 0) return;
const Walk = struct {
m: *Module,
a: Allocator,
seen: []bool,
order: std.ArrayList(ConstId) = .empty,
failed: bool = false,
fn map(w: *@This(), v: Value) Value {
if (v == .constant) w.visit(v.constant) catch {
w.failed = true;
};
return v;
}
fn visit(w: *@This(), c: ConstId) Allocator.Error!void {
if (w.seen[c]) return;
w.seen[c] = true;
switch (w.m.constants.items[c].kind) {
.aggregate => |els| for (els) |el| try w.visit(el),
else => {},
}
try w.order.append(w.a, c);
}
};
var walk: Walk = .{ .m = m, .a = a, .seen = try a.alloc(bool, n) };
@memset(walk.seen, false);
for (m.functions.items) |f| for (f.insts.items) |inst| {
var copy = inst;
// (Reading only: no slice is copied, nothing changes.)
try mapOperands(a, &copy, &walk);
};
for (m.metadata.items) |md| if (md == .value) {
_ = walk.map(md.value.val);
};
if (walk.failed) return error.OutOfMemory;
// Types in order of first use; scalars by type (stable), then
// aggregates in walk order (each after its elements).
var rank: std.AutoHashMapUnmanaged(TypeId, u32) = .empty;
const Key = struct { rank: u32, id: ConstId };
var scalars: std.ArrayList(Key) = .empty;
var aggregates: std.ArrayList(ConstId) = .empty;
for (walk.order.items) |c| {
const k = m.constants.items[c];
if (k.kind == .aggregate) {
try aggregates.append(a, c);
continue;
}
const gop = try rank.getOrPut(a, k.ty);
if (!gop.found_existing) gop.value_ptr.* = rank.count() - 1;
try scalars.append(a, .{ .rank = gop.value_ptr.*, .id = c });
}
std.sort.block(Key, scalars.items, {}, struct {
fn lt(_: void, x: Key, y: Key) bool {
return x.rank < y.rank;
}
}.lt);
const new_id = try a.alloc(ConstId, n);
@memset(new_id, no_const);
var kept: std.ArrayList(Constant) = .empty;
try kept.ensureTotalCapacityPrecise(a, walk.order.items.len);
for (scalars.items) |k| {
new_id[k.id] = @intCast(kept.items.len);
kept.appendAssumeCapacity(m.constants.items[k.id]);
}
for (aggregates.items) |c| {
var k = m.constants.items[c];
const els = try a.alloc(ConstId, k.kind.aggregate.len);
for (k.kind.aggregate, els) |el, *o| o.* = new_id[el];
k.kind = .{ .aggregate = els };
new_id[c] = @intCast(kept.items.len);
kept.appendAssumeCapacity(k);
}
const Remap = struct {
new_id: []const ConstId,
fn map(r: @This(), v: Value) Value {
return if (v == .constant) .{ .constant = r.new_id[v.constant] } else v;
}
};
const remap: Remap = .{ .new_id = new_id };
for (m.functions.items) |*f| for (f.insts.items) |*inst| try mapOperands(a, inst, remap);
for (m.metadata.items) |*md| if (md.* == .value) {
md.value.val = remap.map(md.value.val);
};
m.constants = kept;
// (Constants made from here on start a new index.)
m.constant_ids = .empty;
for (m.constants.items, 0..) |c, i| try m.constant_ids.put(a, c, @intCast(i));
m.small_i32 = @splat(no_const);
}
pub fn addFunction(m: *Module, f: Function) !u32 {
var owned = f;
owned.name = try m.allocator().dupe(u8, f.name);
@ -250,6 +451,13 @@ pub const Module = struct {
return @intCast(m.metadata.items.len - 1);
}
/// The id of an instruction metadata kind.
pub fn mdKind(m: *Module, name: []const u8) !u32 {
for (m.md_kinds.items, 0..) |k, i| if (std.mem.eql(u8, k, name)) return @intCast(i);
try m.md_kinds.append(m.allocator(), try m.allocator().dupe(u8, name));
return @intCast(m.md_kinds.items.len - 1);
}
pub fn addNamedMetadata(m: *Module, name: []const u8, nodes: []const MdId) !void {
const a = m.allocator();
try m.named_metadata.append(a, .{ .name = try a.dupe(u8, name), .nodes = try a.dupe(MdId, nodes) });
@ -257,12 +465,94 @@ pub const Module = struct {
/// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE).
pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 {
try m.pruneConstants();
var enc: Encoder = .{ .m = m, .w = .init(gpa) };
defer enc.w.deinit();
return enc.write();
}
};
/// Calls `ctx.map(v) Value` on each value operand of `inst` and stores the
/// results; operand slices whose values change are copied (slices may be
/// shared between instructions).
fn mapOperands(a: Allocator, inst: *Inst, ctx: anytype) !void {
const S = struct {
fn many(al: Allocator, c: anytype, xs: []const Value) ![]const Value {
for (xs, 0..) |x, k| {
if (std.meta.eql(c.map(x), x)) continue;
const out = try al.dupe(Value, xs);
for (out[k..]) |*o| o.* = c.map(o.*);
return out;
}
return xs;
}
};
switch (inst.op) {
.ret => |*v| if (v.*) |x| {
v.* = ctx.map(x);
},
.br => |*b| if (b.cond) |c| {
b.cond = ctx.map(c);
},
.@"switch" => |*sw| {
sw.cond = ctx.map(sw.cond);
const cases = try a.dupe(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases);
for (cases) |*c| c.val = ctx.map(c.val);
sw.cases = cases;
},
.call => |*c| c.args = try S.many(a, ctx, c.args),
.binop => |*b| {
b.lhs = ctx.map(b.lhs);
b.rhs = ctx.map(b.rhs);
},
.cast => |*c| c.val = ctx.map(c.val),
.cmp => |*c| {
c.lhs = ctx.map(c.lhs);
c.rhs = ctx.map(c.rhs);
},
.select => |*x| {
x.cond = ctx.map(x.cond);
x.t = ctx.map(x.t);
x.f = ctx.map(x.f);
},
.extractvalue => |*x| x.agg = ctx.map(x.agg),
.phi => |*p| {
const ins = try a.dupe(@typeInfo(@TypeOf(p.incoming)).pointer.child, p.incoming);
for (ins) |*in| in.val = ctx.map(in.val);
p.incoming = ins;
},
.alloca => |*x| x.size = ctx.map(x.size),
.load => |*x| x.ptr = ctx.map(x.ptr),
.store => |*x| {
x.ptr = ctx.map(x.ptr);
x.val = ctx.map(x.val);
},
.gep => |*x| {
x.ptr = ctx.map(x.ptr);
x.indices = try S.many(a, ctx, x.indices);
},
.atomicrmw => |*x| {
x.ptr = ctx.map(x.ptr);
x.val = ctx.map(x.val);
},
.cmpxchg => |*x| {
x.ptr = ctx.map(x.ptr);
x.cmp = ctx.map(x.cmp);
x.new = ctx.map(x.new);
},
.@"unreachable" => {},
.extractelement => |*x| {
x.vec = ctx.map(x.vec);
x.index = ctx.map(x.index);
},
.insertelement => |*x| {
x.vec = ctx.map(x.vec);
x.val = ctx.map(x.val);
x.index = ctx.map(x.index);
},
}
}
const block_module = 8;
const block_paramattr = 9;
const block_paramattr_group = 10;
@ -270,6 +560,7 @@ const block_constants = 11;
const block_function = 12;
const block_value_symtab = 14;
const block_metadata = 15;
const block_metadata_attachment = 16;
const block_type = 17;
const Encoder = struct {
@ -371,6 +662,12 @@ const Encoder = struct {
}
try e.writeConstants();
try e.writeMetadata();
if (e.m.md_kinds.items.len != 0) {
// METADATA_KIND: [id, name...]
try w.enterBlock(block_metadata, 3);
for (e.m.md_kinds.items, 0..) |k, id| try w.recordString(6, &.{id}, k);
try w.endBlock();
}
try e.writeSymtab();
for (e.m.functions.items) |*f| {
if (f.num_blocks != 0) try e.writeFunction(f);
@ -384,12 +681,19 @@ const Encoder = struct {
}
fn writeAttributes(e: *Encoder) !void {
// Groups 1..5 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: noinline = 14, noreturn = 17, nounwind = 18,
// readnone = 20, readonly = 21.
// Groups 1..6 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: noduplicate = 12, noinline = 14, noreturn = 17,
// nounwind = 18, readnone = 20, readonly = 21.
const w = &e.w;
try w.enterBlock(block_paramattr_group, 3);
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 } };
const all = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 }, &.{ 12, 18 } };
// noduplicate (the SM 6.8 barriers) only when used: the rest of
// the modules are as they were.
var n: usize = 5;
for (e.m.functions.items) |f| {
if (f.attrs == .noduplicate_nounwind) n = 6;
}
const groups = all[0..n];
for (groups, 1..) |kinds, id| {
try e.push(id);
try e.push(0xFFFFFFFF);
@ -681,6 +985,18 @@ const Encoder = struct {
}
if (e.m.types.items[inst.ty] != .void) inst_id += 1;
}
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
var any_md = false;
for (f.insts.items) |inst| any_md = any_md or inst.md.written();
if (any_md) {
try w.enterBlock(block_metadata_attachment, 3);
for (f.insts.items, 0..) |inst, k| if (inst.md.written()) {
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
try e.rec(11);
};
try w.endBlock();
}
try w.endBlock();
}
};

1670
src/dxil/promote.zig Normal file

File diff suppressed because it is too large Load Diff

View File

@ -5,11 +5,13 @@
//! Layout: a header (version, part count), part offsets, then each
//! non-empty part as (type, size) and its 4-byte aligned contents. Parts
//! come in the order dxc adds them: strings, resources, functions, index
//! arrays, raw bytes, subobjects, then the record tables of the extended
//! function properties (SM 6.10 linear algebra).
//! arrays, raw bytes, subobjects, then the other record tables: work graph
//! nodes (validator 1.8+) and the extended function properties (SM 6.10
//! linear algebra).
const std = @import("std");
const Allocator = std.mem.Allocator;
const shader = @import("shader.zig");
pub const null_ref: u32 = 0xffff_ffff;
@ -24,7 +26,8 @@ pub const Resource = struct {
flags: u32 = 0,
};
/// RuntimeDataFunctionInfo3 (validator 1.10+).
/// RuntimeDataFunctionInfo3 (validator 1.10+; before, 2: without the
/// extended properties).
pub const Function = struct {
name: u32,
unmangled_name: u32,
@ -44,9 +47,14 @@ pub const Function = struct {
extended_properties: u32 = null_ref,
};
/// The extended function property tables, in part order (part types
/// 13..20).
/// The other record tables, by part type: work graph nodes (7..11) and
/// the extended function properties (13..20).
pub const Ext = enum(u32) {
node_ids = 7,
node_io_attribs,
node_func_attribs,
io_nodes,
node_shaders,
properties = 13,
shapes,
constructions,
@ -59,8 +67,10 @@ pub const Ext = enum(u32) {
/// Record size in bytes.
pub fn stride(t: Ext) usize {
return switch (t) {
.node_shaders => 20,
.shapes => 12,
.properties, .constructions, .wave_multiplies, .group_multiplies => 8,
.node_ids, .node_io_attribs, .node_func_attribs, .io_nodes => 8,
.thread_matvec, .outer_products, .accumulate_stores => 4,
};
}
@ -75,7 +85,8 @@ pub const Builder = struct {
functions: std.ArrayList([14]u32) = .empty,
raw: std.ArrayList(u8) = .empty,
subobjects: std.ArrayList([6]u32) = .empty,
ext: [8]std.ArrayList(u8) = @splat(.empty),
/// By part type, from 7.
ext: [14]std.ArrayList(u8) = @splat(.empty),
pub fn init(gpa: Allocator) Allocator.Error!Builder {
var b: Builder = .{ .gpa = gpa };
@ -132,7 +143,7 @@ pub const Builder = struct {
/// (record deduplication, validator 1.7+).
pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 {
std.debug.assert(rec.len == t.stride());
const tab = &b.ext[@intFromEnum(t) - 13];
const tab = &b.ext[@backingInt(t) - 7];
var at: usize = 0;
while (at < tab.items.len) : (at += rec.len) {
if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len);
@ -165,7 +176,11 @@ pub const Builder = struct {
try parts.append(b.gpa, .{ .ty = 3, .data = t });
}
if (b.functions.items.len > 0) {
const t = try table(b.gpa, 14, std.mem.sliceAsBytes(b.functions.items), b.functions.items.len);
const words: usize = if (shader.validatorAtLeast(1, 10)) 14 else 13;
const rows = try b.gpa.alloc(u32, words * b.functions.items.len);
defer b.gpa.free(rows);
for (b.functions.items, 0..) |f, k| @memcpy(rows[k * words ..][0..words], f[0..words]);
const t = try table(b.gpa, words, std.mem.sliceAsBytes(rows), b.functions.items.len);
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 4, .data = t });
}
@ -176,8 +191,12 @@ pub const Builder = struct {
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 6, .data = t });
}
for (b.ext, 13..) |rows, ty| if (rows.items.len > 0) {
const stride = @as(Ext, @enumFromInt(ty)).stride();
// (dxc's table order: the node function attributes before the
// I/O attributes.)
const order = [_]u32{ 7, 9, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20 };
for (order) |ty| if (b.ext[ty - 7].items.len > 0) {
const rows = b.ext[ty - 7];
const stride = @as(Ext, @fromBackingInt(ty)).stride();
const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride);
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t });

207
src/dxil/reflect.zig Normal file
View File

@ -0,0 +1,207 @@
//! Shader reflection: what D3D12's ID3D12ShaderReflection and
//! ID3D12LibraryReflection report about a compiled shader. The DXIL emitter
//! builds it; the DXC drop-in hands it out as DXC_OUT_REFLECTION and reads
//! it back in IDxcUtils::CreateReflection.
//!
//! The blob is a DXIL container: the object's SFI0 part, its signatures'
//! records in declaration order (the parameters reflection reports), and a
//! ZRFL part holding the rest as JSON.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const container = @import("container.zig");
pub const part = container.fourcc("ZRFL");
/// The signatures in declaration order (ISG1 / OSG1 / PSG1's records, which
/// those parts sort by register).
pub const input_part = container.fourcc("ZIS1");
pub const output_part = container.fourcc("ZOS1");
pub const patch_part = container.fourcc("ZPS1");
/// The feature bits reflection reports as required (D3D_SHADER_REQUIRES_*):
/// the bits from 40 up are DXC's optional feature info.
pub const required_features: u64 = (1 << 40) - 1;
/// D3D12_SHADER_INPUT_BIND_DESC.
pub const Bind = struct {
name: []const u8,
/// D3D_SHADER_INPUT_TYPE.
type: u32,
bind_point: u32,
/// 0 for an unbounded range.
bind_count: u32,
/// D3D_SHADER_INPUT_FLAGS.
flags: u32 = 0,
/// D3D_RESOURCE_RETURN_TYPE.
return_type: u32 = 0,
/// D3D_SRV_DIMENSION.
dimension: u32 = 0,
/// The sample count of multisampled textures; the stride of structured
/// buffers.
num_samples: u32 = 0,
space: u32,
id: u32,
};
/// D3D12_SHADER_TYPE_DESC (members by index into Reflection.types).
pub const Type = struct {
/// D3D_SHADER_VARIABLE_CLASS.
class: u32,
/// D3D_SHADER_VARIABLE_TYPE.
kind: u32,
rows: u32 = 0,
cols: u32 = 0,
elements: u32 = 0,
offset: u32 = 0,
name: []const u8 = "",
members: []const Member = &.{},
};
pub const Member = struct { name: []const u8, ty: u32 };
/// D3D12_SHADER_VARIABLE_DESC.
pub const Variable = struct {
name: []const u8,
offset: u32,
size: u32,
/// D3D_SHADER_VARIABLE_FLAGS: `used` when the shader reads it.
flags: u32,
ty: u32,
};
/// D3D12_SHADER_BUFFER_DESC and its variables.
pub const CBuffer = struct {
name: []const u8,
/// D3D_CBUFFER_TYPE.
kind: u32,
size: u32,
flags: u32 = 0,
vars: []const Variable,
};
/// A library function (ID3D12FunctionReflection): indices into
/// Reflection.binds and Reflection.cbuffers.
pub const Function = struct {
name: []const u8,
version: u32,
requires: u64,
binds: []const u32,
cbuffers: []const u32,
};
pub const Reflection = struct {
/// D3D12_SHVER: program type << 16, major << 4, minor.
version: u32,
requires: u64 = 0,
instructions: u32 = 0,
thread_group: [3]u32 = .{ 0, 0, 0 },
binds: []const Bind = &.{},
cbuffers: []const CBuffer = &.{},
types: []const Type = &.{},
functions: []const Function = &.{},
/// Geometry and tessellation state (D3D12_SHADER_DESC).
input_primitive: u32 = 0,
gs_output_topology: u32 = 0,
gs_max_vertices: u32 = 0,
gs_instances: u32 = 0,
control_points: u32 = 0,
hs_output_primitive: u32 = 0,
hs_partitioning: u32 = 0,
tess_domain: u32 = 0,
sample_frequency: bool = false,
};
// D3D enums (d3dcommon.h) used here.
pub const sit = struct {
pub const cbuffer = 0;
pub const tbuffer = 1;
pub const texture = 2;
pub const sampler = 3;
pub const uav_rwtyped = 4;
pub const structured = 5;
pub const uav_rwstructured = 6;
pub const byteaddress = 7;
pub const uav_rwbyteaddress = 8;
pub const uav_append_structured = 9;
pub const uav_consume_structured = 10;
pub const uav_rwstructured_with_counter = 11;
pub const rtaccelerationstructure = 12;
pub const uav_feedbacktexture = 13;
};
pub const sif_userpacked = 1;
pub const sif_comparison_sampler = 2;
pub const svf_userpacked = 1;
pub const svf_used = 2;
pub const ct_cbuffer = 0;
pub const ct_tbuffer = 1;
pub const ct_resource_bind_info = 3;
pub const svc = struct {
pub const scalar = 0;
pub const vector = 1;
pub const matrix_rows = 2;
pub const matrix_columns = 3;
pub const object = 4;
pub const @"struct" = 5;
};
pub const ret = struct {
pub const unorm = 1;
pub const snorm = 2;
pub const sint = 3;
pub const uint = 4;
pub const float = 5;
pub const mixed = 6;
pub const double = 7;
};
/// D3D12_SHVER program types.
pub fn programType(stage: []const u8) u32 {
const names = [_][]const u8{ "pixel", "vertex", "geometry", "hull", "domain", "compute", "library", "raygeneration", "intersection", "anyhit", "closesthit", "miss", "callable", "mesh", "amplification", "node" };
for (names, 0..) |n, i| if (std.mem.eql(u8, n, stage)) return @intCast(i);
return 5;
}
pub fn version(program_type: u32, major: u32, minor: u32) u32 {
return program_type << 16 | major << 4 | minor;
}
/// The reflection blob: `parts` (SFI0 and the signatures) and the ZRFL
/// part.
pub fn encode(gpa: Allocator, r: Reflection, parts: []const container.Part) Allocator.Error![]u8 {
const json = try std.json.Stringify.valueAlloc(gpa, r, .{});
defer gpa.free(json);
var all: std.ArrayList(container.Part) = .empty;
defer all.deinit(gpa);
try all.appendSlice(gpa, parts);
try all.append(gpa, .{ .fourcc = part, .data = json });
return container.assemble(gpa, all.items);
}
/// The ZRFL part of a reflection blob (padding included), parsed into
/// `arena`.
pub fn decode(arena: Allocator, json: []const u8) !Reflection {
const text = std.mem.trimEnd(u8, json, "\x00");
return std.json.parseFromSliceLeaky(Reflection, arena, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always });
}
test "encode and decode" {
const a = std.testing.allocator;
const r: Reflection = .{
.version = version(0, 6, 6),
.requires = 1 << 40,
.binds = &.{.{ .name = "Tex", .type = sit.texture, .bind_point = 3, .bind_count = 1, .space = 0, .id = 0 }},
.cbuffers = &.{.{ .name = "$Globals", .kind = ct_cbuffer, .size = 16, .vars = &.{.{ .name = "A", .offset = 0, .size = 16, .flags = svf_used, .ty = 0 }} }},
.types = &.{.{ .class = svc.vector, .kind = 3, .rows = 1, .cols = 4, .name = "float4" }},
};
const blob = try encode(a, r, &.{});
defer a.free(blob);
var arena: BumpArena = .init(a);
defer arena.deinit();
const view = try container.parse(arena.allocator(), blob);
const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult);
try std.testing.expectEqual(r.version, back.version);
try std.testing.expectEqual(r.requires, back.requires);
try std.testing.expectEqualStrings("Tex", back.binds[0].name);
try std.testing.expectEqualStrings("$Globals", back.cbuffers[0].name);
try std.testing.expectEqual(@as(u32, svf_used), back.cbuffers[0].vars[0].flags);
}

View File

@ -18,6 +18,7 @@
//! Self-contained: depends on std only.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
pub const Version = enum(u32) {
@ -66,7 +67,7 @@ pub fn compile(gpa: Allocator, text: []const u8, version: Version, diag: *Diagno
}
pub fn compileWithOptions(gpa: Allocator, text: []const u8, opts: Options, diag: *Diagnostic) Allocator.Error!?[]u8 {
var arena_state = std.heap.ArenaAllocator.init(gpa);
var arena_state = BumpArena.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();

375
src/dxil/sccp.zig Normal file
View File

@ -0,0 +1,375 @@
//! Sparse conditional constant propagation (Wegman and Zadeck) on a DXIL
//! function in SSA form, over integer values: optimistic, so values carried
//! round a loop that only ever hold one constant are found, and code only
//! reachable through branches that never go that way is left out. (A flag
//! that starts false and is passed back unchanged through a loop, or a loop
//! whose first test already fails, as dxc's optimizer finds them.)
//!
//! The results go into the function as constants: the uses of values found
//! constant, and the conditions of branches found to go one way; promotion
//! then drops what that leaves dead or unreachable.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const stats = @import("../stats.zig");
const unroll = @import("unroll.zig");
const Value = module.Value;
const Inst = module.Inst;
const none = std.math.maxInt(u32);
/// Not yet known (optimistically anything), one constant, or varying.
const Lat = union(enum) {
top,
k: i64,
bot,
fn meet(x: Lat, y: Lat) Lat {
return switch (x) {
.top => y,
.bot => .bot,
.k => |a| switch (y) {
.top => x,
.bot => .bot,
.k => |b| if (a == b) x else .bot,
},
};
}
fn eql(x: Lat, y: Lat) bool {
return std.meta.eql(x, y);
}
};
fn intWidth(m: *const module.Module, ty: module.TypeId) ?u32 {
return switch (m.types.items[ty]) {
.int => |w| w,
else => null,
};
}
fn bitsOf(v: i64, w: u32) u64 {
const u: u64 = @bitCast(v);
return if (w >= 64) u else u & ((@as(u64, 1) << @intCast(w)) - 1);
}
/// A `w`-bit pattern as constants hold it: 0 / 1 for i1, sign-extended
/// above.
fn stored(p: u64, w: u32) i64 {
if (w == 1) return @intCast(p & 1);
if (w >= 64) return @bitCast(p);
const sh: u6 = @intCast(64 - w);
return @as(i64, @bitCast(p << sh)) >> sh;
}
fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) ?module.TypeId {
return switch (v) {
.inst => |i| f.insts.items[i].ty,
.constant => |c| m.constants.items[c].ty,
.arg => |k| m.types.items[f.ty].function.params[k],
else => null,
};
}
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
/// A terminator's successor blocks.
const Succs = struct {
br: [2]u32 = undefined,
sw: ?@FieldType(@FieldType(Inst, "op"), "switch") = null,
len: usize = 0,
fn get(s: Succs, k: usize) u32 {
if (s.sw) |sw| return if (k == 0) sw.default else sw.cases[k - 1].block;
return s.br[k];
}
};
fn successors(term: Inst) Succs {
return switch (term.op) {
.br => |br| if (br.@"else") |e| .{ .br = .{ br.then, e }, .len = 2 } else .{ .br = .{ br.then, 0 }, .len = 1 },
.@"switch" => |sw| .{ .sw = sw, .len = 1 + sw.cases.len },
else => .{},
};
}
/// Runs the propagation on `func`; true if it changed anything.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.sccp);
defer zone.end();
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
const nb = f.num_blocks;
if (n == 0 or nb == 0) return false;
const block_start = try a.alloc(u32, nb + 1);
const block_of = try a.alloc(u32, n);
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| {
if (b >= nb) return false;
block_of[i] = b;
if (isTerminator(inst)) {
b += 1;
block_start[b] = @intCast(i + 1);
}
}
if (b != nb) return false;
}
const lat = try a.alloc(Lat, n);
@memset(lat, .top);
const exec = try a.alloc(bool, nb);
@memset(exec, false);
exec[0] = true;
var edges: std.AutoHashMapUnmanaged(u64, void) = .empty;
const S = struct {
fn key(from: u32, to: u32) u64 {
return @as(u64, from) << 32 | to;
}
};
const Eval = struct {
m: *const module.Module,
f: *const module.Function,
lat: []const Lat,
fn of(s: @This(), v: Value) Lat {
return switch (v) {
.inst => |i| s.lat[i],
.constant => |c| switch (s.m.constants.items[c].kind) {
.int => |x| .{ .k = x },
else => .bot,
},
else => .bot,
};
}
fn inst(s: @This(), i: u32) Lat {
const in = s.f.insts.items[i];
const w = intWidth(s.m, in.ty) orelse return .bot;
switch (in.op) {
.binop => |b| {
const l = s.of(b.lhs);
const r = s.of(b.rhs);
if (l == .bot or r == .bot) {
// (Varying, but a zero still decides these.)
const z = if (l == .k and l.k == 0) true else if (r == .k and r.k == 0) true else false;
if (z and (b.op == .@"and" or b.op == .mul)) return .{ .k = 0 };
return .bot;
}
if (l == .top or r == .top) return .top;
const x = bitsOf(l.k, w);
const y = bitsOf(r.k, w);
const sx = stored(x, w);
const sy = stored(y, w);
const p: u64 = switch (b.op) {
.add => x +% y,
.sub => x -% y,
.mul => x *% y,
.@"and" => x & y,
.@"or" => x | y,
.xor => x ^ y,
.shl => if (y < w) x << @intCast(y) else return .bot,
.lshr => if (y < w) x >> @intCast(y) else return .bot,
.ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return .bot,
.udiv => if (y != 0) x / y else return .bot,
.urem => if (y != 0) x % y else return .bot,
.sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return .bot,
.srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return .bot,
};
return .{ .k = stored(bitsOf(@bitCast(p), w), w) };
},
.cast => |c| {
if (c.op != .zext and c.op != .sext and c.op != .trunc) return .bot;
const from = intWidth(s.m, typeOf(s.m, s.f, c.val) orelse return .bot) orelse return .bot;
const v = s.of(c.val);
if (v != .k) return v;
const x = bitsOf(v.k, from);
const out: u64 = switch (c.op) {
.sext => if (from == 1) (if (x & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(stored(x, from)),
else => x,
};
return .{ .k = stored(bitsOf(@bitCast(out), w), w) };
},
.cmp => |c| {
if (c.pred < 32 or c.pred > 41) return .bot;
const cw = intWidth(s.m, typeOf(s.m, s.f, c.lhs) orelse return .bot) orelse return .bot;
const l = s.of(c.lhs);
const r = s.of(c.rhs);
if (l == .bot or r == .bot) return .bot;
if (l == .top or r == .top) return .top;
const x = bitsOf(l.k, cw);
const y = bitsOf(r.k, cw);
const sx = stored(x, cw);
const sy = stored(y, cw);
const t = switch (c.pred) {
32 => x == y,
33 => x != y,
34 => x > y,
35 => x >= y,
36 => x < y,
37 => x <= y,
38 => sx > sy,
39 => sx >= sy,
40 => sx < sy,
else => sx <= sy,
};
return .{ .k = @intFromBool(t) };
},
.select => |sel| {
const c = s.of(sel.cond);
return switch (c) {
.top => .top,
.k => |x| s.of(if (x & 1 != 0) sel.t else sel.f),
.bot => s.of(sel.t).meet(s.of(sel.f)),
};
},
else => return .bot,
}
}
};
const ev: Eval = .{ .m = m, .f = f, .lat = lat };
// Blocks in reverse postorder: definitions before uses except round
// loops, so the fixed point takes a few passes (the lattice is three
// levels deep).
var rpo: std.ArrayList(u32) = .empty;
{
var post: std.ArrayList(u32) = .empty;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Fr = struct { b: u32, next: u32 };
var stack: std.ArrayList(Fr) = .empty;
try stack.append(a, .{ .b = 0, .next = 0 });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
const succs = successors(insts[block_start[top.b + 1] - 1]);
if (top.next < succs.len) {
const t = succs.get(top.next);
top.next += 1;
if (!seen[t]) {
seen[t] = true;
try stack.append(a, .{ .b = t, .next = 0 });
}
} else {
try post.append(a, top.b);
_ = stack.pop();
}
}
var k = post.items.len;
while (k > 0) {
k -= 1;
try rpo.append(a, post.items[k]);
}
}
var changed = true;
var rounds: u32 = 0;
while (changed) : (rounds += 1) {
if (rounds > 1000) return false;
changed = false;
for (rpo.items) |b| {
if (!exec[b]) continue;
for (block_start[b]..block_start[b + 1]) |ii| {
const i: u32 = @intCast(ii);
const inst = insts[i];
var new: Lat = undefined;
switch (inst.op) {
.phi => |p| {
if (intWidth(m, inst.ty) == null) {
new = .bot;
} else {
new = .top;
for (p.incoming) |in| {
if (!edges.contains(S.key(in.block, b))) continue;
new = new.meet(ev.of(in.val));
}
}
},
.br => |br| {
const targets: [2]?u32 = if (br.cond) |c| switch (ev.of(c)) {
.top => .{ null, null },
.k => |x| .{ if (x & 1 != 0) br.then else br.@"else", null },
.bot => .{ br.then, br.@"else" },
} else .{ br.then, null };
for (targets) |t| if (t) |tb| {
const gop = try edges.getOrPut(a, S.key(b, tb));
if (!gop.found_existing) {
exec[tb] = true;
changed = true;
}
};
continue;
},
.@"switch" => |sw| {
const c = ev.of(sw.cond);
if (c == .top) continue;
var taken: ?u32 = null;
if (c == .k) {
taken = sw.default;
for (sw.cases) |cs| if (ev.of(cs.val) == .k and ev.of(cs.val).k == c.k) {
taken = cs.block;
};
}
var list: std.ArrayList(u32) = .empty;
if (taken) |t| try list.append(a, t) else {
try list.append(a, sw.default);
for (sw.cases) |cs| try list.append(a, cs.block);
}
for (list.items) |tb| {
const gop = try edges.getOrPut(a, S.key(b, tb));
if (!gop.found_existing) {
exec[tb] = true;
changed = true;
}
}
continue;
},
else => new = ev.inst(i),
}
const merged = lat[i].meet(new);
if (!merged.eql(lat[i])) {
lat[i] = merged;
changed = true;
}
}
}
}
// Constants into the function: the uses of integer values found
// constant, and branch conditions.
const repl = try a.alloc(?Value, n);
@memset(repl, null);
var any = false;
for (insts, 0..) |inst, i| {
if (!exec[block_of[i]]) continue;
if (lat[i] != .k) continue;
if (intWidth(m, inst.ty) == null) continue;
repl[i] = try m.constant(.{ .ty = inst.ty, .kind = .{ .int = lat[i].k } });
}
const Mapper = struct {
repl: []const ?Value,
any: *bool,
pub fn visit(c: *@This(), v: Value, _: anytype) Value {
if (v == .inst and v.inst < c.repl.len) if (c.repl[v.inst]) |r| {
c.any.* = true;
return r;
};
return v;
}
};
var mapper: Mapper = .{ .repl = repl, .any = &any };
const ma = m.allocator();
for (insts) |*inst| try unroll.operandsMap(ma, inst, &mapper);
return any;
}

View File

@ -71,8 +71,16 @@ pub const ComputeInfo = struct {
num_threads: [3]u32,
};
/// Validator version we claim in !dx.valver (matches the oracle dxc).
const valver = .{ 1, 11 };
/// The validator version zdxc writes for (!dx.valver; matches the oracle
/// dxc). What its output looks like follows from it: PSVRuntimeInfo4 and
/// RDAT's RuntimeDataFunctionInfo3 from 1.10. Testing with an older
/// validator means changing only this.
pub const validator: [2]u32 = .{ 1, 11 };
/// Whether the validator is at least `major.minor`.
pub fn validatorAtLeast(major: u32, minor: u32) bool {
return validator[0] > major or (validator[0] == major and validator[1] >= minor);
}
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
var m = Module.init(gpa);
@ -86,7 +94,7 @@ pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
// Metadata, in the same shape dxc emits.
const ident = try m.mdNode(&.{try m.mdString("zdxc 0.0.0")});
const version = try m.mdNode(&.{ try m.mdI32(1), try m.mdI32(info.profile.minor) });
const val_ver = try m.mdNode(&.{ try m.mdI32(valver[0]), try m.mdI32(valver[1]) });
const val_ver = try m.mdNode(&.{ try m.mdI32(validator[0]), try m.mdI32(validator[1]) });
const sm = try m.mdNode(&.{ try m.mdString(info.profile.kind.profilePrefix()), try m.mdI32(info.profile.major), try m.mdI32(info.profile.minor) });
const threads = try m.mdNode(&.{ try m.mdI32(info.num_threads[0]), try m.mdI32(info.num_threads[1]), try m.mdI32(info.num_threads[2]) });
const props = try m.mdNode(&.{ try m.mdI32(4), threads }); // kDxilNumThreadsTag
@ -143,6 +151,8 @@ pub const PsvInfo = struct {
/// The stage-specific PSVRuntimeInfo0 union.
stage_info: [16]u8 = @splat(0),
num_threads: [3]u32 = .{ 0, 0, 0 },
/// Minimum and maximum expected wave lane counts (WaveSize).
wave_lanes: [2]u32 = .{ 0, 0xFFFFFFFF },
resources: []const ResourceBind = &.{},
inputs: []const signature.Element = &.{},
outputs: []const signature.Element = &.{},
@ -159,7 +169,7 @@ pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resour
return psv(gpa, .{ .kind = .compute, .entry = entry, .num_threads = num_threads, .resources = resources });
}
/// PSV0 with PSVRuntimeInfo4 (60 bytes), as produced for validator 1.11.
/// PSV0 with PSVRuntimeInfo4 (60 bytes; validator 1.10+) or 3 (52).
pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(gpa);
@ -169,11 +179,12 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s));
const pc_vectors = signature.vectorsUsed(info.patch_constants, 0);
try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4)
const info4 = validatorAtLeast(1, 10);
try w(&buf, gpa, if (info4) 60 else 52); // sizeof(PSVRuntimeInfo4 / 3)
// PSVRuntimeInfo0
try buf.appendSlice(gpa, &info.stage_info);
try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount
try w(&buf, gpa, info.wave_lanes[0]); // MinimumExpectedWaveLaneCount
try w(&buf, gpa, info.wave_lanes[1]); // MaximumExpectedWaveLaneCount
// PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
// vector counts.
// (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
@ -221,7 +232,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
try w(&records, gpa, idx_off);
var cols_and_start: u8 = @intCast(e.cols);
if (e.start_row != null) cols_and_start |= 0x40 | @as(u8, @intCast(e.start_col << 4));
try records.appendSlice(gpa, &.{ @intCast(e.rows), @intCast(e.start_row orelse 0), cols_and_start, @intFromEnum(e.kind), @intCast(e.comp.sigCompType()), @intFromEnum(e.interp), @intCast((e.stream & 3) << 4), 0 });
try records.appendSlice(gpa, &.{ @intCast(e.rows), @intCast(e.start_row orelse 0), cols_and_start, @backingInt(e.kind), @intCast(e.comp.sigCompType()), @backingInt(e.interp), @intCast((e.stream & 3) << 4), 0 });
};
const entry_off: u32 = @intCast(strings.items.len);
try strings.appendSlice(gpa, info.entry);
@ -230,9 +241,11 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// PSVRuntimeInfo3: EntryFunctionName
try w(&buf, gpa, entry_off);
if (info4) {
// PSVRuntimeInfo4
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
}
try w(&buf, gpa, @intCast(info.resources.len));
if (info.resources.len > 0) {

View File

@ -60,14 +60,14 @@ const sv_names = [_][]const u8{
pub fn kindByName(name: []const u8) SemanticKind {
if (!std.ascii.startsWithIgnoreCase(name, "SV_")) return .arbitrary;
for (sv_names[1..], 1..) |n, i| {
if (std.ascii.eqlIgnoreCase(name, n)) return @enumFromInt(i);
if (std.ascii.eqlIgnoreCase(name, n)) return @fromBackingInt(@intCast(i));
}
return .invalid;
}
/// The canonical spelling of a system-value semantic.
pub fn canonicalName(kind: SemanticKind) []const u8 {
return sv_names[@intFromEnum(kind)];
return sv_names[@backingInt(kind)];
}
pub const Interpretation = enum(u8) { na, sv, sgv, arb, not_in_sig, not_packed, target, tess_factor, shadow, clip_cull };
@ -150,7 +150,7 @@ pub fn interpretation(kind: SemanticKind, sp: SigPoint, minor: u8) Interpretatio
.start_vertex_location, .start_instance_location => if (minor >= 8) .{ nis, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na } else @splat(na),
else => @splat(na),
};
return row[@intFromEnum(sp)];
return row[@backingInt(sp)];
}
pub fn shouldBeAllocated(i: Interpretation) bool {
@ -553,6 +553,15 @@ fn systemValue(kind: SemanticKind, domain: Domain) u32 {
/// A DxilProgramSignature part (ISG1 or OSG1) for elements in the
/// signature (not NotInSig ones).
pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain) Allocator.Error![]u8 {
return signaturePart(gpa, elements, is_input, domain, true);
}
/// The same records in declaration order, as reflection lists parameters.
pub fn declarationOrderSignature(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain) Allocator.Error![]u8 {
return signaturePart(gpa, elements, is_input, domain, false);
}
fn signaturePart(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain, sorted: bool) Allocator.Error![]u8 {
const Rec = struct { stream: u32, name: u32, index: u32, sv: u32, comp: u32, reg: u32, mask: u8, rw: u8, min_prec: u32 };
var recs: std.ArrayList(Rec) = .empty;
defer recs.deinit(gpa);
@ -584,7 +593,7 @@ pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: boo
if (sv == 16) sv = 15; // isoline: density, then detail
}
}
std.sort.insertion(Rec, recs.items, {}, struct {
if (sorted) std.sort.insertion(Rec, recs.items, {}, struct {
fn lt(_: void, a: Rec, b: Rec) bool {
if (a.stream != b.stream) return a.stream < b.stream;
if (a.reg != b.reg) return a.reg < b.reg;

854
src/dxil/unroll.zig Normal file
View File

@ -0,0 +1,854 @@
//! Full unrolling of loops with a constant trip count, on a DXIL function
//! after promotion to SSA values (as dxc's loop unrolling runs after SROA):
//! by then a loop's bound often comes from struct fields and arguments
//! only inlining made constant. Unrolled, indices into local arrays become
//! constants (so promotion can take the arrays out of memory) and code
//! guarded by the counter folds away, as it does for dxc.
//!
//! A loop qualifies when it is innermost, has one block leaving it (a
//! conditional branch out of the loop, to one block), and that branch's
//! condition is decided by header phis that start constant and step by
//! values computed from themselves. Its blocks are copied once per
//! iteration, and once more up to the exit, after the function's last
//! block; the original blocks are left unreachable for promotion to drop.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const stats = @import("../stats.zig");
const promote = @import("promote.zig");
const Value = module.Value;
const Inst = module.Inst;
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
const none = std.math.maxInt(u32);
/// Most iterations unrolled, most instructions one loop may grow to
/// unrolled (small loops only, as dxc's full unrolling of loops without
/// [unroll]: larger ones cost compile time and code size for little), and
/// most one function may grow by.
const max_trips = 256;
const max_loop_growth = 300;
const max_growth = 65536;
/// For `[unroll]` loops: dxc's limit on their iterations (its
/// DxilLoopUnroll), and no limit on their size but the function's.
const max_marked_trips = 1024;
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.unroll);
defer zone.end();
var budget: usize = max_growth;
var tried: std.AutoHashMapUnmanaged(u32, void) = .empty;
var any = false;
while (try unrollOne(a, m, func, &budget, &tried)) any = true;
return any;
}
const Cfg = struct {
nb: u32,
block_start: []u32,
succs: [][]u32,
preds: [][]u32,
idom: []u32,
/// Each reachable block's interval in a depth-first walk of the
/// dominator tree (`none` for unreachable blocks): `d` dominates `b`
/// when `b`'s interval is inside `d`'s.
dom_pre: []u32,
dom_post: []u32,
fn dominates(c: *const Cfg, d: u32, b: u32) bool {
if (d == b) return true;
if (c.dom_pre[d] == none or c.dom_pre[b] == none) return false;
return c.dom_pre[d] <= c.dom_pre[b] and c.dom_post[b] <= c.dom_post[d];
}
};
/// Numbers the dominator tree's blocks in and out of a depth-first walk.
fn domIntervals(a: Allocator, idom: []const u32) Allocator.Error!struct { []u32, []u32 } {
const nb = idom.len;
// Children lists, packed: block b's are kids[first[b]..first[b + 1]].
const first = try a.alloc(u32, nb + 1);
@memset(first, 0);
for (idom, 0..) |p, b| if (p != none and p != b) {
first[p + 1] += 1;
};
for (1..nb + 1) |k| first[k] += first[k - 1];
const fill = try a.dupe(u32, first[0..nb]);
const kids = try a.alloc(u32, first[nb]);
for (idom, 0..) |p, b| if (p != none and p != b) {
kids[fill[p]] = @intCast(b);
fill[p] += 1;
};
const pre = try a.alloc(u32, nb);
const post = try a.alloc(u32, nb);
@memset(pre, none);
@memset(post, none);
if (nb == 0) return .{ pre, post };
var clock: u32 = 0;
// `next` reuses fill: the next child to visit.
@memcpy(fill, first[0..nb]);
var stack: std.ArrayList(u32) = .empty;
try stack.append(a, 0);
pre[0] = clock;
clock += 1;
while (stack.items.len > 0) {
const b = stack.items[stack.items.len - 1];
if (fill[b] < first[b + 1]) {
const k = kids[fill[b]];
fill[b] += 1;
pre[k] = clock;
clock += 1;
try stack.append(a, k);
} else {
post[b] = clock;
clock += 1;
_ = stack.pop();
}
}
return .{ pre, post };
}
/// A loop's blocks: a bit per block of the function, and the list in
/// block order.
const Body = struct {
bits: []u64,
blocks: []const u32,
fn has(b: Body, x: u32) bool {
return b.bits[x >> 6] >> @intCast(x & 63) & 1 != 0;
}
fn add(b: *Body, x: u32) void {
b.bits[x >> 6] |= @as(u64, 1) << @intCast(x & 63);
}
};
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
const nb = f.num_blocks;
const insts = f.insts.items;
const block_start = try a.alloc(u32, nb + 1);
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| {
if (b >= nb) return null;
if (isTerminator(inst)) {
b += 1;
block_start[b] = @intCast(i + 1);
}
}
if (b != nb) return null;
// Successors (each once) and predecessors, packed: each block's are a
// slice of one array.
var succ_flat: std.ArrayList(u32) = .empty;
try succ_flat.ensureTotalCapacity(a, 2 * nb);
const succ_off = try a.alloc(u32, nb + 1);
for (0..nb) |bi| {
const start = succ_flat.items.len;
succ_off[bi] = @intCast(start);
switch (insts[block_start[bi + 1] - 1].op) {
.br => |br| {
try succ_flat.append(a, br.then);
if (br.@"else") |e| if (e != br.then) try succ_flat.append(a, e);
},
.@"switch" => |sw| {
try succ_flat.append(a, sw.default);
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, succ_flat.items[start..], c.block) == null) try succ_flat.append(a, c.block);
},
else => {},
}
}
succ_off[nb] = @intCast(succ_flat.items.len);
const succs = try a.alloc([]u32, nb);
for (succs, 0..) |*sl, bi| sl.* = succ_flat.items[succ_off[bi]..succ_off[bi + 1]];
const pred_off = try a.alloc(u32, nb + 1);
@memset(pred_off, 0);
for (succ_flat.items) |t| pred_off[t + 1] += 1;
for (1..nb + 1) |k| pred_off[k] += pred_off[k - 1];
const pred_flat = try a.alloc(u32, succ_flat.items.len);
{
const fill = try a.dupe(u32, pred_off[0..nb]);
for (0..nb) |bi| for (succs[bi]) |t| {
pred_flat[fill[t]] = @intCast(bi);
fill[t] += 1;
};
}
const preds = try a.alloc([]u32, nb);
for (preds, 0..) |*pl, bi| pl.* = pred_flat[pred_off[bi]..pred_off[bi + 1]];
// Reverse postorder, then Cooper, Harvey and Kennedy's dominators.
const order = try a.alloc(u32, nb);
@memset(order, none);
var rpo: std.ArrayList(u32) = .empty;
{
var post: std.ArrayList(u32) = .empty;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Fr = struct { b: u32, next: u32 };
var stack: std.ArrayList(Fr) = .empty;
try stack.append(a, .{ .b = 0, .next = 0 });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (top.next < succs[top.b].len) {
const s = succs[top.b][top.next];
top.next += 1;
if (!seen[s]) {
seen[s] = true;
try stack.append(a, .{ .b = s, .next = 0 });
}
} else {
try post.append(a, top.b);
_ = stack.pop();
}
}
var k = post.items.len;
while (k > 0) {
k -= 1;
order[post.items[k]] = @intCast(rpo.items.len);
try rpo.append(a, post.items[k]);
}
}
const idom = try a.alloc(u32, nb);
@memset(idom, none);
idom[0] = 0;
var changed = true;
while (changed) {
changed = false;
for (rpo.items[1..]) |bb| {
var new: u32 = none;
for (preds[bb]) |p| {
if (idom[p] == none) continue;
if (new == none) {
new = p;
continue;
}
var x = p;
var y = new;
while (x != y) {
while (order[x] > order[y]) x = idom[x];
while (order[y] > order[x]) y = idom[y];
}
new = x;
}
if (new != none and idom[bb] != new) {
idom[bb] = new;
changed = true;
}
}
}
const pre, const post = try domIntervals(a, idom);
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom, .dom_pre = pre, .dom_post = post };
}
fn constInt(m: *const module.Module, v: Value) ?i64 {
if (v != .constant) return null;
return switch (m.constants.items[v.constant].kind) {
.int => |x| x,
else => null,
};
}
fn intWidth(m: *const module.Module, ty: module.TypeId) ?u32 {
return switch (m.types.items[ty]) {
.int => |w| w,
else => null,
};
}
fn bitsOf(v: i64, w: u32) u64 {
const u: u64 = @bitCast(v);
return if (w >= 64) u else u & ((@as(u64, 1) << @intCast(w)) - 1);
}
/// A `w`-bit pattern as constants hold it: 0 / 1 for i1, sign-extended
/// above.
fn stored(p: u64, w: u32) i64 {
if (w == 1) return @intCast(p & 1);
if (w >= 64) return @bitCast(p);
const sh: u6 = @intCast(64 - w);
return @as(i64, @bitCast(p << sh)) >> sh;
}
/// Integer value of `v` given the header phis' values in `state` (index:
/// instruction), or null.
fn eval(m: *const module.Module, f: *const module.Function, state: *const std.AutoHashMapUnmanaged(u32, i64), v: Value, depth: u32) ?i64 {
if (depth > 64) return null;
if (constInt(m, v)) |c| return c;
if (v != .inst) return null;
if (state.get(v.inst)) |s| return s;
const inst = f.insts.items[v.inst];
const w = intWidth(m, inst.ty) orelse return null;
switch (inst.op) {
.binop => |b| {
const x = bitsOf(eval(m, f, state, b.lhs, depth + 1) orelse return null, w);
const y = bitsOf(eval(m, f, state, b.rhs, depth + 1) orelse return null, w);
const sx = stored(x, w);
const sy = stored(y, w);
const p: u64 = switch (b.op) {
.add => x +% y,
.sub => x -% y,
.mul => x *% y,
.@"and" => x & y,
.@"or" => x | y,
.xor => x ^ y,
.shl => if (y < w) x << @intCast(y) else return null,
.lshr => if (y < w) x >> @intCast(y) else return null,
.ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return null,
.udiv => if (y != 0) x / y else return null,
.urem => if (y != 0) x % y else return null,
.sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return null,
.srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return null,
};
return stored(bitsOf(@bitCast(p), w), w);
},
.cast => |c| {
const from = intWidth(m, typeOf(m, f, c.val) orelse return null) orelse return null;
const x = bitsOf(eval(m, f, state, c.val, depth + 1) orelse return null, from);
const out: u64 = switch (c.op) {
.zext, .trunc => x,
.sext => if (from == 1) (if (x & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(stored(x, from)),
else => return null,
};
return stored(bitsOf(@bitCast(out), w), w);
},
.cmp => |c| {
if (c.pred < 32 or c.pred > 41) return null;
const cw = intWidth(m, typeOf(m, f, c.lhs) orelse return null) orelse return null;
const x = bitsOf(eval(m, f, state, c.lhs, depth + 1) orelse return null, cw);
const y = bitsOf(eval(m, f, state, c.rhs, depth + 1) orelse return null, cw);
const sx = stored(x, cw);
const sy = stored(y, cw);
const t = switch (c.pred) {
32 => x == y,
33 => x != y,
34 => x > y,
35 => x >= y,
36 => x < y,
37 => x <= y,
38 => sx > sy,
39 => sx >= sy,
40 => sx < sy,
else => sx <= sy,
};
return @intFromBool(t);
},
.select => |s| {
const c = eval(m, f, state, s.cond, depth + 1) orelse return null;
return eval(m, f, state, if (c & 1 != 0) s.t else s.f, depth + 1);
},
else => return null,
}
}
fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) ?module.TypeId {
return switch (v) {
.inst => |i| f.insts.items[i].ty,
.constant => |c| m.constants.items[c].ty,
.arg => |k| m.types.items[f.ty].function.params[k],
else => null,
};
}
fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried: *std.AutoHashMapUnmanaged(u32, void)) Allocator.Error!bool {
const f = &m.functions.items[func];
const cfg = (try buildCfg(a, f)) orelse return false;
const nb = cfg.nb;
const insts = f.insts.items;
// Loops: headers with back edges (from blocks they dominate), and
// their blocks.
const Loop = struct { h: u32, body: Body, latches: []u32 };
var loops: std.ArrayList(Loop) = .empty;
for (0..nb) |hb| {
const h: u32 = @intCast(hb);
if (cfg.idom[h] == none) continue;
var latches: std.ArrayList(u32) = .empty;
for (cfg.preds[h]) |p| if (cfg.idom[p] != none and cfg.dominates(h, p)) try latches.append(a, p);
if (latches.items.len == 0) continue;
const bits = try a.alloc(u64, (nb + 63) / 64);
@memset(bits, 0);
var body: Body = .{ .bits = bits, .blocks = &.{} };
body.add(h);
var count: usize = 1;
var stack: std.ArrayList(u32) = .empty;
try stack.appendSlice(a, latches.items);
while (stack.pop()) |x| {
if (body.has(x)) continue;
body.add(x);
count += 1;
for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p);
}
// The blocks in order, from the bits.
const blocks = try a.alloc(u32, count);
var k: usize = 0;
for (bits, 0..) |word, wi| {
var w = word;
while (w != 0) : (w &= w - 1) {
blocks[k] = @intCast(wi * 64 + @ctz(w));
k += 1;
}
}
body.blocks = blocks;
try loops.append(a, .{ .h = h, .body = body, .latches = latches.items });
}
// Loops that do nothing (as dxc's loop deletion removes them): no
// instruction with an effect, one block they leave to, and nothing
// after them reading their values. Their preheader goes straight to
// that block; their blocks are left unreachable for promotion to drop.
// (Nested ones too: an outer loop whose inner loops do nothing.)
const loop_inst = try a.alloc(bool, insts.len);
@memset(loop_inst, false);
// (The loop whose instructions loop_inst marks, cleared for the next.)
var marked: ?Body = null;
dead: for (loops.items) |lp| {
if (marked) |mk| for (mk.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], false);
marked = null;
var exit: u32 = none;
for (lp.body.blocks) |bb| {
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) {
.br, .@"switch" => {},
.ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead,
.call => |c| switch (m.functions.items[c.callee].attrs) {
.nounwind_readnone, .nounwind_readonly => {},
else => if (!promote.isWaveOp(m.functions.items[c.callee].name)) continue :dead,
},
else => {},
};
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
if (exit != none and exit != s) continue :dead;
exit = s;
};
}
if (exit == none) continue;
var pre: u32 = none;
for (cfg.preds[lp.h]) |p| if (!lp.body.has(p)) {
if (pre != none) continue :dead;
pre = p;
};
if (pre == none) continue;
const pterm = &insts[cfg.block_start[pre + 1] - 1];
if (pterm.op != .br) continue;
if (pterm.op.br.then == exit or pterm.op.br.@"else" == exit) continue;
for (lp.body.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], true);
marked = lp.body;
// The exit's phis: one value from the loop, from before it.
const phi_end = blk: {
var i = cfg.block_start[exit];
while (insts[i].op == .phi) i += 1;
break :blk i;
};
const from_loop = try a.alloc(?Value, phi_end - cfg.block_start[exit]);
for (cfg.block_start[exit]..phi_end, from_loop) |i, *fl| {
fl.* = null;
for (insts[i].op.phi.incoming) |in| if (lp.body.has(in.block)) {
if (in.val == .inst and loop_inst[in.val.inst]) continue :dead;
if (fl.* != null and !std.meta.eql(fl.*.?, in.val)) continue :dead;
fl.* = in.val;
};
}
// Nothing else outside reads the loop's values.
const Check = struct {
loop_inst: []const bool,
used: bool = false,
pub fn visit(c: *@This(), v: Value, _: anytype) Value {
if (v == .inst and v.inst < c.loop_inst.len and c.loop_inst[v.inst]) c.used = true;
return v;
}
};
var check: Check = .{ .loop_inst = loop_inst };
for (0..nb) |bb| {
if (lp.body.has(@intCast(bb))) continue;
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
if (bb == exit and i < phi_end) continue;
var copy = insts[i];
try operandsMap(a, &copy, &check);
}
}
if (check.used) continue;
const ma = m.allocator();
for (cfg.block_start[exit]..phi_end, from_loop) |i, fl| {
var edges: std.ArrayList(Edge) = .empty;
for (insts[i].op.phi.incoming) |in| if (!lp.body.has(in.block)) try edges.append(ma, in);
if (fl) |v| try edges.append(ma, .{ .val = v, .block = pre });
insts[i].op.phi.incoming = edges.items;
}
if (pterm.op.br.then == lp.h) pterm.op.br.then = exit;
if (pterm.op.br.@"else") |*e| if (e.* == lp.h) {
e.* = exit;
};
for (lp.body.blocks) |bb| insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
return true;
}
candidates: for (loops.items) |lp| {
const h = lp.h;
if (tried.contains(h)) continue;
// Innermost: no other loop's header inside.
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
try tried.put(a, h, {});
// `[unroll]` (its back edge marked by the emitter).
const marked_loop = for (lp.latches) |l| {
if (insts[cfg.block_start[l + 1] - 1].md == .unroll) break true;
} else false;
// One way out: a conditional branch from one block, to one block.
var exiting: u32 = none;
var exit: u32 = none;
var size: usize = 0;
var body_blocks: std.ArrayList(u32) = .empty;
for (lp.body.blocks) |bb| {
try body_blocks.append(a, bb);
size += cfg.block_start[bb + 1] - cfg.block_start[bb];
const term = insts[cfg.block_start[bb + 1] - 1].op;
if (term == .@"switch") {
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) continue :candidates;
}
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
if (exiting != none) continue :candidates;
exiting = bb;
exit = s;
};
}
if (exiting == none) continue;
const xterm = insts[cfg.block_start[exiting + 1] - 1].op;
if (xterm != .br or xterm.br.@"else" == null) continue;
const stay = if (xterm.br.then == exit) xterm.br.@"else".? else xterm.br.then;
if (!lp.body.has(stay) or stay == exit) continue;
for (lp.latches) |l| if (!cfg.dominates(exiting, l)) continue :candidates;
// One way in.
var pre: u32 = none;
for (cfg.preds[h]) |p| if (!lp.body.has(p)) {
if (pre != none) continue :candidates;
pre = p;
};
if (pre == none) continue;
// The header's phis: the integer ones whose values can be followed.
var phis: std.ArrayList(u32) = .empty;
{
var i = cfg.block_start[h];
while (insts[i].op == .phi) : (i += 1) try phis.append(a, i);
}
var state: std.AutoHashMapUnmanaged(u32, i64) = .empty;
for (phis.items) |pi| {
if (intWidth(m, insts[pi].ty) == null) continue;
for (insts[pi].op.phi.incoming) |in| if (in.block == pre) {
if (constInt(m, in.val)) |c| try state.put(a, pi, c);
};
}
const xcond = xterm.br.cond.?;
const stay_on: i64 = if (xterm.br.then == stay) 1 else 0;
var states: std.ArrayList(std.AutoHashMapUnmanaged(u32, i64)) = .empty;
while (true) {
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
if ((c & 1) != stay_on) break;
if (states.items.len >= @as(usize, if (marked_loop) max_marked_trips else max_trips)) continue :candidates;
try states.append(a, try state.clone(a));
// Next values: what every latch passes back (the same).
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
for (phis.items) |pi| {
if (!state.contains(pi)) continue;
var val: ?i64 = null;
var ok = true;
for (insts[pi].op.phi.incoming) |in| {
if (in.block == pre) continue;
const v = eval(m, f, &state, in.val, 0) orelse {
ok = false;
break;
};
if (val != null and val.? != v) ok = false;
val = v;
}
if (ok) if (val) |v| try next.put(a, pi, v);
}
state = next;
}
const trips = states.items.len;
const growth = (trips + 1) * size;
if ((!marked_loop and growth > max_loop_growth) or growth > budget.*) continue;
budget.* -= growth;
try states.append(a, state); // the last pass, up to the exit
// Copies: block `body_blocks[j]` of copy `k` is block
// `nb + k * nbody + j`.
const nbody: u32 = @intCast(body_blocks.items.len);
const index_in = try a.alloc(u32, nb);
@memset(index_in, none);
for (body_blocks.items, 0..) |bb, j| index_in[bb] = @intCast(j);
const n0: u32 = @intCast(insts.len);
const copies: u32 = @intCast(trips + 1);
// Value maps per copy (original instruction -> value).
const maps = try a.alloc(std.AutoHashMapUnmanaged(u32, Value), copies);
for (maps) |*mp| mp.* = .empty;
const S = struct {
fn block(nb_: u32, nbody_: u32, idx: []const u32, k: u32, b: u32) u32 {
return nb_ + k * nbody_ + idx[b];
}
};
var out: std.ArrayList(Inst) = .empty;
const ma = m.allocator();
// New instruction indices come after the existing ones.
var next_index: u32 = n0;
// First pass: give every copied instruction its index (phis of
// later copies refer back, latch values refer forward to the next
// copy's header).
const new_index = try a.alloc([]u32, copies);
for (0..copies) |k| {
new_index[k] = try a.alloc(u32, n0);
@memset(new_index[k], none);
for (body_blocks.items) |bb| {
var i = cfg.block_start[bb];
while (i < cfg.block_start[bb + 1]) : (i += 1) {
new_index[k][i] = next_index;
next_index += 1;
}
}
}
// Header phis: a constant where followed, else the value from the
// copy before (or from the preheader).
for (0..copies) |k| {
for (phis.items) |pi| {
if (states.items[k].get(pi)) |c| {
try maps[k].put(a, pi, try m.constant(.{ .ty = insts[pi].ty, .kind = .{ .int = c } }));
continue;
}
if (k == 0) {
for (insts[pi].op.phi.incoming) |in| if (in.block == pre) try maps[0].put(a, pi, in.val);
}
}
}
const Mapper = struct {
maps: []std.AutoHashMapUnmanaged(u32, Value),
new_index: [][]u32,
k: u32,
fn val(c: @This(), v: Value) Value {
if (v != .inst) return v;
if (c.maps[c.k].get(v.inst)) |x| return x;
if (v.inst < c.new_index[c.k].len and c.new_index[c.k][v.inst] != none) return .{ .inst = c.new_index[c.k][v.inst] };
return v;
}
fn visit(c: *@This(), v: Value, _: anytype) Value {
return c.val(v);
}
};
for (0..copies) |kk| {
const k: u32 = @intCast(kk);
for (body_blocks.items) |bb| {
var i = cfg.block_start[bb];
while (i < cfg.block_start[bb + 1]) : (i += 1) {
var inst = insts[i];
var mapper: Mapper = .{ .maps = maps, .new_index = new_index, .k = k };
if (bb == h and inst.op == .phi) {
if (maps[k].get(i)) |v| {
// Folded away: a phi of that value on every
// edge keeps the numbering (promotion drops it).
var edges: std.ArrayList(Edge) = .empty;
if (k == 0) {
try edges.append(ma, .{ .val = v, .block = pre });
} else for (lp.latches) |l| try edges.append(ma, .{ .val = v, .block = S.block(nb, nbody, index_in, k - 1, l) });
try out.append(ma, .{ .ty = inst.ty, .op = .{ .phi = .{ .incoming = edges.items } } });
continue;
}
// From the latches of the copy before.
var edges: std.ArrayList(Edge) = .empty;
for (inst.op.phi.incoming) |in| {
if (in.block == pre or k == 0) continue;
const prev: Mapper = .{ .maps = maps, .new_index = new_index, .k = k - 1 };
try edges.append(ma, .{ .val = prev.val(in.val), .block = S.block(nb, nbody, index_in, k - 1, in.block) });
}
if (k == 0) {
// (Not followed and no preheader value mapped:
// the preheader's incoming.)
for (inst.op.phi.incoming) |in| if (in.block == pre) try edges.append(ma, .{ .val = in.val, .block = pre });
}
try out.append(ma, .{ .ty = inst.ty, .op = .{ .phi = .{ .incoming = edges.items } } });
continue;
}
if (inst.op == .phi) {
const edges = try ma.alloc(Edge, inst.op.phi.incoming.len);
for (inst.op.phi.incoming, edges) |in, *e| e.* = .{ .val = mapper.val(in.val), .block = if (index_in[in.block] != none) S.block(nb, nbody, index_in, k, in.block) else in.block };
inst.op = .{ .phi = .{ .incoming = edges } };
try out.append(ma, inst);
continue;
}
try operandsMap(ma, &inst, &mapper);
// Branches: within the copy; back to the header: the
// next copy; out of the exiting block: per copy.
switch (inst.op) {
.br => |*br| {
if (bb == exiting) {
const target = if (k + 1 < copies) stay else exit;
const tb = if (target == exit) exit else S.block(nb, nbody, index_in, k, target);
br.* = .{ .then = tb };
} else {
br.then = mapBlock(br.then, h, k, copies, nb, nbody, index_in);
if (br.@"else") |*e| e.* = mapBlock(e.*, h, k, copies, nb, nbody, index_in);
}
},
.@"switch" => |*sw| {
sw.default = mapBlock(sw.default, h, k, copies, nb, nbody, index_in);
const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = mapBlock(c.block, h, k, copies, nb, nbody, index_in) };
sw.cases = cs;
},
else => {},
}
// Integer values the counter decides: constants.
if (inst.op == .binop or inst.op == .cast or inst.op == .cmp or inst.op == .select) {
if (eval(m, f, &states.items[k], .{ .inst = i }, 0)) |c| {
if (intWidth(m, inst.ty) != null) try maps[k].put(a, i, try m.constant(.{ .ty = inst.ty, .kind = .{ .int = c } }));
}
}
try out.append(ma, inst);
}
}
}
// The preheader enters the first copy; the exit's phis and the
// code after the loop see the last copy's values.
const last: Mapper = .{ .maps = maps, .new_index = new_index, .k = copies - 1 };
const in_body = try a.alloc(bool, n0);
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
in_body[i] = lp.body.has(@intCast(bb));
};
const Outside = struct {
last: Mapper,
in_body: []const bool,
fn visit(c: *@This(), v: Value, _: anytype) Value {
if (v == .inst and v.inst < c.in_body.len and c.in_body[v.inst]) return c.last.val(v);
return v;
}
};
var outside: Outside = .{ .last = last, .in_body = in_body };
for (0..nb) |bb| {
if (lp.body.has(@intCast(bb))) {
// The originals: unreachable now.
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
continue;
}
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
var inst = &insts[i];
if (inst.op == .phi) {
const edges = try ma.alloc(Edge, inst.op.phi.incoming.len);
for (inst.op.phi.incoming, edges) |in, *e| e.* = .{
.val = outside.visit(in.val, {}),
.block = if (in.block == exiting and bb == exit) S.block(nb, nbody, index_in, copies - 1, exiting) else in.block,
};
inst.op = .{ .phi = .{ .incoming = edges } };
continue;
}
try operandsMap(ma, inst, &outside);
if (bb == pre) switch (inst.op) {
.br => |*br| {
if (br.then == h) br.then = S.block(nb, nbody, index_in, 0, h);
if (br.@"else") |*e| if (e.* == h) {
e.* = S.block(nb, nbody, index_in, 0, h);
};
},
.@"switch" => |*sw| {
if (sw.default == h) sw.default = S.block(nb, nbody, index_in, 0, h);
const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = if (c.block == h) S.block(nb, nbody, index_in, 0, h) else c.block };
sw.cases = cs;
},
else => {},
};
}
}
try f.insts.appendSlice(ma, out.items);
f.num_blocks = nb + copies * nbody;
return true;
}
return false;
}
/// A branch target in copy `k`: the copy's own block, or (the header) the
/// next copy's.
fn mapBlock(t: u32, h: u32, k: u32, copies: u32, nb: u32, nbody: u32, idx: []const u32) u32 {
if (idx[t] == none) return t;
if (t == h) return nb + @min(k + 1, copies - 1) * nbody + idx[t];
return nb + k * nbody + idx[t];
}
/// Rewrites `inst`'s value operands through `ctx.visit` (block operands
/// are the caller's).
pub fn operandsMap(a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
const S = struct {
fn one(c: anytype, v: *Value) void {
v.* = c.visit(v.*, {});
}
fn many(al: Allocator, c: anytype, vs: *[]const Value) Allocator.Error!void {
const o = try al.alloc(Value, vs.len);
for (vs.*, o) |v, *x| x.* = c.visit(v, {});
vs.* = o;
}
};
switch (inst.op) {
.ret => |*v| if (v.*) |*x| S.one(ctx, x),
.br => |*b| if (b.cond) |*c| S.one(ctx, c),
.@"switch" => |*sw| S.one(ctx, &sw.cond),
.call => |*c| try S.many(a, ctx, &c.args),
.binop => |*b| {
S.one(ctx, &b.lhs);
S.one(ctx, &b.rhs);
},
.cast => |*c| S.one(ctx, &c.val),
.cmp => |*c| {
S.one(ctx, &c.lhs);
S.one(ctx, &c.rhs);
},
.select => |*s| {
S.one(ctx, &s.cond);
S.one(ctx, &s.t);
S.one(ctx, &s.f);
},
.extractvalue => |*x| S.one(ctx, &x.agg),
.phi => |*p| {
const out = try a.alloc(Edge, p.incoming.len);
for (p.incoming, out) |in, *o| o.* = .{ .val = ctx.visit(in.val, {}), .block = in.block };
p.incoming = out;
},
.alloca => |*x| S.one(ctx, &x.size),
.load => |*x| S.one(ctx, &x.ptr),
.store => |*x| {
S.one(ctx, &x.ptr);
S.one(ctx, &x.val);
},
.gep => |*x| {
S.one(ctx, &x.ptr);
try S.many(a, ctx, &x.indices);
},
.atomicrmw => |*x| {
S.one(ctx, &x.ptr);
S.one(ctx, &x.val);
},
.cmpxchg => |*x| {
S.one(ctx, &x.ptr);
S.one(ctx, &x.cmp);
S.one(ctx, &x.new);
},
.@"unreachable" => {},
.extractelement => |*x| {
S.one(ctx, &x.vec);
S.one(ctx, &x.index);
},
.insertelement => |*x| {
S.one(ctx, &x.vec);
S.one(ctx, &x.val);
S.one(ctx, &x.index);
},
}
}

View File

@ -51,6 +51,8 @@ pub const TypeRef = struct {
/// `#pragma pack_matrix` in effect where the type was written (true:
/// row_major): the orientation of a matrix declared without one.
pack_matrix: ?bool = null,
/// `struct S`: declares S (at namespace scope) if it is not yet a type.
elaborated: bool = false,
};
/// Storage classes, type qualifiers and parameter / interpolation

View File

@ -7,6 +7,7 @@
//! builtin types are recognized by name.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const ast = @import("ast.zig");
const lexer = @import("lexer.zig");
@ -20,7 +21,8 @@ const Loc = source.Loc;
pub const Error = Allocator.Error || error{Syntax};
const NameKind = enum { type, template_type, template_func, value };
/// (`function`: a plain function, which may overload function templates.)
const NameKind = enum { type, template_type, template_func, value, function };
pub const Parser = struct {
arena: Allocator,
@ -39,6 +41,8 @@ pub const Parser = struct {
/// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`.
last_struct_name: []const u8 = "",
/// The last parseType read `const` after the type (`float const x`).
type_const: bool = false,
/// The qualifier words read by the last parseQualifiers call.
last_quals: []const ast.QualWord = &.{},
/// Qualifier words for the next parseDeclaratorsInto call.
@ -58,6 +62,11 @@ pub const Parser = struct {
/// Collect every token from `pp` and set up a parser over them.
pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser {
var toks: std.ArrayList(Token) = .empty;
// Growing a large list in an arena leaves every old buffer behind:
// reserve about one token per 5 bytes of the files loaded so far.
var loaded: usize = 0;
for (pp.sm.files.items) |f| loaded += f.text.len;
try toks.ensureTotalCapacity(arena, loaded / 5 + 64);
var packs: std.ArrayList(PackPragma) = .empty;
while (true) {
// Preprocessor diagnostics are ordered by the token being produced.
@ -311,6 +320,14 @@ pub const Parser = struct {
try p.scopes.items[p.scopes.items.len - 1].append(p.arena, name);
}
/// Declares `name` in the outermost scope (under any inner entries).
fn declareGlobalName(p: *Parser, name: []const u8, kind: NameKind) Allocator.Error!void {
const gop = try p.names.getOrPut(p.arena, name);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.insert(p.arena, 0, kind);
try p.scopes.items[0].append(p.arena, name);
}
fn lookupName(p: *const Parser, name: []const u8) ?NameKind {
const list = p.names.get(name) orelse return null;
if (list.items.len == 0) return null;
@ -331,6 +348,10 @@ pub const Parser = struct {
if (p.lookupName(name)) |k| {
if (k == .template_type or k == .template_func) return true;
if (k == .value) return false;
if (k == .function) {
for (p.names.get(name).?.items) |o| if (o == .template_func) return true;
return false;
}
}
// Builtin templates keep working when a same-named user type exists
// in some namespace (the name table is not namespace-aware).
@ -342,6 +363,7 @@ pub const Parser = struct {
fn scanType(p: *const Parser, start: usize) ?usize {
var i = start;
while (isTypeAttrWord(p.toks[i])) i += 1;
if ((p.toks[i].isIdent("struct") or p.toks[i].isIdent("class")) and p.toks[i + 1].kind == .identifier) i += 1;
if (p.toks[i].isIdent("typename")) return p.scanDependentType(i + 1);
if (p.toks[i].isIdent("unsigned") or p.toks[i].isIdent("signed")) {
i += 1;
@ -390,6 +412,8 @@ pub const Parser = struct {
fn skipTypeAttrs(p: *const Parser, start: usize) usize {
var i = start;
// `T const`: a type qualifier written after the type.
while (p.toks[i].isIdent("const")) i += 1;
if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i;
var depth: u32 = 0;
while (true) : (i += 1) {
@ -504,7 +528,7 @@ pub const Parser = struct {
defer p.last_quals = words.items;
while (p.at(.identifier)) {
const word = p.tok().text;
if (inList(&reserved_declspecs, word)) {
if (isReservedDeclspec(word)) {
// dxc reports these and parses on as if they were absent.
_ = p.reportAt(p.pos, .@"error", "'{s}' is a reserved keyword in HLSL", .{word});
_ = p.advance();
@ -545,11 +569,26 @@ pub const Parser = struct {
t.pack_matrix = p.packMatrixAt(type_pos);
if (norm != .none) t.norm = norm;
if (words.items.len > 0) t.attr_words = words.items;
p.type_const = false;
while (p.eatIdent("const")) p.type_const = true;
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
return t;
}
/// parseType for a declaration: `const` after the type joins `quals`.
fn parseDeclType(p: *Parser, quals: *ast.Qualifiers) Error!*ast.TypeRef {
const t = try p.parseType();
if (p.type_const) quals.@"const" = true;
return t;
}
fn parseTypeInner(p: *Parser) Error!*ast.TypeRef {
// An elaborated type: `struct S` names S (declaring it if needed).
const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon;
if (elaborated) {
_ = p.advance();
if (!p.isTypeName(p.tok().text)) try p.declareGlobalName(p.tok().text, .type);
}
const start = p.tok();
if (p.eatIdent("typename")) {
// Dependent name: `typename X<T>::type`.
@ -581,7 +620,7 @@ pub const Parser = struct {
}
var args: []const ast.TemplateArg = &.{};
if (p.at(.less) and (p.forced_template or p.isTemplateName(name.last()))) args = try p.parseTemplateArgs();
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = name, .args = args });
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = name, .args = args, .elaborated = elaborated });
}
/// A qualified name whose final part may carry template arguments.
@ -600,17 +639,22 @@ pub const Parser = struct {
fn parseName(p: *Parser) Error!ast.Name {
const loc = p.tok().loc;
var parts: std.ArrayList([]const u8) = .empty;
var args: std.ArrayList([]const ast.TemplateArg) = .empty;
// Names are parsed very often and nearly all have one part: collect
// them on the stack and copy them to the arena once.
var parts_buf: [32][]const u8 = undefined;
var args_buf: [32][]const ast.TemplateArg = undefined;
var parts: std.ArrayList([]const u8) = .initBuffer(&parts_buf);
var args: std.ArrayList([]const ast.TemplateArg) = .initBuffer(&args_buf);
var any_args = false;
p.forced_template = false;
if (p.eat(.colon_colon)) {
try parts.append(p.arena, "");
try args.append(p.arena, &.{});
parts.appendAssumeCapacity("");
args.appendAssumeCapacity(&.{});
}
while (true) {
const id = try p.expectIdent("identifier");
try parts.append(p.arena, id.text);
if (parts.items.len == parts_buf.len) return p.fail("name has too many parts", .{});
parts.appendAssumeCapacity(id.text);
var part_args: []const ast.TemplateArg = &.{};
// `S<T>::member`: arguments followed by `::` belong to this part.
if (p.at(.less) and p.isTemplateName(id.text)) {
@ -621,7 +665,7 @@ pub const Parser = struct {
}
}
}
try args.append(p.arena, part_args);
args.appendAssumeCapacity(part_args);
if (!(p.at(.colon_colon) and p.peek(1).kind == .identifier and !p.peek(1).isIdent("operator"))) break;
_ = p.advance();
// `X<T>::template Y<U>`: the disambiguator.
@ -630,7 +674,11 @@ pub const Parser = struct {
p.forced_template = true;
}
}
return .{ .loc = loc, .parts = parts.items, .args = if (any_args) args.items else &.{} };
return .{
.loc = loc,
.parts = try p.arena.dupe([]const u8, parts.items),
.args = if (any_args) try p.arena.dupe([]const ast.TemplateArg, args.items) else &.{},
};
}
fn parseTemplateArgs(p: *Parser) Error![]const ast.TemplateArg {
@ -800,9 +848,9 @@ pub const Parser = struct {
return out.append(p.arena, d);
}
const quals = p.parseQualifiers();
var quals = p.parseQualifiers();
const words = p.last_quals;
const ty = try p.parseType();
const ty = try p.parseDeclType(&quals);
p.decl_quals = words;
const first = out.items.len;
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
@ -1255,7 +1303,7 @@ pub const Parser = struct {
if (template_params.len > 0) {
try p.declareNameOuter(name.last(), .template_func, true);
} else if (ctx != .member) {
try p.declareName(name.last(), .value);
try p.declareName(name.last(), .function);
}
_ = try p.expect(.l_paren, "'('");
try p.pushScope();
@ -1264,9 +1312,9 @@ pub const Parser = struct {
if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance();
while (!p.at(.r_paren)) {
const pattrs = try p.parseAttributes();
const pquals = p.parseQualifiers();
var pquals = p.parseQualifiers();
const pwords = p.last_quals;
const pty = try p.parseType();
const pty = try p.parseDeclType(&pquals);
var pname: []const u8 = "";
var pname_loc = p.tok().loc;
if (p.at(.identifier) and !isReserved(p.tok().text)) {
@ -1472,8 +1520,8 @@ pub const Parser = struct {
/// `expr`, or `T name = init` (C++ condition declaration).
fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } {
if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() };
const quals = p.parseQualifiers();
const ty = try p.parseType();
var quals = p.parseQualifiers();
const ty = try p.parseDeclType(&quals);
const name = try p.expectIdent("variable name");
_ = try p.expect(.equal, "'='");
const init_expr = try p.parseAssign();
@ -1531,7 +1579,7 @@ pub const Parser = struct {
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
return true;
if (inList(&reserved_declspecs, w)) return true;
if (isReservedDeclspec(w)) return true;
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) return true;
if (qualifierField(w) != null) {
if (!isContextualQualifier(w)) return true;
@ -1905,14 +1953,22 @@ fn isTechniqueWord(t: Token) bool {
}
/// dxc's g_DeprecatedEffectObjectNames.
fn isEffectObjectWord(t: Token) bool {
const names = [_][]const u8{
const effect_object_words = [_][]const u8{
"texture", "Texture", "pixelshader", "PixelShader", "vertexshader",
"VertexShader", "pixelfragment", "vertexfragment", "ComputeShader", "DomainShader",
"GeometryShader", "HullShader", "BlendState", "DepthStencilState", "DepthStencilView",
"RasterizerState", "RenderTargetView",
};
return t.kind == .identifier and inList(&names, t.text);
fn isEffectObjectWord(t: Token) bool {
if (t.kind != .identifier) return false;
const info = word_map.get(t.text) orelse return false;
return info.effect_object;
}
fn isReservedDeclspec(w: []const u8) bool {
const info = word_map.get(w) orelse return false;
return info.declspec;
}
/// Type attributes that may precede a type: `unorm float`,
@ -2043,6 +2099,8 @@ const WordInfo = struct {
numeric_scalar: bool = false,
object: bool = false,
template: bool = false,
declspec: bool = false,
effect_object: bool = false,
};
fn inList(list: []const []const u8, w: []const u8) bool {
@ -2054,7 +2112,7 @@ fn inList(list: []const []const u8, w: []const u8) bool {
/// replaces linear scans of the lists above (a third of parse time).
const word_map = blk: {
@setEvalBranchQuota(1_000_000);
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs);
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs ++ reserved_declspecs ++ effect_object_words);
for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]};
var kvs: [words.len]struct { []const u8, WordInfo } = undefined;
var n: usize = 0;
@ -2067,6 +2125,8 @@ const word_map = blk: {
.numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"),
.object = inList(&object_types, w) or inList(&enum_typedefs, w),
.template = inList(&template_types, w) or inList(&template_funcs, w),
.declspec = inList(&reserved_declspecs, w),
.effect_object = inList(&effect_object_words, w),
};
for (qualifier_words) |q| {
if (std.mem.eql(u8, q[0], w)) info.qualifier = q[1];
@ -2075,9 +2135,66 @@ const word_map = blk: {
n += 1;
}
const final = kvs[0..n].*;
break :blk std.StaticStringMap(WordInfo).initComptime(final);
break :blk WordMap(WordInfo, final.len).init(final);
};
/// A string map built at compile time: an open-addressing table on a cheap
/// hash, comparing a stored hash before any bytes. Most identifiers a
/// lookup sees are not in it, and miss after a probe or two (what
/// std.StaticStringMap does is compare every key of the same length).
fn WordMap(comptime V: type, comptime n: usize) type {
return struct {
const Self = @This();
/// Twice the keys or more, a power of two.
const size = std.math.ceilPowerOfTwoAssert(usize, n * 4);
const empty = std.math.maxInt(u16);
keys: [n][]const u8,
values: [n]V,
hashes: [n]u32,
slots: [size]u16,
fn hash(w: []const u8) u32 {
var h: u32 = 2166136261;
for (w) |c| h = (h ^ c) *% 16777619;
return h;
}
fn init(comptime kvs: anytype) Self {
var m: Self = undefined;
m.slots = @splat(empty);
for (kvs, 0..) |kv, k| {
m.keys[k] = kv[0];
m.values[k] = kv[1];
m.hashes[k] = hash(kv[0]);
var i = m.hashes[k] & (size - 1);
while (m.slots[i] != empty) i = (i + 1) & (size - 1);
m.slots[i] = k;
}
return m;
}
fn get(m: *const Self, w: []const u8) ?V {
const h = hash(w);
var i = h & (size - 1);
while (true) : (i = (i + 1) & (size - 1)) {
const k = m.slots[i];
if (k == empty) return null;
if (m.hashes[k] == h and std.mem.eql(u8, m.keys[k], w)) return m.values[k];
}
}
};
}
test WordMap {
const M = WordMap(u8, 3);
const m = comptime M.init(.{ .{ "float", 1 }, .{ "in", 2 }, .{ "inout", 3 } });
try std.testing.expectEqual(1, m.get("float").?);
try std.testing.expectEqual(3, m.get("inout").?);
try std.testing.expectEqual(null, m.get("floa"));
try std.testing.expectEqual(null, m.get(""));
}
fn isNumericScalar(w: []const u8) bool {
const info = word_map.get(w) orelse return false;
return info.numeric_scalar;
@ -2120,7 +2237,7 @@ const TestParse = struct {
mfs: source.MemoryFs = .{},
sm: source.SourceManager = undefined,
diags: Diagnostics = undefined,
arena: std.heap.ArenaAllocator = undefined,
arena: BumpArena = undefined,
out: std.Io.Writer.Allocating = undefined,
fn run(t: *TestParse, text: []const u8) ![]const u8 {

View File

@ -4,6 +4,7 @@
//! disabled macro.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const source = @import("source.zig");
const lexer = @import("lexer.zig");
@ -30,6 +31,7 @@ pub const Options = struct {
/// SPIR-V 1.x of the target environment.
spirv_minor: u32 = 0,
enable_16bit: bool = false,
hlsl_version: u16 = 2021,
};
const Builtin = enum {
@ -229,7 +231,10 @@ pub const Preprocessor = struct {
\\#define __DXC_VERSION_MINOR 10
\\#define __DXC_VERSION_RELEASE 0
\\#define __DXC_VERSION_COMMITS 0
\\#define __HLSL_VERSION 2021
\\
);
try w.print("#define __HLSL_VERSION {d}\n", .{o.hlsl_version});
try w.writeAll(
\\#define __SHADER_STAGE_VERTEX 1
\\#define __SHADER_STAGE_PIXEL 0
\\#define __SHADER_STAGE_GEOMETRY 2
@ -1442,7 +1447,7 @@ const TestPP = struct {
mfs: source.MemoryFs = .{},
sm: source.SourceManager = undefined,
diags: Diagnostics = undefined,
arena: std.heap.ArenaAllocator = undefined,
arena: BumpArena = undefined,
pp: Preprocessor = undefined,
fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void {

View File

@ -1,6 +1,7 @@
//! Source files and locations.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const scan = @import("scan.zig");
@ -134,7 +135,7 @@ pub const LineOverride = struct {
pub const PresumedLoc = struct { file: []const u8, line: u32 };
pub const SourceManager = struct {
arena: std.heap.ArenaAllocator,
arena: BumpArena,
files: std.ArrayList(File) = .empty,
fs: FileSystem,
/// path -> contents, or null if the path could not be read.
@ -317,30 +318,46 @@ fn decodeUtf16(a: Allocator, raw: []const u8) !?[]const u8 {
}
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
var i = std.mem.indexOfScalar(u8, raw, '\\') orelse return raw;
var out: std.ArrayList(u8) = .empty;
try out.ensureTotalCapacity(a, raw.len);
var i: usize = 0;
out.appendSliceAssumeCapacity(raw[0..i]);
// At a backslash: a splice, or the backslash kept; then the run to the
// next backslash, copied whole.
while (i < raw.len) {
if (raw[i] == '\\') {
var j = i + 1;
// Clang tolerates whitespace between the backslash and newline.
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
if (j < raw.len and raw[j] == '\n') {
i = j + 1;
continue;
}
if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
} else if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
i = j + 2;
continue;
}
}
out.appendAssumeCapacity(raw[i]);
} else {
out.appendAssumeCapacity('\\');
i += 1;
}
const next = std.mem.indexOfScalarPos(u8, raw, i, '\\') orelse raw.len;
out.appendSliceAssumeCapacity(raw[i..next]);
i = next;
}
return out.items;
}
test spliceLines {
const cases = [_][2][]const u8{
.{ "a\\\nb", "ab" },
.{ "a\\ \t\r\nb\\", "ab\\" },
.{ "\\x\\\\\ny", "\\x\\y" },
.{ "no splice", "no splice" },
.{ "#define A 1 \\\n + 2\n", "#define A 1 + 2\n" },
};
for (cases) |c| {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectEqualStrings(c[1], try spliceLines(arena.allocator(), c[0]));
}
}
test "line and column lookup" {
var mfs: MemoryFs = .{};
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());

View File

@ -20,6 +20,7 @@ const Allocator = std.mem.Allocator;
const ir = @import("ir.zig");
const types = @import("../sema/types.zig");
const opt = @import("opt.zig");
const split_resources = @import("split_resources.zig");
const Ref = ir.Ref;
const BlockId = ir.BlockId;
@ -73,6 +74,41 @@ pub fn run(m: *ir.Module) Error!void {
try markDead(m);
}
/// Inlines only the calls of functions that return a resource or a struct
/// holding one, in every kind of module (ray-tracing libraries included),
/// before resources are split out of structs: what such a function
/// returns can be an element of a resource array picked by an index it
/// computes (`bindless[NonUniformResourceIndex(i)]`), which no function
/// signature can pass back. dxc's legalization inlines everything.
pub fn runResourceReturns(m: *ir.Module) Error!void {
const a = m.arena;
const n = m.functions.items.len;
const shapes = try a.alloc(?Shape, n);
var any = false;
for (m.functions.items, shapes) |f, *sh| {
sh.* = .keep;
if (!isResource(m.types, f.ret) and !split_resources.holdsResources(m.types, f.ret)) continue;
const shape = try shapeOf(a, m, f);
sh.* = shape;
if (shape != .keep) any = true;
}
if (!any) return;
const done = try a.alloc(bool, n);
@memset(done, false);
var work: std.ArrayList(u32) = .empty;
for (m.entries.items) |e| {
try work.append(a, e.wrapper);
if (e.patch_wrapper) |pw| try work.append(a, pw);
}
try work.appendSlice(a, m.exports.items);
while (work.pop()) |fi| {
if (done[fi]) continue;
done[fi] = true;
try inlineCalls(m, m.functions.items[fi], shapes, &work);
}
try markDead(m);
}
/// How a function returns, for inlining it.
const Shape = union(enum) {
/// Not inlinable.

View File

@ -38,7 +38,8 @@ pub const BlockId = enum(u32) {
};
/// Where a pointer points.
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray };
/// (`node`: a work graph node record.)
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray, node };
/// Ray tracing shader storage an entry receives: the incoming payload,
/// the hit attributes and the incoming callable data.
@ -72,6 +73,9 @@ pub const Constant = union(enum) {
pub const Op = union(enum) {
/// A scalar constant (or a vector of one constant, splatted).
constant: Constant,
/// A node shader's input (`output` false) or its output `index`: the
/// node object (Entry.node's inputs / outputs).
node_io: struct { output: bool, index: u32 },
/// The function's `n`th parameter (a pointer for out / inout).
param: u32,
/// Pointer to a module global (resource, groupshared, static).
@ -356,6 +360,8 @@ pub const Stage = enum {
mesh,
amplification,
library,
/// Work graph nodes (SM 6.8 libraries).
node,
raygeneration,
intersection,
anyhit,
@ -409,6 +415,45 @@ pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, tria
pub const MeshOutput = enum { vertices, primitives, indices };
/// A node shader's properties (`[Shader("node")]`), from its attributes.
pub const NodeInfo = struct {
launch: Launch = .broadcasting,
is_program_entry: bool = false,
/// `[NodeID("name", index)]`; by default the function's name, 0.
id: NodeId,
local_root_arguments_table_index: ?u32 = null,
share_input_of: ?NodeId = null,
dispatch_grid: ?[3]u32 = null,
max_dispatch_grid: ?[3]u32 = null,
max_recursion_depth: ?u32 = null,
inputs: []const NodeIo = &.{},
outputs: []const NodeIo = &.{},
/// NodeLaunchType.
pub const Launch = enum(u32) { broadcasting = 1, coalescing = 2, thread = 3 };
};
pub const NodeId = struct { name: []const u8, index: u32 = 0 };
/// One node input or output: a parameter of a node object type.
pub const NodeIo = struct {
kind: types.NodeKind,
/// The record type (void for empty inputs / outputs).
record: TypeId,
/// I/O flags beyond the kind: TrackRWInputSharing 0x100,
/// GloballyCoherent 0x200.
extra_flags: u32 = 0,
/// Outputs: `[NodeID]`, by default the parameter's name, 0.
output_id: ?NodeId = null,
max_records: ?u32 = null,
/// Outputs: the index of the output whose records these share.
max_records_shared_with: ?u32 = null,
/// Output arrays: `[NodeArraySize(n)]`, or maxInt for
/// `[UnboundedSparseNodes]`.
array_size: ?u32 = null,
allow_sparse_nodes: bool = false,
};
pub const MeshInfo = struct {
max_vertices: u32 = 0,
max_primitives: u32 = 0,
@ -436,9 +481,14 @@ pub const Entry = struct {
name: []const u8,
stage: Stage,
num_threads: [3]u32 = .{ 1, 1, 1 },
/// `[WaveSize(min[, max[, preferred]])]`: zeros where not given (no
/// attribute: min 0).
wave_size: [3]u32 = .{ 0, 0, 0 },
geometry: GeometryInfo = .{},
tess: TessInfo = .{},
mesh: MeshInfo = .{},
/// Node shaders.
node: ?NodeInfo = null,
inputs: std.ArrayList(SigElement) = .empty,
outputs: std.ArrayList(SigElement) = .empty,
/// Patch constants: written by the hull shader's patch constant
@ -483,8 +533,9 @@ pub const SpirvExt = struct {
pub const SpirvInst = struct {
opcode: u32,
set: ?[]const u8 = null,
/// Values, pointers (`[[vk::ext_reference]]`) or literal words.
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId },
/// Values, pointers (`[[vk::ext_reference]]`), literal words, types,
/// or the id of an OpString (printf's format).
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId, string: []const u8 },
capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{},
};
@ -658,6 +709,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
.float => |v| try w.print("const {d}", .{v}),
},
.param => |p| try w.print("param {d}", .{p}),
.node_io => |x| try w.print("node_{s} {d}", .{ if (x.output) "output" else "input", x.index }),
.global => |g| try w.print("global @{d}", .{g}),
.local_var => try w.writeAll("local_var"),
.load => |p| try w.print("load %{d}", .{p.index()}),

View File

@ -169,9 +169,7 @@ fn structAlign(t: *const TypeTable, info: *const types.StructInfo, rules: Rules)
}
fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 {
var buf: [256]u32 = undefined;
if (info.fields.items.len > buf.len) return error.Unsupported;
const off = try layoutFields(t, info, rules, buf[0..info.fields.items.len]);
const off = try layoutFields(t, info, rules, null);
return switch (rules) {
.dx_legacy => off,
// (Packed structs still round up to their widest component: a
@ -180,9 +178,9 @@ fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules)
};
}
/// Stores the offsets of `info`'s fields in `out`; returns where the last
/// one ends.
fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: []u32) Error!u32 {
/// Stores the offsets of `info`'s fields in `out` (if given); returns where
/// the last one ends.
fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: ?[]u32) Error!u32 {
var off: u32 = 0;
var first: usize = 0;
if (info.bases.items.len > 0 and rules != .dx_legacy and rules != .dx_packed) {
@ -190,7 +188,7 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules
// its alignment); DXIL lays its fields out in place.
const base = info.bases.items[0];
first = base.fields.items.len;
_ = try layoutFields(t, base, rules, out[0..first]);
_ = try layoutFields(t, base, rules, if (out) |o| o[0..first] else null);
off = try structSize(t, base, rules);
}
// Explicit offsets (packoffset / register(cN)): the other members
@ -201,20 +199,20 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules
};
if (packed_end) |pe| off = @max(off, pe);
var end: u32 = off;
for (info.fields.items[first..], out[first..]) |f, *o| {
for (info.fields.items[first..], first..) |f, i| {
// (Resources in structs take no space in buffers.)
if (isOpaque(t, f.type)) {
o.* = off;
continue;
}
if (f.pack_offset) |po| {
o.* = po;
continue;
}
const at = if (isOpaque(t, f.type))
off
else if (f.pack_offset) |po|
po
else at: {
// [[vk::offset]] (SPIR-V only): later members continue from it.
o.* = if (f.vk_offset) |vo| vo else try place(t, off, f.type, f.row_major, rules);
off = o.* + try sizeOf(t, f.type, f.row_major, rules);
const o = if (f.vk_offset) |vo| vo else try place(t, off, f.type, f.row_major, rules);
off = o + try sizeOf(t, f.type, f.row_major, rules);
end = @max(end, off);
break :at o;
};
if (out) |o| o[i] = at;
}
return @max(end, packed_end orelse 0);
}

View File

@ -73,11 +73,21 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
/// The stage a `[shader("...")]` attribute names.
fn stageNamed(name: []const u8) ?ir.Stage {
const names = [_]struct { []const u8, ir.Stage }{
.{ "vertex", .vertex }, .{ "pixel", .pixel }, .{ "geometry", .geometry },
.{ "hull", .hull }, .{ "domain", .domain }, .{ "compute", .compute },
.{ "mesh", .mesh }, .{ "amplification", .amplification }, .{ "raygeneration", .raygeneration },
.{ "intersection", .intersection }, .{ "anyhit", .anyhit }, .{ "closesthit", .closesthit },
.{ "miss", .miss }, .{ "callable", .callable },
.{ "node", .node },
.{ "vertex", .vertex },
.{ "pixel", .pixel },
.{ "geometry", .geometry },
.{ "hull", .hull },
.{ "domain", .domain },
.{ "compute", .compute },
.{ "mesh", .mesh },
.{ "amplification", .amplification },
.{ "raygeneration", .raygeneration },
.{ "intersection", .intersection },
.{ "anyhit", .anyhit },
.{ "closesthit", .closesthit },
.{ "miss", .miss },
.{ "callable", .callable },
};
for (names) |t| if (std.ascii.eqlIgnoreCase(name, t[0])) return t[1];
return null;
@ -1026,6 +1036,15 @@ const Lowerer = struct {
},
.conditional => |x| {
const ty = try l.concrete(e.ty);
// HLSL 2018: both operands, then a (per-component) select.
if (l.s.opts.hlsl_version < 2021 and t.isNumeric(ty)) {
const cs = t.shape(x.cond.ty);
const cond_ty = if (cs != null and cs.?.kind != .scalar) try t.withComponent(ty, .bool) else try t.scalar(.bool);
const cond = try l.converted(x.cond, cond_ty);
const a = try l.converted(x.then, ty);
const b = try l.converted(x.@"else", ty);
return l.b.add(.{ .op = .{ .select = .{ .cond = cond, .t = a, .f = b } }, .ty = ty });
}
const tmp = try l.b.add(.{ .op = .local_var, .ty = ty, .ptr = .function });
const cond = try l.condition(x.cond);
const then_b = try l.b.newBlock();
@ -1061,6 +1080,13 @@ const Lowerer = struct {
const idx = try l.indexValue(x.index, bt.resource.kind.indexDims());
return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) });
}
if (bt == .node) {
if (bt.node.kind.isArray()) return l.b.load(try l.nodeRecordPtr(e));
// An output of an outputs array: the node object.
const obj = try l.rvalue(x.base);
const idx = try l.converted(x.index, try t.scalar(.uint));
return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty });
}
if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e));
const base = try l.rvalue(x.base);
if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) });
@ -1072,6 +1098,9 @@ const Lowerer = struct {
return l.b.load(p);
},
.sizeof_type, .sizeof_expr, .is_same => {
// (Sema keeps the size; a template instance's type names
// no longer resolve here.)
if (e.kind == .sizeof_type and e.info != 0) return l.b.constInt(try l.concrete(e.ty), e.info - 1);
if (l.s.evalInt(e)) |v| return l.b.constInt(try l.concrete(e.ty), v);
return l.fail(e, "this expression");
},
@ -1103,7 +1132,13 @@ const Lowerer = struct {
_ = try l.rvalue(lhs);
return l.rvalue(rhs);
},
.log_and, .log_or => {
.log_and, .log_or => if (l.s.opts.hlsl_version < 2021) {
// HLSL 2018: both operands, component-wise.
const ty = try l.concrete(e.ty);
const a = try l.converted(lhs, ty);
const b = try l.converted(rhs, ty);
return l.b.add(.{ .op = .{ .binary = .{ .op = if (op == .log_and) .log_and else .log_or, .lhs = a, .rhs = b } }, .ty = ty });
} else {
// Short-circuit (HLSL 2021: scalar operands).
const bool_ty = try t.scalar(.bool);
const tmp = try l.b.add(.{ .op = .local_var, .ty = bool_ty, .ptr = .function });
@ -1359,6 +1394,7 @@ const Lowerer = struct {
fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref {
const r = l.s.resolution(e) orelse return l.fail(e, "this call");
const ret_ty = try l.concrete(e.ty);
if (r == .node_record) return l.b.load(try l.nodeRecordPtr(e));
switch (r) {
.function => |f| {
if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty);
@ -1529,6 +1565,16 @@ const Lowerer = struct {
};
return result;
}
// printf: NonSemantic.DebugPrintf's DebugPrintf (opcode 1)
// with the format as an OpString (SPIR-V only).
if (std.mem.eql(u8, name, "printf") and l.s.opts.spirv and args.len >= 1 and args[0].kind == .string_lit) {
const p = try l.arena.create(ir.SpirvInst);
const ops = try l.arena.alloc(@typeInfo(@TypeOf(p.operands)).pointer.child, args.len);
ops[0] = .{ .string = try stringContents(l.arena, args[0].kind.string_lit) };
for (ops[1..], args[1..]) |*o, a| o.* = .{ .value = try l.converted(a, try l.concrete(a.ty)) };
p.* = .{ .opcode = 1, .set = "NonSemantic.DebugPrintf", .operands = ops, .extensions = try l.arena.dupe([]const u8, &.{"SPV_KHR_non_semantic_info"}) };
return l.b.add(.{ .op = .{ .spirv_inst = p }, .ty = TypeTable.void_type });
}
if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) {
// The payload goes by reference (a groupshared
// variable).
@ -1736,7 +1782,22 @@ const Lowerer = struct {
return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space });
}
/// A node record: `obj.Get()`, `obj.Get(i)` or `obj[i]` (an element
/// of the node object, in node record memory).
fn nodeRecordPtr(l: *Lowerer, e: *ast.Expr) Error!Ref {
const t = l.types();
const obj_expr, const index: ?*ast.Expr = switch (e.kind) {
.call => |c| .{ c.callee.kind.member.base, if (c.args.len > 0) c.args[0] else null },
.index => |x| .{ x.base, x.index },
else => return l.fail(e, "this node record"),
};
const obj = try l.rvalue(obj_expr);
const idx = if (index) |i| try l.converted(i, try t.scalar(.uint)) else try l.b.constInt(try t.scalar(.uint), 0);
return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = .node });
}
fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
if (l.s.resolution(e)) |r| if (r == .node_record) return l.nodeRecordPtr(e);
const t = l.types();
// A resource inside a global struct: its own global.
if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty);
@ -1756,6 +1817,12 @@ const Lowerer = struct {
return l.variableLvalue(e, r.variable);
},
.member => |m| {
// One component of a vector (atomics' `ref`, `B[i].x`).
if (l.s.resolution(e) == null and t.get(m.base.ty) == .vector) if (try swizzleComponents(l.arena, m.name)) |comps| if (comps.len == 1) {
const base = try l.lvalue(m.base);
const idx = try l.b.constInt(try t.scalar(.uint), comps[0]);
return l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = l.b.f.inst(base).ptr });
};
const r = l.s.resolution(e) orelse return l.fail(e, "this member");
// A static member through an object.
if (r == .variable) return l.variableLvalue(e, r.variable);
@ -2397,6 +2464,97 @@ const Lowerer = struct {
entry.patch_wrapper = wrapper;
}
/// A node shader's properties: its attributes and its node object
/// parameters (inputs, then outputs, in parameter order).
fn nodeInfo(l: *Lowerer, f: *const semamod.Function) Error!ir.NodeInfo {
const eqi = std.ascii.eqlIgnoreCase;
var info: ir.NodeInfo = .{ .id = .{ .name = f.name } };
for (f.decl.attrs) |a| {
if (eqi(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
const v = try stringContents(l.arena, a.args[0].kind.string_lit);
if (eqi(v, "coalescing")) info.launch = .coalescing else if (eqi(v, "thread")) info.launch = .thread else info.launch = .broadcasting;
} else if (eqi(a.name, "nodeisprogramentry")) {
info.is_program_entry = true;
} else if (eqi(a.name, "nodeid")) {
if (try l.nodeId(a)) |id| info.id = id;
} else if (eqi(a.name, "nodelocalrootargumentstableindex") and a.args.len == 1) {
info.local_root_arguments_table_index = l.attrUint(a.args[0]);
} else if (eqi(a.name, "nodeshareinputof")) {
info.share_input_of = try l.nodeId(a);
} else if (eqi(a.name, "nodedispatchgrid") and a.args.len == 3) {
info.dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) };
} else if (eqi(a.name, "nodemaxdispatchgrid") and a.args.len == 3) {
info.max_dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) };
} else if (eqi(a.name, "nodemaxrecursiondepth") and a.args.len == 1) {
info.max_recursion_depth = l.attrUint(a.args[0]);
}
}
var inputs: std.ArrayList(ir.NodeIo) = .empty;
var outputs: std.ArrayList(ir.NodeIo) = .empty;
var out_names: std.ArrayList([]const u8) = .empty;
// MaxRecordsSharedWith names a later output too: resolved after.
var shared: std.ArrayList(struct { out: usize, name: []const u8 }) = .empty;
for (f.decl.params, f.params) |pd, p| {
const nt = switch (l.s.types.get(p.type)) {
.node => |x| x,
else => continue,
};
var io: ir.NodeIo = .{ .kind = nt.kind, .record = nt.elem };
if (pd.quals.globallycoherent) io.extra_flags |= 0x200;
if (nt.elem != TypeTable.void_type and l.trackRwInputSharing(nt.elem)) io.extra_flags |= 0x100;
if (!nt.kind.isInput()) io.output_id = .{ .name = pd.name };
for (pd.attrs) |a| {
if (eqi(a.name, "maxrecords") and a.args.len == 1) {
io.max_records = l.attrUint(a.args[0]);
} else if (eqi(a.name, "nodeid")) {
if (try l.nodeId(a)) |id| io.output_id = id;
} else if (eqi(a.name, "nodearraysize") and a.args.len == 1) {
io.array_size = l.attrUint(a.args[0]);
} else if (eqi(a.name, "unboundedsparsenodes")) {
io.array_size = std.math.maxInt(u32);
io.allow_sparse_nodes = true;
} else if (eqi(a.name, "allowsparsenodes")) {
io.allow_sparse_nodes = true;
} else if (eqi(a.name, "maxrecordssharedwith") and a.args.len == 1 and a.args[0].kind == .name) {
try shared.append(l.arena, .{ .out = outputs.items.len, .name = a.args[0].kind.name.last() });
}
}
if (nt.kind.isInput()) {
try inputs.append(l.arena, io);
} else {
try outputs.append(l.arena, io);
try out_names.append(l.arena, pd.name);
}
}
for (shared.items) |sh| {
for (out_names.items, 0..) |n, k| if (std.mem.eql(u8, n, sh.name)) {
outputs.items[sh.out].max_records_shared_with = @intCast(k);
};
}
info.inputs = inputs.items;
info.outputs = outputs.items;
return info;
}
/// `[NodeID("name"[, index])]`, `[NodeShareInputOf(...)]`.
fn nodeId(l: *Lowerer, a: ast.Attribute) Error!?ir.NodeId {
if (a.args.len < 1 or a.args[0].kind != .string_lit) return null;
return .{ .name = try stringContents(l.arena, a.args[0].kind.string_lit), .index = if (a.args.len > 1) l.attrUint(a.args[1]) else 0 };
}
fn attrUint(l: *Lowerer, e: *const ast.Expr) u32 {
return @intCast(std.math.clamp(l.s.evalInt(e) orelse 0, 0, std.math.maxInt(u32)));
}
/// A record struct declared `[NodeTrackRWInputSharing]`.
fn trackRwInputSharing(l: *Lowerer, record: TypeId) bool {
const info = switch (l.s.types.get(record)) {
.@"struct" => |s| s,
else => return false,
};
return l.s.structHasAttr(info, "nodetrackrwinputsharing");
}
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
const inits = try l.staticInits();
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage, .ext = try l.spirvExt(f.decl.attrs) };
@ -2405,6 +2563,9 @@ const Lowerer = struct {
if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) {
for (a.args, 0..) |arg, i| entry.num_threads[i] = @intCast(@max(1, l.s.evalInt(arg) orelse 1));
}
if (std.ascii.eqlIgnoreCase(a.name, "wavesize") and a.args.len >= 1 and a.args.len <= 3) {
for (a.args, 0..) |arg, i| entry.wave_size[i] = @intCast(@max(0, l.s.evalInt(arg) orelse 0));
}
if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "RootSignature") and a.args.len == 1 and a.args[0].kind == .string_lit) entry.root_signature = try stringContents(l.arena, a.args[0].kind.string_lit);
@ -2434,14 +2595,25 @@ const Lowerer = struct {
}
};
if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload;
if (opts.stage == .node) entry.node = try l.nodeInfo(f);
const tess = opts.stage == .hull or opts.stage == .domain;
if (tess) l.tessAttributes(f, &entry);
// Hull shaders: where the control point inputs start.
var cp_first: ?u32 = null;
var node_in: u32 = 0;
var node_out: u32 = 0;
for (f.decl.params, f.params, 0..) |pd, p, i| {
if (l.s.types.get(p.type) == .stream) continue;
n_args += 1;
const q = pd.quals;
if (l.s.types.get(p.type) == .node) {
const output = !l.s.types.get(p.type).node.kind.isInput();
const index = if (output) node_out else node_in;
if (output) node_out += 1 else node_in += 1;
args[i] = try l.b.add(.{ .op = .{ .node_io = .{ .output = output, .index = index } }, .ty = p.type });
locals[i] = args[i];
continue;
}
if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) {
// Output arrays: stores through them write the outputs.
const arr = l.s.types.get(p.type).array;
@ -2724,7 +2896,6 @@ pub fn isObject(t: *TypeTable, ty: TypeId) bool {
};
}
fn semanticOf(sems: []const ast.Semantic) ?[]const u8 {
for (sems) |sem| if (sem.kind == .semantic) return sem.values[0];
return null;
@ -2818,6 +2989,7 @@ fn signExtend(v: u64, bits: u8) i64 {
/// Whether `e` designates storage (a variable, or a part of one) rather
/// than a temporary such as an operator call's result.
fn isAddressable(s: *const Sema, e: *const ast.Expr) bool {
if (s.resolution(e)) |r| if (r == .node_record) return true;
return switch (e.kind) {
.name, .this => true,
.member => |m| isAddressable(s, m.base),

View File

@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
/// `op` with every operand passed through `ctx.map`.
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
return switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => op,
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => op,
.load => |p| .{ .load = ctx.map(p) },
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },
@ -207,7 +207,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands);
for (ops) |*o| switch (o.*) {
.value => |*v| v.* = ctx.map(v.*),
.literal, .type => {},
.literal, .type, .string => {},
};
const n = try a.create(ir.SpirvInst);
n.* = x.*;
@ -227,7 +227,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
/// allocating.
pub fn eachOperand(op: Op, ctx: anytype) void {
switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => {},
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => {},
.load => |p| ctx.use(p),
.store => |x| {
ctx.use(x.ptr);
@ -278,7 +278,7 @@ pub fn eachOperand(op: Op, ctx: anytype) void {
.heap_resource => |h| ctx.use(h.index),
.spirv_inst => |x| for (x.operands) |o| switch (o) {
.value => |v| ctx.use(v),
.literal, .type => {},
.literal, .type, .string => {},
},
.patch_output => |x| ctx.use(x.value),
.phi => |ps| for (ps) |pp| ctx.use(pp.value),

View File

@ -189,6 +189,8 @@ const Pass = struct {
if (info.done) return;
info.done = true;
const f = p.m.functions.items[fi];
// (Inlined everywhere: not emitted.)
if (f.dead) return;
// Callees first: their returns may be resources.
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
@ -209,7 +211,10 @@ const Pass = struct {
const n_old = f.insts.items.len;
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
for (f.blocks.items, 0..) |*blk, bi| {
// Definitions before uses: inlining leaves a call's continuation
// ahead of the callee's blocks.
for (try reversePostorder(p.a, f)) |bi| {
const blk = &f.blocks.items[bi];
var out: std.ArrayList(Ref) = .empty;
for (blk.insts.items) |r| {
const old = f.insts.items[r.index()];
@ -421,7 +426,6 @@ const Pass = struct {
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
else => {},
}
_ = bi;
}
_ = n_old;
// What each out / inout resource holds when the function returns:
@ -480,6 +484,42 @@ const Pass = struct {
}
};
/// `f`'s blocks in reverse postorder from the entry (each block after its
/// dominators), then any unreachable ones in list order.
fn reversePostorder(a: Allocator, f: *const ir.Function) Allocator.Error![]const u32 {
const n = f.blocks.items.len;
const seen = try a.alloc(bool, n);
@memset(seen, false);
var post: std.ArrayList(u32) = try .initCapacity(a, n);
// (block, whether its successors were pushed)
var stack: std.ArrayList(struct { b: u32, expanded: bool }) = .empty;
if (n > 0) try stack.append(a, .{ .b = 0, .expanded = false });
while (stack.pop()) |it| {
if (it.expanded) {
post.appendAssumeCapacity(it.b);
continue;
}
if (seen[it.b]) continue;
seen[it.b] = true;
try stack.append(a, .{ .b = it.b, .expanded = true });
const succs: []const ir.BlockId = switch (f.blocks.items[it.b].term) {
.br => |t| &.{t},
.cond_br => |c| &.{ c.@"else", c.then },
.@"switch" => |sw| blk: {
const out = try a.alloc(ir.BlockId, sw.cases.len + 1);
for (sw.cases, 0..) |c, i| out[sw.cases.len - 1 - i] = c.block;
out[sw.cases.len] = sw.default;
break :blk out;
},
else => &.{},
};
for (succs) |sb| if (sb != .none and !seen[sb.index()]) try stack.append(a, .{ .b = @intCast(sb.index()), .expanded = false });
}
std.mem.reverse(u32, post.items);
for (0..n) |bi| if (!seen[bi]) post.appendAssumeCapacity(@intCast(bi));
return post.items;
}
/// Splits every function's resource-holding aggregates (SPIR-V only).
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
var any = false;

View File

@ -20,14 +20,45 @@
//! directory, as on the command line. Each job's output and diagnostics
//! are printed in job order; the exit code is 0 when every job succeeds,
//! else 1 if any job failed on its command line or I/O, else 5.
//!
//! Two more threads read the jobs' input files ahead of the compiles and
//! write their outputs after them, so the compile threads do not wait on
//! opening files (which Windows, with its on-access scanner, serializes).
//! An output that cannot be written is reported after every job's output,
//! and fails its job.
const std = @import("std");
const BumpArena = @import("zdxc").BumpArena;
const Io = std.Io;
const Allocator = std.mem.Allocator;
const FileSystem = @import("zdxc").front.source.FileSystem;
/// Compiles one job: `args` is a full command line (argv[0] first). It
/// writes to `stdout` / `stderr` and returns the exit code.
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8;
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, ctx: Context, stdout: *Io.Writer, stderr: *Io.Writer) u8;
/// What a run gives a compile besides its command line.
pub const Context = struct {
/// The input file's text, already read.
source: ?[]const u8 = null,
/// Reads the other files (null: from disk).
fs: ?FileSystem = null,
/// Where to add the files to write (allocated in the compile's arena),
/// instead of writing them.
outputs: ?*Outputs = null,
};
/// A file a job writes.
pub const Output = struct { path: []const u8, bytes: []const u8 };
pub const Outputs = std.ArrayList(Output);
/// The input file a job's command line names, if any.
pub const InputFn = *const fn (arena: Allocator, args: []const [:0]const u8) ?[]const u8;
/// How many jobs the reading thread may get ahead of the compiles.
const read_ahead = 256;
/// The compiles wake the reading thread every this many jobs.
const wake_every = 32;
const JobFile = struct {
threads: ?u32 = null,
@ -43,7 +74,7 @@ pub fn find(argv: []const [:0]const u8) ?usize {
/// Runs the job file `argv[at]` names; the other arguments apply to every
/// job. Returns the process exit code.
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, input: InputFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const path = argv[at]["--job=".len..];
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 30)) catch |e| {
try stderr.print("zdxc: error: cannot read job file '{s}': {s}\n", .{ path, @errorName(e) });
@ -70,8 +101,23 @@ pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, comp
j.* = full;
}
var b: Batch = .{ .io = io, .jobs = jobs, .results = try arena.alloc(Result, jobs.len), .compile = compile, .stdout = stdout, .stderr = stderr };
var b: Batch = .{
.io = io,
.jobs = jobs,
.results = try arena.alloc(Result, jobs.len),
.sources = try arena.alloc(Source, jobs.len),
.files = .{ .io = io },
.compile = compile,
.input = input,
.stdout = stdout,
.stderr = stderr,
};
@memset(b.results, .{});
@memset(b.sources, .{});
const reader: ?std.Thread = std.Thread.spawn(.{}, Batch.read, .{&b}) catch null;
b.reading = reader != null;
const writer: ?std.Thread = std.Thread.spawn(.{}, Batch.write, .{&b}) catch null;
b.writing = writer != null;
const cpus: u32 = @intCast(std.Thread.getCpuCount() catch 1);
const nthreads = @max(1, @min(file.threads orelse cpus, jobs.len));
// The calling thread is one of the workers.
@ -83,6 +129,9 @@ pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, comp
}
b.work();
for (threads[0..spawned]) |t| t.join();
if (reader) |t| t.join();
if (writer) |t| t.join();
try stderr.writeAll(b.write_errors.items);
var failed: usize = 0;
var code: u8 = 0;
@ -99,38 +148,204 @@ const Result = struct {
code: u8 = 0,
out: []u8 = &.{},
err: []u8 = &.{},
/// Files for the writing thread; owned by smp_allocator.
writes: []Output = &.{},
};
/// Files the jobs read (headers, mostly), shared by the whole run: each is
/// opened once, rather than once per job and include directory searched.
/// Files that do not exist are remembered too. The text lives until the
/// process exits.
const FileCache = struct {
io: Io,
mutex: Io.Mutex = .init,
files: std.StringHashMapUnmanaged(?[]const u8) = .empty,
fn fileSystem(c: *FileCache) FileSystem {
return .{ .ctx = c, .readFn = read };
}
fn read(ctx: *anyopaque, _: Allocator, path: []const u8) ?[]const u8 {
const c: *FileCache = @ptrCast(@alignCast(ctx));
const gpa = std.heap.smp_allocator;
{
c.mutex.lockUncancelable(c.io);
defer c.mutex.unlock(c.io);
if (c.files.get(path)) |cached| return cached;
}
// Read outside the lock: other jobs keep using the cache meanwhile.
const text: ?[]const u8 = Io.Dir.cwd().readFileAlloc(c.io, path, gpa, .limited(256 << 20)) catch null;
c.mutex.lockUncancelable(c.io);
defer c.mutex.unlock(c.io);
const key = gpa.dupe(u8, path) catch return text;
const gop = c.files.getOrPut(gpa, key) catch {
gpa.free(key);
return text;
};
if (gop.found_existing) {
gpa.free(key);
if (text) |t| gpa.free(t);
return gop.value_ptr.*;
}
gop.value_ptr.* = text;
return text;
}
};
/// A job's input file, as read by the reading thread.
const Source = struct {
state: std.atomic.Value(State) = .init(.pending),
/// Valid once `state` is `.read`; owned by smp_allocator.
text: []u8 = &.{},
const State = enum(u32) {
pending,
read,
/// No input named, or it could not be read: the compile reads (and
/// reports) it itself.
none,
};
};
const Batch = struct {
io: Io,
jobs: []const []const [:0]const u8,
results: []Result,
sources: []Source,
files: FileCache,
compile: CompileFn,
input: InputFn,
stdout: *Io.Writer,
stderr: *Io.Writer,
/// Whether the reading thread is running (else every source is read by
/// its compile).
reading: bool = false,
/// Whether the writing thread is running (else every compile writes its
/// own outputs).
writing: bool = false,
/// Messages for the outputs the writing thread could not write.
write_errors: std.ArrayList(u8) = .empty,
/// `printed`, for the writing thread to wait on: it writes a job's
/// outputs once the job is printed.
printed_count: std.atomic.Value(u32) = .init(0),
next: std.atomic.Value(usize) = .init(0),
/// Jobs taken by the compiles, for the reading thread to wait on.
started: std.atomic.Value(u32) = .init(0),
/// Guards `results` and the writers; jobs are printed in order.
mutex: Io.Mutex = .init,
printed: usize = 0,
/// Reads every job's input file in job order, at most `read_ahead`
/// jobs ahead of the compiles.
fn read(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: BumpArena = .init(gpa);
defer arena.deinit();
for (b.jobs, b.sources, 0..) |args, *s, i| {
while (true) {
const started = b.started.load(.acquire);
if (i < @as(usize, started) + read_ahead) break;
b.io.futexWaitUncancelable(u32, &b.started.raw, started);
}
_ = arena.reset(.retain_capacity);
const text: ?[]u8 = if (b.input(arena.allocator(), args)) |path|
Io.Dir.cwd().readFileAlloc(b.io, path, gpa, .limited(256 << 20)) catch null
else
null;
if (text) |t| s.text = t;
s.state.store(if (text != null) .read else .none, .release);
b.io.futexWake(Source.State, &s.state.raw, std.math.maxInt(u32));
}
}
/// Writes every job's outputs, in job order, as the jobs are printed.
fn write(b: *Batch) void {
const gpa = std.heap.smp_allocator;
for (b.results, 0..) |*r, i| {
while (true) {
const printed = b.printed_count.load(.acquire);
if (i < printed) break;
b.io.futexWaitUncancelable(u32, &b.printed_count.raw, printed);
}
for (r.writes) |o| {
Io.Dir.cwd().writeFile(b.io, .{ .sub_path = o.path, .data = o.bytes }) catch |e| {
b.write_errors.print(gpa, "zdxc: error: cannot write '{s}': {s}\n", .{ o.path, @errorName(e) }) catch {};
r.code = 1;
};
gpa.free(o.path);
gpa.free(o.bytes);
}
gpa.free(r.writes);
r.writes = &.{};
}
}
/// The outputs of a job, copied out of its arena (null if out of
/// memory: then the job fails).
fn keep(outputs: []const Output) ?[]Output {
const gpa = std.heap.smp_allocator;
const kept = gpa.alloc(Output, outputs.len) catch return null;
for (kept, outputs, 0..) |*k, o, n| {
const path = gpa.dupe(u8, o.path) catch null;
const bytes = if (path != null) gpa.dupe(u8, o.bytes) catch null else null;
if (bytes == null) {
if (path) |p| gpa.free(p);
for (kept[0..n]) |d| {
gpa.free(d.path);
gpa.free(d.bytes);
}
gpa.free(kept);
return null;
}
k.* = .{ .path = path.?, .bytes = bytes.? };
}
return kept;
}
fn work(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
var arena: BumpArena = .init(gpa);
defer arena.deinit();
while (true) {
const i = b.next.fetchAdd(1, .monotonic);
if (i >= b.jobs.len) return;
if (b.started.fetchAdd(1, .release) % wake_every == wake_every - 1) b.io.futexWake(u32, &b.started.raw, 1);
_ = arena.reset(.retain_capacity);
const a = arena.allocator();
var out: Io.Writer.Allocating = .init(a);
var err: Io.Writer.Allocating = .init(a);
const code = b.compile(b.io, a, b.jobs[i], &out.writer, &err.writer);
const s = &b.sources[i];
var source: ?[]const u8 = null;
if (b.reading) {
while (true) switch (s.state.load(.acquire)) {
.pending => b.io.futexWaitUncancelable(Source.State, &s.state.raw, .pending),
.read => {
source = s.text;
break;
},
.none => break,
};
}
var outputs: Outputs = .empty;
var code = b.compile(b.io, a, b.jobs[i], .{
.source = source,
.fs = b.files.fileSystem(),
.outputs = if (b.writing) &outputs else null,
}, &out.writer, &err.writer);
gpa.free(s.text);
s.text = &.{};
// The arena is reused for the next job: keep the output.
const writes: []Output = keep(outputs.items) orelse writes: {
err.writer.writeAll("zdxc: error: OutOfMemory\n") catch {};
code = 1;
break :writes &.{};
};
b.finish(i, .{
.done = true,
.code = code,
.out = gpa.dupe(u8, out.written()) catch &.{},
.err = gpa.dupe(u8, err.written()) catch &.{},
.writes = writes,
});
}
}
@ -152,5 +367,7 @@ const Batch = struct {
}
b.stdout.flush() catch {};
b.stderr.flush() catch {};
b.printed_count.store(@intCast(b.printed), .release);
b.io.futexWake(u32, &b.printed_count.raw, 1);
}
};

View File

@ -18,9 +18,9 @@ pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(arena);
const code = if (job.find(args)) |at|
try job.run(io, arena, args, at, runCommandLine, &stdout_writer.interface, &stderr_writer.interface)
try job.run(io, arena, args, at, runCommandLine, inputFile, &stdout_writer.interface, &stderr_writer.interface)
else
runCommandLine(io, arena, args, &stdout_writer.interface, &stderr_writer.interface);
runCommandLine(io, arena, args, .{}, &stdout_writer.interface, &stderr_writer.interface);
try stdout_writer.interface.flush();
return code;
}
@ -28,19 +28,30 @@ pub fn main(init: std.process.Init) !u8 {
/// Runs one command line (argv[0] first) and returns its exit code, which
/// follows dxc: 1 for command-line and I/O errors, 5 when the compilation
/// reports errors.
fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
return runOrFail(io, arena, argv, stdout, stderr) catch |err| {
fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx: job.Context, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
return runOrFail(io, arena, argv, ctx, stdout, stderr) catch |err| {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
stderr.flush() catch {};
return 1;
};
}
fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
/// The input file a command line (argv[0] first) compiles, if it names one.
fn inputFile(arena: std.mem.Allocator, argv: []const [:0]const u8) ?[]const u8 {
const args = arena.alloc([]const u8, argv.len -| 1) catch return null;
for (args, argv[1..]) |*a, v| a.* = v;
var failure: zdxc.options.Failure = .{};
const parsed = zdxc.options.parse(arena, args, &failure) catch return null;
return if (parsed.inputs.len > 0) parsed.inputs[parsed.inputs.len - 1] else null;
}
fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx: job.Context, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const args = try arena.alloc([]const u8, argv.len -| 1);
for (args, argv[1..]) |*a, v| a.* = v;
const r = try zdxc.compile.compile(arena, .{
.args = args,
.source = ctx.source,
.fs = ctx.fs,
.io = io,
.color = Io.File.stderr().supportsAnsiEscapeCodes(io) catch false,
.require_output = true,
@ -48,17 +59,19 @@ fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdou
try stdout.writeAll(r.text);
try stderr.writeAll(r.diagnostics);
try stderr.flush();
if (r.status != .ok) return @intFromEnum(r.status);
if (r.object) |bytes| try write(io, stderr, r.object_name.?, bytes) orelse return 1;
if (r.root_signature) |bytes| try write(io, stderr, r.root_signature_name.?, bytes) orelse return 1;
if (r.status != .ok) return @backingInt(r.status);
if (r.object) |bytes| try write(io, arena, ctx.outputs, stderr, r.object_name.?, bytes) orelse return 1;
if (r.root_signature) |bytes| try write(io, arena, ctx.outputs, stderr, r.root_signature_name.?, bytes) orelse return 1;
if (r.preprocessed) |text| {
if (r.preprocessed_name) |path| try write(io, stderr, path, text) orelse return 1 else try stdout.writeAll(text);
if (r.preprocessed_name) |path| try write(io, arena, ctx.outputs, stderr, path, text) orelse return 1 else try stdout.writeAll(text);
}
return 0;
}
/// Writes an output file; null (after an error message) if it cannot.
fn write(io: Io, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void {
/// Writes an output file (or adds it to `outputs`); null (after an error
/// message) if it cannot.
fn write(io: Io, arena: std.mem.Allocator, outputs: ?*job.Outputs, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void {
if (outputs) |o| return try o.append(arena, .{ .path = path, .bytes = bytes });
Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }) catch |err| {
try stderr.print("zdxc: error: cannot write '{s}': {s}\n", .{ path, @errorName(err) });
try stderr.flush();

View File

@ -1,8 +1,10 @@
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
//! zdxc: an HLSL 2018 / 2021 compiler targeting DXIL and SPIR-V.
pub const diag = @import("diag.zig");
pub const options = @import("options.zig");
pub const compile = @import("compile.zig");
pub const stats = @import("stats.zig");
pub const BumpArena = @import("BumpArena.zig");
pub const Diagnostics = diag.Diagnostics;
pub const front = struct {
@ -26,6 +28,7 @@ pub const dxil = struct {
pub const signature = @import("dxil/signature.zig");
pub const emit = @import("dxil/emit.zig");
pub const rootsig = @import("dxil/rootsig.zig");
pub const reflect = @import("dxil/reflect.zig");
};
pub const ir = struct {

View File

@ -8,7 +8,8 @@
//! coerced into the group's class (`float_like`, `numeric`, `any_int`...),
//! and the layout is taken from the declared dimensions (binding symbolic
//! sizes like `c` and `r2` across arguments) or, for `<>`, from the
//! arguments. Candidates are ranked by total conversion cost.
//! arguments. Candidates are ranked by their worst conversion, then their
//! total conversion cost.
const std = @import("std");
const Allocator = std.mem.Allocator;
@ -48,6 +49,28 @@ pub const Db = struct {
return db;
}
var shared_db: Db = .{};
/// 0: not built, 1: being built, 2: built.
var shared_state: std.atomic.Value(u8) = .init(0);
/// The Db, built once per process and then shared read-only: it
/// depends only on the generated table, and building it costs thousands
/// of allocations per compile.
pub fn shared() Allocator.Error!*const Db {
while (true) switch (shared_state.load(.acquire)) {
2 => return &shared_db,
0 => if (shared_state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) {
shared_db = init(std.heap.smp_allocator) catch |e| {
shared_state.store(0, .release);
return e;
};
shared_state.store(2, .release);
return &shared_db;
},
else => std.atomic.spinLoopHint(),
};
}
/// `ns` (e.g. `Texture2DMethods`) declares a method `name`.
pub fn hasMethod(db: *const Db, ns: []const u8, name: []const u8) bool {
var buf: [256]u8 = undefined;
@ -69,6 +92,17 @@ pub const Db = struct {
return list.items;
}
/// The conversion cost of the best overload of global intrinsic `name`
/// for `args`, or null if none fits (no diagnostics).
pub fn bestCost(db: *const Db, sema: anytype, name: []const u8, args: []const ArgInfo) !?u32 {
var best: ?u32 = null;
for (try db.candidates(sema.arena, "Intrinsics", name)) |ci| {
const m = try matchOne(sema, &table.intrinsics[ci], null, args, null) orelse continue;
if (best == null or m.cost < best.?) best = m.cost;
}
return best;
}
/// Resolve a call; reports a diagnostic and returns the error type when
/// no overload matches. `sema` is the calling Sema (for conversions and
/// diagnostics); `object` is the method's object type, if any.
@ -78,6 +112,37 @@ pub const Db = struct {
pub const Resolved = struct { ret: TypeId, index: u16 = 0, params: []const TypeId = &.{}, ok: bool = false };
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
// The same call (name, object, explicit type, argument types and
// lvalues) resolves the same way: matched once per compile.
var key_buf: [256]u8 = undefined;
var key: std.ArrayList(u8) = .initBuffer(&key_buf);
const keyed = memoKey(&key, ns, name, object, args, explicit);
if (keyed) if (sema.intrinsic_memo.get(key.items)) |r| return r;
const reported = sema.diags.list.items.len;
const r = try db.resolveUncached(sema, loc, ns, name, object, args, explicit);
// (Not one that reported something: a repeat reports it again.)
if (keyed and r.ok and sema.diags.list.items.len == reported) try sema.intrinsic_memo.put(sema.arena, try sema.arena.dupe(u8, key.items), r);
return r;
}
/// The memo key of a call; false if it does not fit.
fn memoKey(key: *std.ArrayList(u8), ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) bool {
const fixed = ns.len + name.len + 2 + 2 * @sizeOf(TypeId) + args.len * (@sizeOf(TypeId) + 1);
if (fixed > key.capacity) return false;
key.appendSliceAssumeCapacity(ns);
key.appendAssumeCapacity(0);
key.appendSliceAssumeCapacity(name);
key.appendAssumeCapacity(0);
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, object orelse std.math.maxInt(TypeId))));
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, explicit orelse std.math.maxInt(TypeId))));
for (args) |a| {
key.appendSliceAssumeCapacity(std.mem.asBytes(&a.ty));
key.appendAssumeCapacity(@intFromBool(a.lvalue));
}
return true;
}
fn resolveUncached(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
const cands = try db.candidates(sema.arena, ns, name);
if (cands.len == 0) {
if (object) |o| {
@ -132,6 +197,16 @@ const Bindings = struct {
return null;
}
/// Bind `name` to `v` unless it is bound to a smaller value.
fn lower(b: *Bindings, name: []const u8, v: u16) void {
if (std.fmt.parseInt(u16, name, 10)) |_| return else |_| {}
for (b.names[0..b.n], b.values[0..b.n]) |k, *old| if (std.mem.eql(u8, k, name)) {
old.* = @min(old.*, v);
return;
};
_ = b.bind(name, v);
}
/// Bind or check; false on conflict.
fn bind(b: *Bindings, name: []const u8, v: u16) bool {
if (b.get(name)) |old| return old == v;
@ -156,6 +231,7 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
.resource => |r| r.elem,
.stream => |s| s.elem,
.patch => |p| p.elem,
.node => |x| x.elem,
else => TypeTable.error_type,
} else TypeTable.error_type;
@ -188,12 +264,68 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
}
var bindings: Bindings = .{};
// A vector size (`c` of `numeric<c>`) shared by several arguments takes
// the widest of them, scalars splatting to it, as in dxc: `dot(1, v)`
// is a dot product of v's size, not v truncated to a scalar.
{
var syms: [8][]const u8 = undefined;
var widest: [8]u16 = undefined;
var ok: [8]bool = undefined;
var ns: usize = 0;
for (args[0..it.params.len], 1..) |a, i| {
if (!specs[i].any_layout) continue;
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
if (ls.any_layout or ls.dims.len != 1) continue;
const sym = ls.dims[0];
if (std.fmt.parseInt(u16, sym, 10)) |_| continue else |_| {}
const sh = t.shape(a.ty) orelse continue;
const len: u16 = switch (sh.kind) {
.scalar => 1,
.vector => sh.cols,
else => continue,
};
const k = for (syms[0..ns], 0..) |s, j| {
if (std.mem.eql(u8, s, sym)) break j;
} else blk: {
if (ns == syms.len) break :blk null;
syms[ns] = sym;
widest[ns] = len;
ok[ns] = true;
ns += 1;
break :blk ns - 1;
} orelse continue;
// (Vectors of two different sizes: left to the usual binding,
// which converts to the first.)
if (len != 1 and widest[k] != 1 and len != widest[k]) ok[k] = false;
widest[k] = @max(widest[k], len);
}
for (syms[0..ns], widest[0..ns], ok[0..ns]) |s, w, good| if (good and w > 1) {
_ = bindings.bind(s, w);
};
}
for (args[0..it.params.len], 1..) |a, i| {
// (Also arguments whose layout links to a `<>` one.)
if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue;
const sh = t.shape(a.ty) orelse continue;
if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh;
}
var cost: u32 = 0;
// A dimension shared by several arguments (`dot(numeric<c>,
// numeric<c>)`, mul's `numeric<r, c>` and `numeric<c>`) is the
// smallest one: dxc truncates the larger arguments (with a warning).
// Scalars splat and do not bind it.
for (args[0..it.params.len], 1..) |a, i| {
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
const sh = t.shape(a.ty) orelse continue;
switch (ls.dims.len) {
1 => if (sh.kind == .vector) bindings.lower(ls.dims[0], sh.cols),
2 => if (sh.kind == .matrix) {
bindings.lower(ls.dims[0], sh.rows);
bindings.lower(ls.dims[1], sh.cols);
},
else => {},
}
}
var sum: u32 = 0;
var worst: u32 = 0;
const out_params = try sema.arena.alloc(bool, args.len);
@memset(out_params, false);
const param_types = try sema.arena.alloc(TypeId, args.len);
@ -208,13 +340,17 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
param_types[ai] = if (pt == TypeTable.error_type) a.ty else pt;
if (pt == TypeTable.error_type) continue; // unconstrained object / unknown class
const c = sema.conversionCost(a.ty, pt) orelse return null;
cost += c;
// A `ref` argument (InterlockedAdd's destination) is the storage
// itself: its type must match.
if (s.qual == .ref and c != 0) return null;
sum += c;
worst = @max(worst, c);
}
// Return type.
const ret = try paramType(sema, specs, 0, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
for (args[@min(args.len, it.params.len)..], @min(args.len, it.params.len)..) |a, ai| param_types[ai] = a.ty; // varargs
return .{ .ret = ret, .cost = cost, .out_params = out_params, .params = param_types };
return .{ .ret = ret, .cost = Scalar.overloadCost(worst, sum), .out_params = out_params, .params = param_types };
}
/// The concrete type of spec `i`, or null if the arguments cannot fit.
@ -250,6 +386,12 @@ fn paramType(
// Non-numeric classes.
const base = if (cs.special == .none) cs.base else s.base;
// NodeOutput's Get{Thread,Group}NodeOutputRecords: records of the
// output's record type.
if (i == 0 and obj_elem != TypeTable.error_type) {
const records: ?types.NodeKind = if (std.mem.eql(u8, base, "ThreadNodeOutputRecords")) .thread_output_records else if (std.mem.eql(u8, base, "GroupNodeOutputRecords")) .group_output_records else null;
if (records) |k| return try t.intern(.{ .node = .{ .kind = k, .elem = obj_elem } });
}
if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) {
// Objects (samplers are checked) and classes zdxc does not model
// (HitObject, node records, LinAlg...): unconstrained.

View File

@ -25,6 +25,9 @@ pub const Options = struct {
entry: ?[]const u8 = null,
spirv: bool = false,
enable_16bit: bool = false,
/// HLSL 2016-2018 (below 2021): `&&`, `||` and `?:` work component-wise
/// on vectors and evaluate both operands.
hlsl_version: u16 = 2021,
/// Target shader model 6.x (long vectors need 6.9).
sm_minor: u8 = 10,
/// Library target (`lib_6_x`): exported functions are the roots of
@ -86,6 +89,9 @@ pub const Resolution = union(enum) {
/// A bitfield member (`this_bitfield`: named without `this.`).
bitfield: types.Bitfield,
this_bitfield: types.Bitfield,
/// A node object's record: `Get()`, `Get(i)` or `[i]` (lowered as an
/// element of the object).
node_record,
};
pub const Param = struct {
@ -93,6 +99,10 @@ pub const Param = struct {
type: TypeId,
dir: enum { in, out, inout },
has_default: bool,
/// A template instance's default argument that does not convert to
/// the parameter's type: an error only where a call uses it (C++
/// instantiates default arguments on use).
bad_default: bool = false,
/// `groupshared` parameter (SM 6.8 groupshared arguments).
groupshared: bool = false,
};
@ -113,13 +123,20 @@ pub const Function = struct {
param_vars: []?*Variable = &.{},
/// A function template instance's arguments.
template_args: []const Bound = &.{},
/// A method of a class template instance: its body, checked when the
/// method is first called (as C++ instantiates members).
pending: ?*const PendingBody = null,
};
pub const PendingBody = struct { f: *const ast.FuncDecl, scope: *Scope, strct: ?*types.StructInfo };
/// A bound template argument.
pub const Bound = types.TemplateArg;
pub const FuncSet = struct {
funcs: std.ArrayList(*Function) = .empty,
/// Function templates of the same name, overloading with `funcs`.
templates: ?*TemplateSet = null,
};
pub const Symbol = union(enum) {
@ -208,7 +225,9 @@ pub const Sema = struct {
current_block: ?*const ast.Decl = null,
loop_depth: u32 = 0,
switch_depth: u32 = 0,
intrinsic_db: intrinsics.Db,
intrinsic_db: *const intrinsics.Db,
/// Intrinsic calls resolved so far (see Db.resolve).
intrinsic_memo: std.StringHashMapUnmanaged(intrinsics.Db.Resolved) = .empty,
enum_scopes: std.AutoHashMapUnmanaged(*types.EnumInfo, *Scope) = .empty,
/// Where each template was declared (its names resolve from there).
template_scopes: std.AutoHashMapUnmanaged(*const ast.Decl, *Scope) = .empty,
@ -232,7 +251,7 @@ pub const Sema = struct {
.opts = opts,
.global = global,
.scope = global,
.intrinsic_db = try intrinsics.Db.init(arena),
.intrinsic_db = try intrinsics.Db.shared(),
};
try s.declareBuiltins();
return s;
@ -309,8 +328,15 @@ pub const Sema = struct {
const set = blk: {
if (s.scope.syms.get(name)) |sym| switch (sym) {
.template => |t| break :blk t,
// Plain functions take precedence over templates.
.functions => return,
// Function templates overload the plain functions.
.functions => |fs| {
if (d.kind != .func) return;
if (fs.templates == null) {
fs.templates = try s.arena.create(TemplateSet);
fs.templates.?.* = .{};
}
break :blk fs.templates.?;
},
else => {},
};
const set = try s.arena.create(TemplateSet);
@ -740,18 +766,74 @@ pub const Sema = struct {
/// A call to a function template: deduce, instantiate (once per
/// argument list), then resolve as an ordinary call.
fn callTemplate(s: *Sema, e: *ast.Expr, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo) Allocator.Error!TypeId {
// Every overload that deduces contributes its instance.
const all = try s.arena.create(FuncSet);
all.* = .{};
for (tset.decls.items) |d| {
if (d.kind != .func) continue;
const inst = try s.instantiateCall(d, explicit, args, callee, tset.decls.items.len > 1, owner);
if (inst) |set| try all.funcs.appendSlice(s.arena, set.funcs.items);
}
const all = try s.templateInstances(tset, explicit, args, callee, owner, tset.decls.items.len > 1);
if (all.funcs.items.len == 0) {
s.err(callee.loc, "this call to a function template is not supported yet", .{});
return TypeTable.error_type;
}
return s.resolveInstances(e, all, args, callee);
}
/// The instances of `tset`'s function templates that deduce for `args`.
fn templateInstances(s: *Sema, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo, quiet: bool) Allocator.Error!*FuncSet {
const all = try s.arena.create(FuncSet);
all.* = .{};
for (tset.decls.items) |d| {
if (d.kind != .func) continue;
// (Not with too many or too few arguments.)
const ps = d.kind.func.params;
var required: usize = 0;
for (ps) |p| {
if (p.init == null) required += 1;
}
if (args.len > ps.len or args.len < required) continue;
const inst = try s.instantiateCall(d, explicit, args, callee, quiet, owner);
if (inst) |set| try all.funcs.appendSlice(s.arena, set.funcs.items);
}
return all;
}
/// A call to plain functions and function templates of one name: the
/// templates' instances win only by a lower cost (as in C++, a tie goes
/// to the plain function).
fn callOverloads(s: *Sema, e: *ast.Expr, set: *FuncSet, tset: *TemplateSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) Allocator.Error!Typed {
const insts = try s.templateInstances(tset, &.{}, args, callee, null, true);
const both = try s.arena.create(FuncSet);
both.* = .{};
try both.funcs.appendSlice(s.arena, set.funcs.items);
try both.funcs.appendSlice(s.arena, insts.funcs.items);
if (try s.intrinsicFitsBetter(callee, both, args)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], args, &.{});
var plain: ?u32 = null;
for (set.funcs.items) |f| {
const cost = s.callCost(f, args) orelse continue;
if (plain == null or cost < plain.?) plain = cost;
}
var templ: ?u32 = null;
for (insts.funcs.items) |f| {
const cost = s.callCost(f, args) orelse continue;
if (templ == null or cost < templ.?) templ = cost;
}
if (templ != null and (plain == null or templ.? < plain.?)) return rvalue(try s.resolveInstances(e, insts, args, callee));
return rvalue(s.resolveUserCall(e, set, args, callee));
}
/// Whether a call by an intrinsic's name to user functions `set` (or
/// template instances) goes to the intrinsic: when it fits better, or
/// when none of them fits (a tie goes to the user function).
fn intrinsicFitsBetter(s: *Sema, callee: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo) Allocator.Error!bool {
if (callee.kind != .name or callee.kind.name.parts.len != 1) return false;
const name = callee.kind.name.parts[0];
if (!s.intrinsic_db.has(name, s.opts.spirv)) return false;
var user: ?u32 = null;
for (set.funcs.items) |f| {
const cost = s.callCost(f, args) orelse continue;
if (user == null or cost < user.?) user = cost;
}
const ic = try s.intrinsic_db.bestCost(s, name, args) orelse return user == null;
return user == null or ic < user.?;
}
fn resolveInstances(s: *Sema, e: *ast.Expr, all: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) Allocator.Error!TypeId {
// A template declared, then defined: its definition's instance.
var kept: usize = 0;
for (all.funcs.items) |a| {
@ -865,13 +947,26 @@ pub const Sema = struct {
}
fn lookup(s: *Sema, name: []const u8) ?Symbol {
// (The name hashed once, for every scope out to the global one.)
const key: Prehashed = .{ .h = std.hash_map.hashString(name) };
var sc: ?*Scope = s.scope;
while (sc) |c| : (sc = c.parent) {
if (c.syms.get(name)) |sym| return sym;
if (c.syms.getAdapted(name, key)) |sym| return sym;
}
return null;
}
/// A string hash map key context with the hash already worked out.
const Prehashed = struct {
h: u64,
pub fn hash(k: Prehashed, _: []const u8) u64 {
return k.h;
}
pub fn eql(_: Prehashed, a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
};
/// Resolve a possibly qualified name.
fn lookupName(s: *Sema, n: ast.Name) ?Symbol {
return s.lookupNameInst(n) catch null;
@ -1264,6 +1359,18 @@ pub const Sema = struct {
// Any other builtin object (RayQuery, node records, vk:: types...).
// vk::ext_result_id<T>: a T (an inline instruction's result).
if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type;
// Work graph node objects: their record type.
if (types.NodeKind.named(n)) |kind| {
var elem: TypeId = TypeTable.void_type;
if (kind.templated()) {
if (args.len == 0) {
s.err(t.loc, "'{s}' requires a record type template argument", .{n});
return TypeTable.error_type;
}
elem = try s.typeArg(args[0]) orelse return TypeTable.error_type;
}
return s.types.intern(.{ .node = .{ .kind = kind, .elem = elem } });
}
if (isOtherBuiltinObject(n)) {
var elem: TypeId = TypeTable.void_type;
if (eql(n, "RayQuery")) {
@ -1279,6 +1386,14 @@ pub const Sema = struct {
// `S<T>::type` where the instance has no such member (the
// parser cannot tell); other unknown names were reported there.
if (t.name.parts.len > 1 and t.name.args.len > 0) s.err(t.loc, "no type named '{s}' in this template instance", .{n});
// `struct S` before any declaration of S: forward-declares it.
if (t.elaborated and t.name.parts.len == 1 and s.global.syms.get(n) == null) {
const info = try s.arena.create(types.StructInfo);
info.* = .{ .name = n, .scopes = &.{} };
const ty = try s.types.intern(.{ .@"struct" = info });
try s.global.syms.put(s.arena, n, .{ .type = ty });
return ty;
}
return TypeTable.error_type;
}
@ -1452,6 +1567,15 @@ pub const Sema = struct {
// ------------------------------------------------------------------
// Constant evaluation (array sizes, case labels, template arguments)
/// Whether struct `info` was declared with attribute `name` (any case).
pub fn structHasAttr(s: *const Sema, info: *const types.StructInfo, name: []const u8) bool {
_ = s;
const ss: *const StructSema = @ptrCast(@alignCast(info.sema orelse return false));
if (ss.decl.kind != .@"struct") return false;
for (ss.decl.kind.@"struct".attrs) |a| if (std.ascii.eqlIgnoreCase(a.name, name)) return true;
return false;
}
pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 {
return switch (s.evalConst(e) orelse return null) {
.int => |v| v,
@ -2070,6 +2194,13 @@ pub const Sema = struct {
if (last_shader) |kept| {
if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept });
} else last_shader = stage;
} else if (std.ascii.eqlIgnoreCase(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
// (Exactly these: dxc compares case-sensitively.)
const lit = a.args[0].kind.string_lit;
const v = if (lit.len >= 2) lit[1 .. lit.len - 1] else lit;
if (!eql(v, "broadcasting") and !eql(v, "coalescing") and !eql(v, "thread")) {
s.err(a.args[0].loc, "attribute 'NodeLaunch' must have one of these values: broadcasting,coalescing,thread", .{});
}
} else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) {
if (last_wavesize) |kept| {
var same = kept.args.len == a.args.len;
@ -2300,10 +2431,16 @@ pub const Sema = struct {
// Unsized arrays take their size from the initializer.
if (v.init) |init_e| if (!is_auto) {
if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) {
// (Its items typed first: their sizes count.)
_ = try s.checkInitializer(TypeTable.error_type, init_e);
const elem = s.types.get(ty).array.elem;
const elem_count = s.types.componentCount(elem) orelse 1;
const flat = s.flatCount(init_e);
ty = try s.types.array(elem, @intCast(@max(1, (flat + elem_count - 1) / @max(1, elem_count))));
variable.type = ty;
init_e.ty = ty;
if (!s.checkInitCount(ty, init_e)) variable.type = TypeTable.error_type;
return;
}
variable.type = ty;
// Uses of a declaration with a bad initializer are not
@ -2388,22 +2525,33 @@ pub const Sema = struct {
.has_default = p.init != null,
.groupshared = p.quals.groupshared,
};
if (p.init) |init_e| _ = try s.checkInitializer(pt, init_e);
if (p.init) |init_e| {
if (s.instance_depth > 0) {
const m = s.diags.mark();
_ = try s.checkInitializer(pt, init_e);
if (s.diags.error_count != m.errors) {
s.diags.rollback(m);
out.bad_default = true;
}
} else _ = try s.checkInitializer(pt, init_e);
}
}
const func = try s.arena.create(Function);
func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner };
// Add to the overload set, matching an earlier prototype if any.
const set = blk: {
var templates: ?*TemplateSet = null;
if (s.scope.syms.get(name)) |sym| {
if (sym == .functions) break :blk sym.functions;
if (sym != .template) {
s.err(d.loc, "redefinition of '{s}' as a different kind of symbol", .{name});
return;
}
if (sym.template.decls.items.len > 0 and sym.template.decls.items[0].kind == .func) templates = sym.template;
}
const set = try s.arena.create(FuncSet);
set.* = .{};
set.* = .{ .templates = templates };
try s.declare(name, .{ .functions = set }, d.loc);
break :blk set;
};
@ -2525,6 +2673,26 @@ pub const Sema = struct {
}
fn funcBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void {
if (f.body != null and func.owner != null and s.instance_depth > 0 and s.current_fn == null) {
const p = try s.arena.create(PendingBody);
p.* = .{ .f = f, .scope = s.scope, .strct = s.current_struct };
func.pending = p;
return;
}
return s.checkBody(func, f);
}
/// Checks a pending method body (see Function.pending).
fn ensureBody(s: *Sema, func: *Function) Allocator.Error!void {
const p = func.pending orelse return;
func.pending = null;
const ctx = s.enterInstance(p.scope);
defer s.leaveInstance(ctx);
s.current_struct = p.strct;
try s.checkBody(func, p.f);
}
fn checkBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void {
const params = func.params;
const body = f.body orelse return;
const saved_fn = s.current_fn;
@ -2799,7 +2967,36 @@ pub const Sema = struct {
}
}
/// Whether `name` is declared in the current function (its parameters
/// and blocks).
fn inFunctionScope(s: *Sema, name: []const u8) bool {
var sc: ?*Scope = s.scope;
while (sc) |c| : (sc = c.parent) {
if (c.kind != .block and c.kind != .function) return false;
if (c.syms.contains(name)) return true;
if (c.kind == .function) return false;
}
return false;
}
/// A field (or bitfield) of the method's struct named `name`.
fn thisField(s: *Sema, e: *ast.Expr, info: *types.StructInfo, name: []const u8) Allocator.Error!?Typed {
for (info.fields.items, 0..) |f, k| if (std.mem.eql(u8, f.name, name)) {
s.record(e, .{ .this_field = @intCast(k) });
return .{ .ty = f.type, .lvalue = true };
};
if (findBitfield(info, name)) |bf| {
s.record(e, .{ .this_bitfield = bf });
return .{ .ty = bf.type, .lvalue = true };
}
return null;
}
fn nameExpr(s: *Sema, e: *ast.Expr, n: ast.Name) Allocator.Error!Typed {
// Inside methods, fields come before names outside the function.
if (n.parts.len == 1 and s.current_struct != null and !s.inFunctionScope(n.parts[0])) {
if (try s.thisField(e, s.current_struct.?, n.parts[0])) |t| return t;
}
if (s.lookupName(n)) |sym| switch (sym) {
.variable => |v| {
s.record(e, .{ .variable = v });
@ -2827,16 +3024,7 @@ pub const Sema = struct {
}
// Struct fields and methods used unqualified inside methods.
if (s.current_struct) |info| {
if (n.parts.len == 1) {
for (info.fields.items, 0..) |f, k| if (std.mem.eql(u8, f.name, n.parts[0])) {
s.record(e, .{ .this_field = @intCast(k) });
return .{ .ty = f.type, .lvalue = true };
};
if (findBitfield(info, n.parts[0])) |bf| {
s.record(e, .{ .this_bitfield = bf });
return .{ .ty = bf.type, .lvalue = true };
}
}
if (n.parts.len == 1) if (try s.thisField(e, info, n.parts[0])) |t| return t;
}
if (n.parts.len > 1) {
for (n.parts[0 .. n.parts.len - 1], 0..) |part, i| {
@ -3027,6 +3215,10 @@ pub const Sema = struct {
const ls = s.types.shape(lt) orelse return s.invalidOperands(loc, lt, rt);
const rs = s.types.shape(rt) orelse return s.invalidOperands(loc, lt, rt);
if (logical) {
if (s.opts.hlsl_version < 2021 and (ls.kind != .scalar or rs.kind != .scalar)) {
const sh = TypeTable.combineDimensions(ls, rs) orelse return s.invalidOperands(loc, lt, rt);
return try s.types.withShape(.bool, sh);
}
if (ls.kind != .scalar or rs.kind != .scalar) {
s.err(loc, "operands for short-circuiting logical binary operator must be scalar, for non-scalar types use '{s}'", .{if (op == .log_and) "and" else "or"});
return null;
@ -3160,6 +3352,7 @@ pub const Sema = struct {
const c = try s.expr(cond);
const t = try s.expr(then);
const f = try s.expr(else_e);
if (s.opts.hlsl_version < 2021) return s.legacyConditional(e, c, t, f);
if (c.ty != TypeTable.error_type) {
if (s.types.shape(c.ty)) |sh| {
if (sh.kind != .scalar) {
@ -3177,6 +3370,29 @@ pub const Sema = struct {
return err_typed;
}
/// HLSL 2018's `?:`: a vector condition selects per component, and the
/// result takes the shape of all three operands.
fn legacyConditional(s: *Sema, e: *ast.Expr, c: Typed, t: Typed, f: Typed) Allocator.Error!Typed {
if (c.ty == TypeTable.error_type or t.ty == TypeTable.error_type or f.ty == TypeTable.error_type) return err_typed;
const r = if (t.ty == f.ty) t.ty else if (s.types.isNumeric(t.ty) and s.types.isNumeric(f.ty))
s.arithmetic(e, t.ty, f.ty) orelse return err_typed
else {
s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(t.ty), s.typeName(f.ty) });
return err_typed;
};
const cs = s.types.shape(c.ty) orelse return rvalue(r);
if (cs.kind == .scalar) return rvalue(r);
const rs = s.types.shape(r) orelse {
s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(c.ty), s.typeName(r) });
return err_typed;
};
const sh = TypeTable.combineDimensions(cs, rs) orelse {
s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(c.ty), s.typeName(r) });
return err_typed;
};
return rvalue(try s.types.withShape(s.types.component(r).?, sh));
}
/// `sizeof(ty)` plus one, or zero when it has no size: HLSL sizes are
/// tightly packed at scalar alignment. A struct that had errors has
/// size 1, as in clang.
@ -3382,6 +3598,17 @@ pub const Sema = struct {
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
},
.stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } },
.node => |x| {
// Get: the record (records objects); the rest from the
// intrinsics table.
const known = (eql(name, "Get") and x.kind.hasRecords()) or
if (methodNamespace(s.types.get(b.ty))) |ns| s.intrinsic_db.hasMethod(ns, name) else false;
if (!known) {
s.err(name_loc, "no member named '{s}' in '{s}'", .{ name, s.typeName(b.ty) });
return err_typed;
}
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
},
else => {
s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)});
return err_typed;
@ -3425,6 +3652,16 @@ pub const Sema = struct {
};
return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only };
},
.node => |x| {
// Records of a records array; an output of an outputs array.
if (x.kind.isArray()) {
s.record(e, .node_record);
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
}
if (x.kind.outputElement()) |k| return rvalue(try s.types.intern(.{ .node = .{ .kind = k, .elem = x.elem } }));
s.err(e.loc, "type '{s}' does not provide a subscript operator", .{s.typeName(b.ty)});
return err_typed;
},
.resource => |r| {
if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) {
if (r.kind == .other) return err_typed;
@ -3520,7 +3757,13 @@ pub const Sema = struct {
};
for (arg_types) |a| if (a.ty == TypeTable.error_type) return err_typed;
switch (target) {
.functions => |set| return rvalue(s.resolveUserCall(e, set, arg_types, callee)),
.functions => |set| if (set.templates) |tset| {
if (template_args.len > 0) return rvalue(try s.callTemplate(e, tset, template_args, arg_types, callee, null));
return s.callOverloads(e, set, tset, arg_types, callee);
} else {
if (try s.intrinsicFitsBetter(callee, set, arg_types)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], arg_types, template_args);
return rvalue(s.resolveUserCall(e, set, arg_types, callee));
},
.template => |set| {
// A member template called unqualified from a method.
var owner: ?*types.StructInfo = null;
@ -3530,15 +3773,13 @@ pub const Sema = struct {
owner = info;
};
};
if (template_args.len == 0 and owner == null) {
const insts = try s.templateInstances(set, &.{}, arg_types, callee, null, true);
if (try s.intrinsicFitsBetter(callee, insts, arg_types)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], arg_types, template_args);
}
return rvalue(try s.callTemplate(e, set, template_args, arg_types, callee, owner));
},
.intrinsic => |name| {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
return rvalue(r.ret);
},
.intrinsic => |name| return s.intrinsicCall(e, callee, name, arg_types, template_args),
.method => |m| {
switch (s.types.get(m.object)) {
.@"struct" => |info| {
@ -3548,6 +3789,25 @@ pub const Sema = struct {
if (sym != .functions) return err_typed;
return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee));
},
.node => |x| if (eql(m.name, "Get")) {
// The record (`Get(i)`: of several).
const most: usize = if (x.kind.isArray()) 1 else 0;
if (arg_types.len > most) {
s.err(e.loc, "too many arguments to function call, expected at most {d}, have {d}", .{ most, arg_types.len });
return err_typed;
}
if (arg_types.len == 1 and s.conversionCost(arg_types[0].ty, try s.types.scalar(.uint)) == null) {
s.err(e.loc, "no matching member function for call to 'Get'", .{});
return err_typed;
}
s.record(e, .node_record);
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
} else {
const ns = methodNamespace(s.types.get(m.object)) orelse return err_typed;
const r = try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, null);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params, .object = m.object } });
return rvalue(r.ret);
},
else => {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
@ -3592,33 +3852,54 @@ pub const Sema = struct {
return null;
}
fn intrinsicCall(s: *Sema, e: *ast.Expr, callee: *ast.Expr, name: []const u8, arg_types: []const intrinsics.ArgInfo, template_args: []const ast.TemplateArg) Allocator.Error!Typed {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
if (r.ok) {
s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
// `dot(float4, float3)`: the longer argument is truncated.
for (arg_types, r.params[0..@min(arg_types.len, r.params.len)], 0..) |a, pt, i| {
const as = s.types.shape(a.ty) orelse continue;
const ps = s.types.shape(pt) orelse continue;
if (as.kind == .scalar or ps.kind == .scalar or (ps.rows >= as.rows and ps.cols >= as.cols)) continue;
const loc = if (e.kind == .call and i < e.kind.call.args.len) startLoc(e.kind.call.args[i]) else a.loc;
s.warn(loc, "conversion", "implicit truncation of vector type", .{});
}
}
return rvalue(r.ret);
}
/// The cost of calling `f` with `args`, or null if it cannot take them.
fn callCost(s: *Sema, f: *const Function, args: []const intrinsics.ArgInfo) ?u32 {
if (args.len > f.params.len) return null;
var required: usize = 0;
for (f.params) |p| {
if (!p.has_default) required += 1;
}
if (args.len < required) return null;
var sum: u32 = 0;
var worst: u32 = 0;
for (args, 0..) |a, i| {
const p = f.params[i];
var c = s.conversionCost(a.ty, p.type) orelse return null;
// groupshared parameters bind only groupshared arguments
// (and are preferred for them).
if (p.groupshared and !a.groupshared) return null;
if (a.groupshared and !p.groupshared) c += 4;
sum += c;
worst = @max(worst, c);
}
return types.Scalar.overloadCost(worst, sum);
}
/// Overload resolution among user functions by conversion cost.
fn resolveUserCall(s: *Sema, e: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) TypeId {
var best: ?*Function = null;
var best_cost: u32 = std.math.maxInt(u32);
var ambiguous = false;
for (set.funcs.items) |f| {
if (args.len > f.params.len) continue;
var required: usize = 0;
for (f.params) |p| {
if (!p.has_default) required += 1;
}
if (args.len < required) continue;
var cost: u32 = 0;
var ok = true;
for (args, 0..) |a, i| {
const p = f.params[i];
const c = s.conversionCost(a.ty, p.type);
// groupshared parameters bind only groupshared arguments
// (and are preferred for them).
if (c == null or (p.groupshared and !a.groupshared)) {
ok = false;
break;
}
cost += c.?;
if (a.groupshared and !p.groupshared) cost += 1;
}
if (!ok) continue;
const cost = s.callCost(f, args) orelse continue;
if (cost < best_cost) {
best = f;
best_cost = cost;
@ -3639,8 +3920,13 @@ pub const Sema = struct {
s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"});
}
}
for (f.params[@min(args.len, f.params.len)..]) |p| if (p.bad_default) {
s.err(callee.loc, "cannot initialize a parameter of type '{s}' with its default argument", .{s.typeName(p.type)});
return TypeTable.error_type;
};
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
s.record(e, .{ .function = f });
s.ensureBody(f) catch {};
return f.ret;
}
@ -3658,24 +3944,24 @@ pub const Sema = struct {
if (tt == .@"enum" and (tt.@"enum".scoped or ft == .@"enum")) return null; // needs a cast
const fs = s.types.shape(from).?;
const ts = s.types.shape(to).?;
var cost: u32 = if (fc.? == tc.?) 0 else if (fc.?.isLiteral()) 1 else if (fc.?.isFloat() == tc.?.isFloat() and tc.?.rank() > fc.?.rank()) 2 else 3;
var cost: u32 = fc.?.conversionCost(tc.?);
cost += switch (TypeTable.convertDimensions(ts, fs) orelse return null) {
.identity => 0,
.scalar => 1, // float1 -> float
.splat => if (ts.count() == 1) 1 else 4,
.conversion => 6, // vector <-> matrix of the same size
.truncation => if (ts.count() == 1) 10 else 8,
.scalar => 4, // float1 -> float
.splat => if (ts.count() == 1) 4 else 16,
.conversion => 24, // vector <-> matrix of the same size
.truncation => if (ts.count() == 1) 40 else 32,
};
return cost;
}
// A descriptor heap element converts to any resource or sampler.
if (ft == .dynamic_resource and (tt == .resource or tt == .sampler)) return 0;
// Derived structs convert to their bases.
if (ft == .@"struct" and tt == .@"struct" and derivesFrom(ft.@"struct", tt.@"struct")) return 2;
if (ft == .@"struct" and tt == .@"struct" and derivesFrom(ft.@"struct", tt.@"struct")) return 8;
// int -> unscoped enum (dxc accepts it).
if (tt == .@"enum" and !tt.@"enum".scoped and s.types.isNumeric(from) and ft != .@"enum") return 3;
if (tt == .@"enum" and !tt.@"enum".scoped and s.types.isNumeric(from) and ft != .@"enum") return 12;
// ConstantBuffer<S> / TextureBuffer<S> are usable as an S value.
if (ft == .resource and (ft.resource.kind == .constant_buffer or ft.resource.kind == .texture_buffer) and ft.resource.elem == to) return 1;
if (ft == .resource and (ft.resource.kind == .constant_buffer or ft.resource.kind == .texture_buffer) and ft.resource.elem == to) return 4;
return switch (ft) {
.array => |fa| switch (tt) {
.array => |ta| if ((ta.len == fa.len or ta.len == 0) and s.conversionCost(fa.elem, ta.elem) == 0) 0 else null,
@ -3730,18 +4016,7 @@ pub const Sema = struct {
if (item.kind != .init_list) _ = try s.expr(item) else _ = try s.checkInitializer(TypeTable.error_type, item);
}
e.ty = target;
if (target == TypeTable.error_type) return true;
const want = if (s.types.get(target) == .string) 1 else s.types.componentCount(target) orelse return true;
const have = s.flatCount(e);
if (have != want and have != 0) {
if (have < want) {
s.err(e.loc, "too few elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
} else {
s.err(e.loc, "too many elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
}
return false;
}
return true;
return s.checkInitCount(target, e);
}
const t = try s.expr(e);
if (t.callee != null and t.ty == TypeTable.error_type) {
@ -3757,6 +4032,23 @@ pub const Sema = struct {
return false;
}
/// An initializer list (its items typed) has as many components as
/// `target`.
fn checkInitCount(s: *Sema, target: TypeId, e: *ast.Expr) bool {
if (target == TypeTable.error_type) return true;
const want = if (s.types.get(target) == .string) 1 else s.types.componentCount(target) orelse return true;
const have = s.flatCount(e);
if (have != want and have != 0) {
if (have < want) {
s.err(e.loc, "too few elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
} else {
s.err(e.loc, "too many elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
}
return false;
}
return true;
}
/// dxc's err_hlsl_cannot_convert: "implicitly" only when an explicit
/// cast would work.
fn convertError(s: *Sema, loc: Loc, from: TypeId, to: TypeId) void {
@ -3873,6 +4165,9 @@ pub fn parseIntLiteral(text: []const u8) ?i64 {
if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) {
base = 16;
body = digits[2..];
} else if (isBinaryLiteral(digits)) {
base = 2;
body = digits[2..];
} else if (digits.len > 1 and digits[0] == '0') {
base = 8;
body = digits[1..];
@ -3892,6 +4187,11 @@ pub fn parseFloatLiteral(text: []const u8) ?f64 {
/// dxc's `.#INF`): where the suffix starts and whether it is floating.
fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } {
var i: usize = 0;
if (isBinaryLiteral(text)) {
i = 2;
while (i < text.len and (text[i] == '0' or text[i] == '1')) i += 1;
return .{ .end = i, .float = false };
}
const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X');
if (hex) i = 2;
const isDigit = struct {
@ -3920,6 +4220,24 @@ fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = f
return .{ .end = i, .float = float };
}
/// `0b101`: a binary integer literal (clang accepts them in HLSL).
/// Where an expression's text starts (clang's getBeginLoc): `i` in `i.T`.
fn startLoc(e: *const ast.Expr) Loc {
return switch (e.kind) {
.member => |m| startLoc(m.base),
.index => |x| startLoc(x.base),
.binary => |b| startLoc(b.lhs),
.assign => |b| startLoc(b.lhs),
.conditional => |c| startLoc(c.cond),
.call => |c| startLoc(c.callee),
else => e.loc,
};
}
fn isBinaryLiteral(text: []const u8) bool {
return text.len > 2 and text[0] == '0' and (text[1] == 'b' or text[1] == 'B') and (text[2] == '0' or text[2] == '1');
}
/// `f16` / `f32` / `f64` (any case) at the end of a float literal.
fn fixedFloatSuffix(text: []const u8) ?[]const u8 {
if (text.len < 4) return null;
@ -4134,6 +4452,15 @@ fn methodNamespace(t: types.Type) ?[]const u8 {
.constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null,
.other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null,
},
.node => |x| switch (x.kind) {
.empty_input => "EmptyNodeInputMethods",
.rw_dispatch_input => "RWDispatchNodeInputRecordMethods",
.group_input, .rw_group_input => "GroupNodeInputRecordsMethods",
.output => "NodeOutputMethods",
.empty_output => "EmptyNodeOutputMethods",
.thread_output_records, .group_output_records => "GroupOrThreadNodeOutputRecordsMethods",
else => null,
},
else => null,
};
}

View File

@ -97,6 +97,45 @@ pub const Scalar = enum(u8) {
};
}
/// The cost of converting a component from `a` to `b` in overload
/// resolution (lower is better), ordered as dxc ranks them: a literal to
/// its own kind, widening within a kind, then a change of sign, then
/// integer to bool, then narrowing or a change of kind, and integer to
/// float last.
pub fn conversionCost(a: Scalar, b: Scalar) u32 {
if (a == b) return 0;
const l = a.props();
const r = b.props();
if (a.isLiteral()) {
// (An integer literal takes bool before float.)
if (r.p.floating == l.p.floating and b != .bool) return if (r.p.min_precision) 5 else 4;
return if (b == .bool and !l.p.floating) 6 else 7;
}
if (l.p.floating and r.p.floating) {
if (r.bits < l.bits) return 12;
// `half` (32-bit, partial precision) ranks after float.
return if (r.p.partial_precision) 9 else 8;
}
if (a.isInt() and b.isInt()) {
const same_sign = l.p.unsigned == r.p.unsigned;
if (r.bits < l.bits) return if (same_sign and !l.p.unsigned) 10 else 12;
if (same_sign) return 8;
// A change of sign: to signed best at the same width, to
// unsigned best wider.
return if ((r.bits == l.bits) == l.p.unsigned) 9 else 10;
}
// (From 64 bits, bool ranks with the narrowing to 32.)
if (a.isInt() and b == .bool) return if (l.bits <= 32) 11 else if (l.p.unsigned) 12 else 10;
if (a.isInt() and r.p.floating) return 13;
return 12;
}
/// An overload candidate's cost from its arguments' conversion costs:
/// dxc ranks candidates by their worst conversion, then by all of them.
pub fn overloadCost(worst: u32, sum: u32) u32 {
return worst << 16 | @min(sum, 0xffff);
}
/// The component type of a binary operation on `a` and `b`: a port of
/// dxc's CombineBasicTypes.
pub fn combine(a: Scalar, b: Scalar) Scalar {
@ -488,6 +527,110 @@ pub const Type = union(enum) {
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
/// scope)]]` (SM 6.10): an opaque matrix handle.
linalg: LinAlgMatrix,
/// A work graph node input, output or output record object
/// (`DispatchNodeInputRecord<T>`, `NodeOutput<T>`, ...): `elem` is the
/// record type (void for the empty ones).
node: struct { kind: NodeKind, elem: TypeId },
};
/// Work graph node object types, as DXC's NodeIOKind.
pub const NodeKind = enum {
dispatch_input,
rw_dispatch_input,
group_input,
rw_group_input,
thread_input,
rw_thread_input,
empty_input,
output,
output_array,
empty_output,
empty_output_array,
thread_output_records,
group_output_records,
pub const names = [_]struct { []const u8, NodeKind }{
.{ "DispatchNodeInputRecord", .dispatch_input }, .{ "RWDispatchNodeInputRecord", .rw_dispatch_input },
.{ "GroupNodeInputRecords", .group_input }, .{ "RWGroupNodeInputRecords", .rw_group_input },
.{ "ThreadNodeInputRecord", .thread_input }, .{ "RWThreadNodeInputRecord", .rw_thread_input },
.{ "EmptyNodeInput", .empty_input }, .{ "NodeOutput", .output },
.{ "NodeOutputArray", .output_array }, .{ "EmptyNodeOutput", .empty_output },
.{ "EmptyNodeOutputArray", .empty_output_array }, .{ "ThreadNodeOutputRecords", .thread_output_records },
.{ "GroupNodeOutputRecords", .group_output_records },
};
pub fn named(n: []const u8) ?NodeKind {
for (names) |e| if (std.mem.eql(u8, e[0], n)) return e[1];
return null;
}
pub fn name(k: NodeKind) []const u8 {
for (names) |e| if (e[1] == k) return e[0];
unreachable;
}
/// NodeIOFlags: input 0x1, output 0x2, read-write 0x4, empty 0x8,
/// array 0x10; record granularity thread 0x20, group 0x40, dispatch
/// 0x60.
pub fn ioFlags(k: NodeKind) u32 {
return switch (k) {
.dispatch_input => 0x61,
.rw_dispatch_input => 0x65,
.group_input => 0x41,
.rw_group_input => 0x45,
.thread_input => 0x21,
.rw_thread_input => 0x25,
.empty_input => 0x9,
.output => 0x6,
.output_array => 0x16,
.empty_output => 0xA,
.empty_output_array => 0x1A,
.thread_output_records => 0x26,
.group_output_records => 0x46,
};
}
pub fn isInput(k: NodeKind) bool {
return k.ioFlags() & 1 != 0;
}
/// Objects holding records (Get and, for the group ones, indexing).
pub fn hasRecords(k: NodeKind) bool {
return switch (k) {
.dispatch_input, .rw_dispatch_input, .group_input, .rw_group_input, .thread_input, .rw_thread_input, .thread_output_records, .group_output_records => true,
else => false,
};
}
/// Several records: `Get(i)` and `[i]` (dxc's IsArray).
pub fn isArray(k: NodeKind) bool {
return switch (k) {
.group_input, .rw_group_input, .thread_output_records, .group_output_records => true,
else => false,
};
}
/// An array of outputs: `[i]` is one.
pub fn outputElement(k: NodeKind) ?NodeKind {
return switch (k) {
.output_array => .output,
.empty_output_array => .empty_output,
else => null,
};
}
/// Records that may be written.
pub fn writable(k: NodeKind) bool {
return k.ioFlags() & 4 != 0 and k.hasRecords();
}
/// Whether the type takes a record type argument.
pub fn templated(k: NodeKind) bool {
return switch (k) {
.empty_input, .empty_output, .empty_output_array => false,
else => true,
};
}
};
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
@ -496,7 +639,9 @@ pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u3
pub const TypeTable = struct {
gpa: Allocator,
types: std.ArrayList(Type) = .empty,
map: std.AutoHashMapUnmanaged(Key, TypeId) = .empty,
map: std.HashMapUnmanaged(Key, TypeId, KeyContext, std.hash_map.default_max_load_percentage) = .empty,
/// scalar's results.
scalars: [@typeInfo(Scalar).@"enum".field_names.len]TypeId = @splat(std.math.maxInt(TypeId)),
pub const error_type: TypeId = 0;
pub const void_type: TypeId = 1;
@ -504,6 +649,23 @@ pub const TypeTable = struct {
/// Hashable identity of structural types.
const Key = struct { tag: u8, a: u64, b: u64 };
/// Hashes a Key's words (it has padding, which the automatic context
/// hashes around field by field).
const KeyContext = struct {
fn mix(x: u64) u64 {
var z = x;
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
return z ^ (z >> 31);
}
pub fn hash(_: KeyContext, k: Key) u64 {
return mix(k.a ^ mix(k.b ^ @as(u64, k.tag) << 56));
}
pub fn eql(_: KeyContext, x: Key, y: Key) bool {
return x.tag == y.tag and x.a == y.a and x.b == y.b;
}
};
pub fn init(gpa: Allocator) !TypeTable {
var t: TypeTable = .{ .gpa = gpa };
try t.types.append(gpa, .@"error");
@ -539,6 +701,7 @@ pub const TypeTable = struct {
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
.linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
.node => |x| .{ .tag = 17, .a = @backingInt(x.kind), .b = x.elem },
};
}
@ -552,7 +715,9 @@ pub const TypeTable = struct {
}
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
return t.intern(.{ .scalar = s });
const k = @backingInt(s);
if (t.scalars[k] == std.math.maxInt(TypeId)) t.scalars[k] = try t.intern(.{ .scalar = s });
return t.scalars[k];
}
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
@ -718,6 +883,7 @@ pub const TypeTable = struct {
.triangle => "TriangleStream",
}, try t.format(gpa, s.elem), ""),
.patch => |p| templateName(gpa, if (p.output) "OutputPatch" else "InputPatch", try t.format(gpa, p.elem), try std.fmt.allocPrint(gpa, ", {d}", .{p.count})),
.node => |x| if (x.kind.templated()) templateName(gpa, x.kind.name(), try t.format(gpa, x.elem), "") else x.kind.name(),
.descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap",
.dynamic_resource => "<dynamic resource>",
.texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) {

View File

@ -10,6 +10,7 @@ pub const Id = u32;
pub const Op = enum(u16) {
undef = 1,
source = 3,
string = 7,
name = 5,
member_name = 6,
extension = 10,
@ -259,6 +260,8 @@ pub const Section = enum {
memory_model,
entry_points,
execution_modes,
/// OpString (before OpSource and the names).
debug_strings,
debug_names,
annotations,
types_globals,

View File

@ -4,6 +4,7 @@
//! (binding = register number, descriptor set = register space).
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const ir = @import("../ir/ir.zig");
const types = @import("../sema/types.zig");
@ -142,7 +143,7 @@ pub const TargetEnv = struct {
};
pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics, env: TargetEnv) Error![]u8 {
var arena_state = std.heap.ArenaAllocator.init(gpa);
var arena_state = BumpArena.init(gpa);
defer arena_state.deinit();
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal, .vk = m.vk };
defer e.b.deinit();
@ -201,6 +202,10 @@ const Emitter = struct {
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
ext_imports: std.StringHashMapUnmanaged(Id) = .empty,
string_ids: std.StringHashMapUnmanaged(Id) = .empty,
/// Reads of resource locals nothing assigns: the resource of the same
/// type each stands in with where it is used.
undef_resources: std.AutoHashMapUnmanaged(u32, Id) = .empty,
/// Flattened resource arrays: a variable per element.
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
flat_iface: std.ArrayList(Id) = .empty,
@ -836,12 +841,30 @@ const Emitter = struct {
.value => |r| e.val(r),
.literal => |w| w,
.type => |t| try e.typeId(t),
.string => |str| try e.stringId(str),
});
const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode)));
try e.b.emit(.functions, op, words.items);
return id;
}
/// A declared resource global of type `ty`.
fn anyGlobalOf(e: *Emitter, ty: TypeId) ?u32 {
for (e.m.globals.items, 0..) |g, gi| {
if (g.ty == ty and g.space == .resource and e.global_vars[gi] != 0) return @intCast(gi);
}
return null;
}
/// An OpString of `str` (made once).
fn stringId(e: *Emitter, str: []const u8) Error!Id {
if (e.string_ids.get(str)) |id| return id;
const id = e.b.newId();
try e.b.emitWithString(.debug_strings, .string, &.{id}, str, &.{});
try e.string_ids.put(e.arena, str, id);
return id;
}
/// An OpExtInstImport of `name` (made once).
fn extInstImport(e: *Emitter, name: []const u8) Error!Id {
if (std.mem.eql(u8, name, "GLSL.std.450")) {
@ -1088,6 +1111,7 @@ const Emitter = struct {
.miss => 5317,
.callable => 5318,
.library => return e.unsupported("library targets are not supported", .{}),
.node => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}),
};
const wrapper = e.func_ids[entry.wrapper];
const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name;
@ -2371,7 +2395,9 @@ const Emitter = struct {
}
fn val(e: *Emitter, r: Ref) Id {
return e.vals[r.index()];
const v = e.vals[r.index()];
if (v == 0) if (e.undef_resources.get(r.index())) |stand_in| return stand_in;
return v;
}
fn compOf(e: *Emitter, ty: TypeId) Scalar {
@ -2384,6 +2410,7 @@ const Emitter = struct {
const ri = r.index();
switch (i.op) {
.constant, .param, .local_var => {},
.node_io => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}),
.spec_constant => |k| e.vals[ri] = try e.specConstant(k),
.spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty),
.ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {
@ -2435,7 +2462,28 @@ const Emitter = struct {
try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform });
return;
}
if (e.val(p) == 0 and f.inst(p).op == .local_var) return e.unsupported("a resource local read before it is assigned", .{});
if (e.val(p) == 0 and f.inst(p).op == .local_var) {
// A resource local nothing assigns (a struct copied
// with a resource member left unset, read where dxc's
// legalization folds the read away): its value is
// undefined, so any resource of its type will do.
// An OpUndef pointer would break logical addressing.
// Copies (`res = this`) pass the undefined value on
// without assigning it; the first real use takes the
// stand-in.
const only_copies = for (f.insts.items) |x| {
if (x.op != .store or x.op.store.ptr != p) continue;
const v = f.inst(x.op.store.value);
if (v.op != .load or f.inst(v.op.load).op != .local_var) break false;
} else true;
if (only_copies) if (e.anyGlobalOf(i.ty)) |g| {
if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]);
e.vals[ri] = 0;
try e.undef_resources.put(e.arena, @intCast(ri), e.global_vars[g]);
return;
};
return e.unsupported("a resource local read before it is assigned", .{});
}
e.vals[ri] = e.val(p);
return;
}
@ -2472,6 +2520,8 @@ const Emitter = struct {
}
return;
}
// Copying an undefined resource assigns nothing.
if (target.op == .local_var and e.undef_resources.contains(s.value.index())) return;
if (target.op == .local_var and isResourceType(e.t, target.ty)) {
const old = e.vals[s.ptr.index()];
if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{});
@ -4275,12 +4325,20 @@ const Emitter = struct {
}
fn globalOf(e: *Emitter, r: Ref) ?u32 {
return e.globalOfDepth(r, 0);
}
/// (Copies between resource locals can form cycles: give up after
/// `max_depth` steps.)
fn globalOfDepth(e: *Emitter, r: Ref, depth: u32) ?u32 {
const max_depth = 256;
if (depth > max_depth) return null;
const i = e.f.inst(r);
return switch (i.op) {
.global => |g| g,
.load => |p| e.globalOf(p),
.load => |p| e.globalOfDepth(p, depth + 1),
.local_var => for (e.f.insts.items) |inst| {
if (inst.op == .store and inst.op.store.ptr == r) break e.globalOf(inst.op.store.value);
if (inst.op == .store and inst.op.store.ptr == r) break e.globalOfDepth(inst.op.store.value, depth + 1);
} else null,
// A specialized parameter: the global it is bound to.
.param => |pi| blk: {

102
src/stats.zig Normal file
View File

@ -0,0 +1,102 @@
//! Time and allocations per compilation stage, for benchmarks. A caller
//! that wants them points `current` at a `Stats` for the thread's
//! compilation; zones anywhere in the compiler then add to it. With no
//! `Stats` (the default) a zone costs one thread-local load.
const std = @import("std");
pub const Stage = enum {
/// Command-line options and setup.
args,
/// Preprocessing and lexing, up to a token array.
preprocess,
parse,
sema,
lower,
ir_opt,
/// DXIL emission, in all (the zones below are inside it).
dxil,
/// Lowering the entry's IR to DXIL instructions (inlining every call).
dxil_lower,
/// Renumbering a function's instructions into its body.
dxil_finish,
promote,
sccp,
unroll,
cse,
/// Block merging, bypassing and if-conversion (dxil/cfg.zig).
cfg,
bitcode,
container,
spirv,
/// Diagnostics rendering and the rest of `compile`.
other,
};
pub const count = @typeInfo(Stage).@"enum".field_names.len;
/// Sizes of the work, to explain the times.
pub const Counter = enum {
/// DXIL instructions lowering produced (before any optimization).
dxil_lowered,
/// DXIL instructions left in the emitted functions.
dxil_final,
/// Times promotion ran.
promote_runs,
};
pub const counter_count = @typeInfo(Counter).@"enum".field_names.len;
/// What the caller's allocator counters read at a point (the caller's
/// `sample` fills it in).
pub const Sample = struct { calls: u64 = 0, bytes: u64 = 0 };
pub const Stats = struct {
io: std.Io,
ns: [count]u64 = @splat(0),
/// Allocation calls and bytes requested in each stage.
calls: [count]u64 = @splat(0),
bytes: [count]u64 = @splat(0),
/// Times each zone was entered.
entries: [count]u32 = @splat(0),
counters: [counter_count]u64 = @splat(0),
sample: ?*const fn (ctx: ?*anyopaque) Sample = null,
sample_ctx: ?*anyopaque = null,
fn read(s: *const Stats) Sample {
return if (s.sample) |f| f(s.sample_ctx) else .{};
}
};
pub threadlocal var current: ?*Stats = null;
pub const Zone = struct {
stage: Stage,
t0: i96 = 0,
s0: Sample = .{},
on: bool = false,
/// Ends the zone, adding its time and allocations to its stage
/// (inclusive of zones nested in it).
pub fn end(z: Zone) void {
if (!z.on) return;
const s = current orelse return;
const t1 = std.Io.Clock.awake.now(s.io).toNanoseconds();
const s1 = s.read();
const k = @backingInt(z.stage);
s.ns[k] += @intCast(t1 - z.t0);
s.calls[k] += s1.calls - z.s0.calls;
s.bytes[k] += s1.bytes - z.s0.bytes;
s.entries[k] += 1;
}
};
/// Adds `n` to a counter.
pub fn add(c: Counter, n: u64) void {
if (current) |s| s.counters[@backingInt(c)] += n;
}
pub fn begin(stage: Stage) Zone {
const s = current orelse return .{ .stage = stage };
return .{ .stage = stage, .t0 = std.Io.Clock.awake.now(s.io).toNanoseconds(), .s0 = s.read(), .on = true };
}